_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q173300
OServerCommandPostAuthToken.authenticate
test
protected String authenticate(final String username, final String password, final String iDatabaseName) throws IOException { ODatabaseDocument db = null; String userRid = null; try { db = (ODatabaseDocument) server.openDatabase(iDatabaseName, username, password); userRid = (db.getUser() == null ? "<server user>" : db.getUser().getDocument().getIdentity().toString()); } catch (OSecurityAccessException e) { // WRONG USER/PASSWD } catch (OLockException e) { OLogManager.instance().error(this, "Cannot access to the database '" + iDatabaseName + "'", e); } finally { if (db != null) { db.close(); } } return userRid; }
java
{ "resource": "" }
q173301
ODocumentHelper.getMapEntry
test
@SuppressWarnings("unchecked") public static Object getMapEntry(final Map<String, ?> iMap, final Object iKey) { if (iMap == null || iKey == null) return null; if (iKey instanceof String) { String iName = (String) iKey; int pos = iName.indexOf('.'); if (pos > -1) iName = iName.substring(0, pos); final Object value = iMap.get(iName); if (value == null) return null; if (pos > -1) { final String restFieldName = iName.substring(pos + 1); if (value instanceof ODocument) return getFieldValue(value, restFieldName); else if (value instanceof Map<?, ?>) return getMapEntry((Map<String, ?>) value, restFieldName); } return value; } else return iMap.get(iKey); }
java
{ "resource": "" }
q173302
OIdentifiableIterator.getRecord
test
protected ORecord getRecord() { final ORecord record; if (reusedRecord != null) { // REUSE THE SAME RECORD AFTER HAVING RESETTED IT record = reusedRecord; record.reset(); } else record = null; return record; }
java
{ "resource": "" }
q173303
OIdentifiableIterator.readCurrentRecord
test
protected ORecord readCurrentRecord(ORecord iRecord, final int iMovement) { if (limit > -1 && browsedRecords >= limit) // LIMIT REACHED return null; do { final boolean moveResult; switch (iMovement) { case 1: moveResult = nextPosition(); break; case -1: moveResult = prevPosition(); break; case 0: moveResult = checkCurrentPosition(); break; default: throw new IllegalStateException("Invalid movement value : " + iMovement); } if (!moveResult) return null; try { if (iRecord != null) { ORecordInternal.setIdentity(iRecord, new ORecordId(current.getClusterId(), current.getClusterPosition())); iRecord = database.load(iRecord, fetchPlan, false); } else iRecord = database.load(current, fetchPlan, false); } catch (ODatabaseException e) { if (Thread.interrupted() || database.isClosed()) // THREAD INTERRUPTED: RETURN throw e; if (e.getCause() instanceof OSecurityException) throw e; brokenRIDs.add(current.copy()); OLogManager.instance().error(this, "Error on fetching record during browsing. The record has been skipped", e); } if (iRecord != null) { browsedRecords++; return iRecord; } } while (iMovement != 0); return null; }
java
{ "resource": "" }
q173304
OrientGraphFactory.getTx
test
public OrientGraph getTx() { final OrientGraph g; if (pool == null) { g = (OrientGraph) getTxGraphImplFactory().getGraph(getDatabase(), user, password, settings); } else { // USE THE POOL g = (OrientGraph) getTxGraphImplFactory().getGraph(pool, settings); } initGraph(g); return g; }
java
{ "resource": "" }
q173305
OrientGraphFactory.getNoTx
test
public OrientGraphNoTx getNoTx() { final OrientGraphNoTx g; if (pool == null) { g = (OrientGraphNoTx) getNoTxGraphImplFactory().getGraph(getDatabase(), user, password, settings); } else { // USE THE POOL g = (OrientGraphNoTx) getNoTxGraphImplFactory().getGraph(pool, settings); } initGraph(g); return g; }
java
{ "resource": "" }
q173306
OrientGraphFactory.setupPool
test
public OrientGraphFactory setupPool(final int iMin, final int iMax) { if (pool != null) { pool.close(); } pool = new OPartitionedDatabasePool(url, user, password, 8, iMax).setAutoCreate(true); properties.entrySet().forEach(p -> pool.setProperty(p.getKey(), p.getValue())); return this; }
java
{ "resource": "" }
q173307
OrientGraphFactory.getProperty
test
public Object getProperty(final String iName) { return properties.get(iName.toLowerCase(Locale.ENGLISH)); }
java
{ "resource": "" }
q173308
OrientTransactionalGraph.stopTransaction
test
@SuppressWarnings("deprecation") @Override public void stopTransaction(final Conclusion conclusion) { makeActive(); if (getDatabase().isClosed() || getDatabase().getTransaction() instanceof OTransactionNoTx || getDatabase().getTransaction().getStatus() != TXSTATUS.BEGUN) return; if (Conclusion.SUCCESS == conclusion) commit(); else rollback(); }
java
{ "resource": "" }
q173309
OrientSql.parse
test
final public OStatement parse() throws ParseException { /*@bgen(jjtree) parse */ Oparse jjtn000 = new Oparse(JJTPARSE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1));OStatement result; try { result = Statement(); jj_consume_token(0); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetLastToken(getToken(0)); {if (true) return result;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } throw new Error("Missing return statement in function"); }
java
{ "resource": "" }
q173310
OrientSql.getNextToken
test
final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; return token; }
java
{ "resource": "" }
q173311
OrientSql.getToken
test
final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; }
java
{ "resource": "" }
q173312
OrientSql.generateParseException
test
public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[279]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 424; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } if ((jj_la1_2[i] & (1<<j)) != 0) { la1tokens[64+j] = true; } if ((jj_la1_3[i] & (1<<j)) != 0) { la1tokens[96+j] = true; } if ((jj_la1_4[i] & (1<<j)) != 0) { la1tokens[128+j] = true; } if ((jj_la1_5[i] & (1<<j)) != 0) { la1tokens[160+j] = true; } if ((jj_la1_6[i] & (1<<j)) != 0) { la1tokens[192+j] = true; } if ((jj_la1_7[i] & (1<<j)) != 0) { la1tokens[224+j] = true; } if ((jj_la1_8[i] & (1<<j)) != 0) { la1tokens[256+j] = true; } } } } for (int i = 0; i < 279; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } jj_endpos = 0; jj_rescan_token(); jj_add_error_token(0, 0); int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); }
java
{ "resource": "" }
q173313
OrientVertex.getVertices
test
@Override public Iterable<Vertex> getVertices(final Direction iDirection, final String... iLabels) { setCurrentGraphInThreadLocal(); OrientBaseGraph.getEdgeClassNames(getGraph(), iLabels); OrientBaseGraph.encodeClassNames(iLabels); final ODocument doc = getRecord(); final OMultiCollectionIterator<Vertex> iterable = new OMultiCollectionIterator<Vertex>(); for (OTriple<String, Direction, String> connectionField : getConnectionFields(iDirection, iLabels)) { String fieldName = connectionField.getKey(); OPair<Direction, String> connection = connectionField.getValue(); final Object fieldValue = doc.rawField(fieldName); if (fieldValue != null) if (fieldValue instanceof OIdentifiable) { addSingleVertex(doc, iterable, fieldName, connection, fieldValue, iLabels); } else if (fieldValue instanceof Collection<?>) { Collection<?> coll = (Collection<?>) fieldValue; if (coll.size() == 1) { // SINGLE ITEM: AVOID CALLING ITERATOR if (coll instanceof ORecordLazyMultiValue) addSingleVertex(doc, iterable, fieldName, connection, ((ORecordLazyMultiValue) coll).rawIterator().next(), iLabels); else if (coll instanceof List<?>) addSingleVertex(doc, iterable, fieldName, connection, ((List<?>) coll).get(0), iLabels); else addSingleVertex(doc, iterable, fieldName, connection, coll.iterator().next(), iLabels); } else { // CREATE LAZY Iterable AGAINST COLLECTION FIELD if (coll instanceof ORecordLazyMultiValue) iterable.add(new OrientVertexIterator(this, coll, ((ORecordLazyMultiValue) coll).rawIterator(), connection, iLabels, coll.size())); else iterable.add(new OrientVertexIterator(this, coll, coll.iterator(), connection, iLabels, -1)); } } else if (fieldValue instanceof ORidBag) { iterable.add(new OrientVertexIterator(this, fieldValue, ((ORidBag) fieldValue).rawIterator(), connection, iLabels, -1)); } } return iterable; }
java
{ "resource": "" }
q173314
OrientVertex.remove
test
@Override public void remove() { checkClass(); final OrientBaseGraph graph = checkIfAttached(); graph.setCurrentGraphInThreadLocal(); graph.autoStartTransaction(); final ODocument doc = getRecord(); if (doc == null) throw ExceptionFactory.vertexWithIdDoesNotExist(this.getId()); Map<String, List<ODocument>> treeRidbagEdgesToRemove = new HashMap<String, List<ODocument>>(); if (!graph.getRawGraph().getTransaction().isActive()) { for (String fieldName : doc.fieldNames()) { final OPair<Direction, String> connection = getConnection(Direction.BOTH, fieldName); if (connection == null) // SKIP THIS FIELD continue; Object fv = doc.field(fieldName); if (fv instanceof ORidBag && !((ORidBag) fv).isEmbedded()) { List<ODocument> docs = new ArrayList<ODocument>(); for (OIdentifiable id : (ORidBag) fv) docs.add(OrientBaseGraph.getDocument(id, true)); treeRidbagEdgesToRemove.put(fieldName, docs); } } } // REMOVE THE VERTEX RECORD FIRST TO CATCH CME BEFORE EDGES ARE REMOVED super.removeRecord(); // REMOVE THE VERTEX FROM MANUAL INDEXES final Iterator<Index<? extends Element>> it = graph.getIndices().iterator(); if (it.hasNext()) { final Set<Edge> allEdges = new HashSet<Edge>(); for (Edge e : getEdges(Direction.BOTH)) allEdges.add(e); while (it.hasNext()) { final Index<? extends Element> index = it.next(); if (Vertex.class.isAssignableFrom(index.getIndexClass())) { OrientIndex<OrientVertex> idx = (OrientIndex<OrientVertex>) index; idx.removeElement(this); } if (Edge.class.isAssignableFrom(index.getIndexClass())) { OrientIndex<OrientEdge> idx = (OrientIndex<OrientEdge>) index; for (Edge e : allEdges) idx.removeElement((OrientEdge) e); } } } for (Map.Entry<String, List<ODocument>> entry : treeRidbagEdgesToRemove.entrySet()) { doc.removeField(entry.getKey()); Iterator<ODocument> iter = entry.getValue().iterator(); while (iter.hasNext()) { ODocument docEdge = iter.next(); OrientBaseGraph.deleteEdgeIfAny(docEdge, false); } } graph.removeEdgesInternal(this, doc, null, true, settings.isUseVertexFieldsForEdgeLabels(), settings.isAutoScaleEdgeType()); }
java
{ "resource": "" }
q173315
OrientVertex.addEdge
test
@Override public Edge addEdge(final String label, Vertex inVertex) { if (inVertex instanceof PartitionVertex) // WRAPPED: GET THE BASE VERTEX inVertex = ((PartitionVertex) inVertex).getBaseVertex(); return addEdge(label, (OrientVertex) inVertex, null, null, (Object[]) null); }
java
{ "resource": "" }
q173316
OrientVertex.addEdge
test
public OrientEdge addEdge(final String label, final OrientVertex inVertex, final String iClassName) { return addEdge(label, inVertex, iClassName, null, (Object[]) null); }
java
{ "resource": "" }
q173317
OrientVertex.getConnectionClass
test
public String getConnectionClass(final Direction iDirection, final String iFieldName) { if (iDirection == Direction.OUT) { if (iFieldName.length() > CONNECTION_OUT_PREFIX.length()) return iFieldName.substring(CONNECTION_OUT_PREFIX.length()); } else if (iDirection == Direction.IN) { if (iFieldName.length() > CONNECTION_IN_PREFIX.length()) return iFieldName.substring(CONNECTION_IN_PREFIX.length()); } return OrientEdgeType.CLASS_NAME; }
java
{ "resource": "" }
q173318
OrientVertex.getConnection
test
protected OPair<Direction, String> getConnection(final Direction iDirection, final String iFieldName, String... iClassNames) { if (iClassNames != null && iClassNames.length == 1 && iClassNames[0].equalsIgnoreCase("E")) // DEFAULT CLASS, TREAT IT AS NO CLASS/LABEL iClassNames = null; final OrientBaseGraph graph = getGraph(); if (iDirection == Direction.OUT || iDirection == Direction.BOTH) { if (settings.isUseVertexFieldsForEdgeLabels()) { // FIELDS THAT STARTS WITH "out_" if (iFieldName.startsWith(CONNECTION_OUT_PREFIX)) { String connClass = getConnectionClass(Direction.OUT, iFieldName); if (iClassNames == null || iClassNames.length == 0) return new OPair<Direction, String>(Direction.OUT, connClass); // CHECK AGAINST ALL THE CLASS NAMES OrientEdgeType edgeType = graph.getEdgeType(connClass); if (edgeType != null) { for (String clsName : iClassNames) { if (edgeType.isSubClassOf(clsName)) return new OPair<Direction, String>(Direction.OUT, connClass); } } } } else if (iFieldName.equals(OrientBaseGraph.CONNECTION_OUT)) // CHECK FOR "out" return new OPair<Direction, String>(Direction.OUT, null); } if (iDirection == Direction.IN || iDirection == Direction.BOTH) { if (settings.isUseVertexFieldsForEdgeLabels()) { // FIELDS THAT STARTS WITH "in_" if (iFieldName.startsWith(CONNECTION_IN_PREFIX)) { String connClass = getConnectionClass(Direction.IN, iFieldName); if (iClassNames == null || iClassNames.length == 0) return new OPair<Direction, String>(Direction.IN, connClass); // CHECK AGAINST ALL THE CLASS NAMES OrientEdgeType edgeType = graph.getEdgeType(connClass); if (edgeType != null) { for (String clsName : iClassNames) { if (edgeType.isSubClassOf(clsName)) return new OPair<Direction, String>(Direction.IN, connClass); } } } } else if (iFieldName.equals(OrientBaseGraph.CONNECTION_IN)) // CHECK FOR "in" return new OPair<Direction, String>(Direction.IN, null); } // NOT FOUND return null; }
java
{ "resource": "" }
q173319
ODatabaseImport.processBrokenRids
test
private void processBrokenRids(Set<ORID> brokenRids) throws IOException, ParseException { if (exporterVersion >= 12) { listener.onMessage("Reading of set of RIDs of records which were detected as broken during database export\n"); jsonReader.readNext(OJSONReader.BEGIN_COLLECTION); while (true) { jsonReader.readNext(OJSONReader.NEXT_IN_ARRAY); final ORecordId recordId = new ORecordId(jsonReader.getValue()); brokenRids.add(recordId); if (jsonReader.lastChar() == ']') break; } } if (migrateLinks) { if (exporterVersion >= 12) listener.onMessage( brokenRids.size() + " were detected as broken during database export, links on those records will be removed from" + " result database"); migrateLinksInImportedDocuments(brokenRids); } }
java
{ "resource": "" }
q173320
OConsoleApplication.getConsoleMethods
test
protected Map<Method, Object> getConsoleMethods() { if (methods != null) return methods; // search for declared command collections final Iterator<OConsoleCommandCollection> ite = ServiceLoader.load(OConsoleCommandCollection.class).iterator(); final Collection<Object> candidates = new ArrayList<Object>(); candidates.add(this); while (ite.hasNext()) { try { // make a copy and set it's context final OConsoleCommandCollection cc = ite.next().getClass().newInstance(); cc.setContext(this); candidates.add(cc); } catch (InstantiationException ex) { Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } catch (IllegalAccessException ex) { Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } } methods = new TreeMap<Method, Object>(new Comparator<Method>() { public int compare(Method o1, Method o2) { final ConsoleCommand ann1 = o1.getAnnotation(ConsoleCommand.class); final ConsoleCommand ann2 = o2.getAnnotation(ConsoleCommand.class); if (ann1 != null && ann2 != null) { if (ann1.priority() != ann2.priority()) // PRIORITY WINS return ann1.priority() - ann2.priority(); } int res = o1.getName().compareTo(o2.getName()); if (res == 0) res = o1.toString().compareTo(o2.toString()); return res; } }); for (final Object candidate : candidates) { final Method[] classMethods = candidate.getClass().getMethods(); for (Method m : classMethods) { if (Modifier.isAbstract(m.getModifiers()) || Modifier.isStatic(m.getModifiers()) || !Modifier.isPublic(m.getModifiers())) { continue; } if (m.getReturnType() != Void.TYPE) { continue; } methods.put(m, candidate); } } return methods; }
java
{ "resource": "" }
q173321
ODistributedAbstractPlugin.executeOnLocalNode
test
@Override public Object executeOnLocalNode(final ODistributedRequestId reqId, final ORemoteTask task, final ODatabaseDocumentInternal database) { if (database != null && !(database.getStorage() instanceof ODistributedStorage)) throw new ODistributedException( "Distributed storage was not installed for database '" + database.getName() + "'. Implementation found: " + database .getStorage().getClass().getName()); final ODistributedAbstractPlugin manager = this; return OScenarioThreadLocal.executeAsDistributed(new Callable<Object>() { @Override public Object call() throws Exception { try { final Object result = task.execute(reqId, serverInstance, manager, database); if (result instanceof Throwable && !(result instanceof OException)) // EXCEPTION ODistributedServerLog.debug(this, nodeName, getNodeNameById(reqId.getNodeId()), DIRECTION.IN, "Error on executing request %d (%s) on local node: ", (Throwable) result, reqId, task); else { // OK final String sourceNodeName = task.getNodeSource(); if (database != null) { final ODistributedDatabaseImpl ddb = getMessageService().getDatabase(database.getName()); if (ddb != null && !(result instanceof Throwable) && task instanceof OAbstractReplicatedTask && !task .isIdempotent()) { // UPDATE LSN WITH LAST OPERATION ddb.setLSN(sourceNodeName, ((OAbstractReplicatedTask) task).getLastLSN(), true); // UPDATE LSN WITH LAST LOCAL OPERATION ddb.setLSN(getLocalNodeName(), ((OAbstractPaginatedStorage) database.getStorage().getUnderlying()).getLSN(), true); } } } return result; } catch (InterruptedException e) { // IGNORE IT ODistributedServerLog.debug(this, nodeName, getNodeNameById(reqId.getNodeId()), DIRECTION.IN, "Interrupted execution on executing distributed request %s on local node: %s", e, reqId, task); return e; } catch (Exception e) { if (!(e instanceof OException)) ODistributedServerLog.error(this, nodeName, getNodeNameById(reqId.getNodeId()), DIRECTION.IN, "Error on executing distributed request %s on local node: %s", e, reqId, task); return e; } } }); }
java
{ "resource": "" }
q173322
ODistributedAbstractPlugin.getNodesWithStatus
test
@Override public int getNodesWithStatus(final Collection<String> iNodes, final String databaseName, final DB_STATUS... statuses) { for (Iterator<String> it = iNodes.iterator(); it.hasNext(); ) { final String node = it.next(); if (!isNodeStatusEqualsTo(node, databaseName, statuses)) it.remove(); } return iNodes.size(); }
java
{ "resource": "" }
q173323
ODatabaseWrapperAbstract.backup
test
@Override public List<String> backup(OutputStream out, Map<String, Object> options, Callable<Object> callable, final OCommandOutputListener iListener, int compressionLevel, int bufferSize) throws IOException { return underlying.backup(out, options, callable, iListener, compressionLevel, bufferSize); }
java
{ "resource": "" }
q173324
OCommandExecutorScript.waitForNextRetry
test
protected void waitForNextRetry() { try { Thread.sleep(new Random().nextInt(MAX_DELAY - 1) + 1); } catch (InterruptedException e) { OLogManager.instance().error(this, "Wait was interrupted", e); } }
java
{ "resource": "" }
q173325
OHttpRequestWrapper.getArgument
test
public String getArgument(final int iPosition) { return args != null && args.length > iPosition ? args[iPosition] : null; }
java
{ "resource": "" }
q173326
OHttpRequestWrapper.hasParameters
test
public int hasParameters(final String... iNames) { int found = 0; if (iNames != null && request.parameters != null) for (String name : iNames) found += request.parameters.containsKey(name) ? 1 : 0; return found; }
java
{ "resource": "" }
q173327
OServerAdmin.connect
test
@Deprecated public synchronized OServerAdmin connect(final String iUserName, final String iUserPassword) throws IOException { final String username; final String password; OCredentialInterceptor ci = OSecurityManager.instance().newCredentialInterceptor(); if (ci != null) { ci.intercept(storage.getURL(), iUserName, iUserPassword); username = ci.getUsername(); password = ci.getPassword(); } else { username = iUserName; password = iUserPassword; } OConnect37Request request = new OConnect37Request(username, password); networkAdminOperation((network, session) -> { OStorageRemoteNodeSession nodeSession = session.getOrCreateServerSession(network.getServerURL()); try { network.beginRequest(request.getCommand(), session); request.write(network, session); } finally { network.endRequest(); } OConnectResponse response = request.createResponse(); try { network.beginResponse(nodeSession.getSessionId(), true); response.read(network, session); } finally { storage.endResponse(network); } return null; }, "Cannot connect to the remote server/database '" + storage.getURL() + "'"); return this; }
java
{ "resource": "" }
q173328
OServerAdmin.listDatabases
test
@Deprecated public synchronized Map<String, String> listDatabases() throws IOException { OListDatabasesRequest request = new OListDatabasesRequest(); OListDatabasesResponse response = networkAdminOperation(request, "Cannot retrieve the configuration list"); return response.getDatabases(); }
java
{ "resource": "" }
q173329
OServerAdmin.getServerInfo
test
@Deprecated public synchronized ODocument getServerInfo() throws IOException { OServerInfoRequest request = new OServerInfoRequest(); OServerInfoResponse response = networkAdminOperation(request, "Cannot retrieve server information"); ODocument res = new ODocument(); res.fromJSON(response.getResult()); return res; }
java
{ "resource": "" }
q173330
OServerAdmin.existsDatabase
test
public synchronized boolean existsDatabase(final String iDatabaseName, final String storageType) throws IOException { OExistsDatabaseRequest request = new OExistsDatabaseRequest(iDatabaseName, storageType); OExistsDatabaseResponse response = networkAdminOperation(request, "Error on checking existence of the remote storage: " + storage.getName()); return response.isExists(); }
java
{ "resource": "" }
q173331
OServerAdmin.dropDatabase
test
public synchronized OServerAdmin dropDatabase(final String iDatabaseName, final String storageType) throws IOException { ODropDatabaseRequest request = new ODropDatabaseRequest(iDatabaseName, storageType); ODropDatabaseResponse response = networkAdminOperation(request, "Cannot delete the remote storage: " + storage.getName()); OURLConnection connection = OURLHelper.parse(getURL()); OrientDBRemote remote = (OrientDBRemote) ODatabaseDocumentTxInternal.getOrCreateRemoteFactory(connection.getPath()); remote.forceDatabaseClose(iDatabaseName); ODatabaseRecordThreadLocal.instance().remove(); return this; }
java
{ "resource": "" }
q173332
OServerAdmin.freezeDatabase
test
public synchronized OServerAdmin freezeDatabase(final String storageType) throws IOException { OFreezeDatabaseRequest request = new OFreezeDatabaseRequest(storage.getName(), storageType); OFreezeDatabaseResponse response = networkAdminOperation(request, "Cannot freeze the remote storage: " + storage.getName()); return this; }
java
{ "resource": "" }
q173333
OServerAdmin.releaseDatabase
test
public synchronized OServerAdmin releaseDatabase(final String storageType) throws IOException { OReleaseDatabaseRequest request = new OReleaseDatabaseRequest(storage.getName(), storageType); OReleaseDatabaseResponse response = networkAdminOperation(request, "Cannot release the remote storage: " + storage.getName()); return this; }
java
{ "resource": "" }
q173334
OServerAdmin.clusterStatus
test
public ODocument clusterStatus() { ODistributedStatusRequest request = new ODistributedStatusRequest(); ODistributedStatusResponse response = storage.networkOperation(request, "Error on executing Cluster status "); OLogManager.instance().debug(this, "Cluster status %s", response.getClusterConfig().toJSON("prettyPrint")); return response.getClusterConfig(); }
java
{ "resource": "" }
q173335
OCommandExecutorSQLCreateIndex.execute
test
@SuppressWarnings("rawtypes") public Object execute(final Map<Object, Object> iArgs) { if (indexName == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final ODatabaseDocument database = getDatabase(); final OIndex<?> idx; List<OCollate> collatesList = null; if (collates != null) { collatesList = new ArrayList<OCollate>(); for (String collate : collates) { if (collate != null) { final OCollate col = OSQLEngine.getCollate(collate); collatesList.add(col); } else collatesList.add(null); } } if (fields == null || fields.length == 0) { OIndexFactory factory = OIndexes.getFactory(indexType.toString(), null); if (keyTypes != null) idx = database.getMetadata().getIndexManager() .createIndex(indexName, indexType.toString(), new OSimpleKeyIndexDefinition(keyTypes, collatesList), null, null, metadataDoc, engine); else if (serializerKeyId != 0) { idx = database.getMetadata().getIndexManager() .createIndex(indexName, indexType.toString(), new ORuntimeKeyIndexDefinition(serializerKeyId), null, null, metadataDoc, engine); } else { throw new ODatabaseException("Impossible to create an index without specify the key type or the associated property"); } } else { if ((keyTypes == null || keyTypes.length == 0) && collates == null) { idx = oClass.createIndex(indexName, indexType.toString(), null, metadataDoc, engine, fields); } else { final List<OType> fieldTypeList; if (keyTypes == null) { for (final String fieldName : fields) { if (!fieldName.equals("@rid") && !oClass.existsProperty(fieldName)) throw new OIndexException( "Index with name : '" + indexName + "' cannot be created on class : '" + oClass.getName() + "' because field: '" + fieldName + "' is absent in class definition."); } fieldTypeList = ((OClassImpl) oClass).extractFieldTypes(fields); } else fieldTypeList = Arrays.asList(keyTypes); final OIndexDefinition idxDef = OIndexDefinitionFactory .createIndexDefinition(oClass, Arrays.asList(fields), fieldTypeList, collatesList, indexType.toString(), null); idx = database.getMetadata().getIndexManager() .createIndex(indexName, indexType.name(), idxDef, oClass.getPolymorphicClusterIds(), null, metadataDoc, engine); } } if (idx != null) return idx.getSize(); return null; }
java
{ "resource": "" }
q173336
OGraphCommandExecutorSQLFactory.getGraph
test
public static OrientGraph getGraph(final boolean autoStartTx, OModifiableBoolean shouldBeShutDown) { final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal.instance().get(); final OrientBaseGraph result = OrientBaseGraph.getActiveGraph(); if (result != null && (result instanceof OrientGraph)) { final ODatabaseDocumentInternal graphDb = result.getRawGraph(); // CHECK IF THE DATABASE + USER IN TL IS THE SAME IN ORDER TO USE IT if (canReuseActiveGraph(graphDb, database)) { if (!graphDb.isClosed()) { ODatabaseRecordThreadLocal.instance().set(graphDb); if (autoStartTx && autoTxStartRequired(graphDb)) ((OrientGraph) result).begin(); shouldBeShutDown.setValue(false); return (OrientGraph) result; } } } // Set it again on ThreadLocal because the getRawGraph() may have set a closed db in the thread-local ODatabaseRecordThreadLocal.instance().set(database); shouldBeShutDown.setValue(true); final OrientGraph g = (OrientGraph) OrientGraphFactory.getTxGraphImplFactory().getGraph(database, false); if (autoStartTx && autoTxStartRequired(database)) g.begin(); return g; }
java
{ "resource": "" }
q173337
OCommandExecutorSQLRetryAbstract.parseRetry
test
protected void parseRetry() throws OCommandSQLParsingException { retry = Integer.parseInt(parserNextWord(true)); String temp = parseOptionalWord(true); if (temp.equals("WAIT")) { wait = Integer.parseInt(parserNextWord(true)); } else parserGoBack(); }
java
{ "resource": "" }
q173338
OTransactionNoTx.saveRecord
test
public ORecord saveRecord(final ORecord iRecord, final String iClusterName, final OPERATION_MODE iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback) { try { return database.saveAll(iRecord, iClusterName, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback); } catch (Exception e) { // REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS final ORecordId rid = (ORecordId) iRecord.getIdentity(); if (rid.isValid()) database.getLocalCache().freeRecord(rid); if (e instanceof ONeedRetryException) throw (ONeedRetryException) e; throw OException.wrapException( new ODatabaseException("Error during saving of record" + (iRecord != null ? " with rid " + iRecord.getIdentity() : "")), e); } }
java
{ "resource": "" }
q173339
OTransactionNoTx.deleteRecord
test
public void deleteRecord(final ORecord iRecord, final OPERATION_MODE iMode) { if (!iRecord.getIdentity().isPersistent()) return; try { database.executeDeleteRecord(iRecord, iRecord.getVersion(), true, iMode, false); } catch (Exception e) { // REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS final ORecordId rid = (ORecordId) iRecord.getIdentity(); if (rid.isValid()) database.getLocalCache().freeRecord(rid); if (e instanceof RuntimeException) throw (RuntimeException) e; throw OException.wrapException( new ODatabaseException("Error during deletion of record" + (iRecord != null ? " with rid " + iRecord.getIdentity() : "")), e); } }
java
{ "resource": "" }
q173340
OSecurityAuthenticatorAbstract.getAuthenticationHeader
test
public String getAuthenticationHeader(String databaseName) { String header; // Default to Basic. if (databaseName != null) header = "WWW-Authenticate: Basic realm=\"OrientDB db-" + databaseName + "\""; else header = "WWW-Authenticate: Basic realm=\"OrientDB Server\""; return header; }
java
{ "resource": "" }
q173341
OSystemUserAuthenticator.authenticate
test
public String authenticate(final String username, final String password) { String principal = null; try { if (getServer() != null) { // dbName parameter is null because we don't need to filter any roles for this. OUser user = getServer().getSecurity().getSystemUser(username, null); if (user != null && user.getAccountStatus() == OSecurityUser.STATUSES.ACTIVE) { if (user.checkPassword(password)) principal = username; } } } catch (Exception ex) { OLogManager.instance().error(this, "authenticate()", ex); } return principal; }
java
{ "resource": "" }
q173342
OSystemUserAuthenticator.isAuthorized
test
public boolean isAuthorized(final String username, final String resource) { if (username == null || resource == null) return false; try { if (getServer() != null) { OUser user = getServer().getSecurity().getSystemUser(username, null); if (user != null && user.getAccountStatus() == OSecurityUser.STATUSES.ACTIVE) { ORole role = null; ORule.ResourceGeneric rg = ORule.mapLegacyResourceToGenericResource(resource); if (rg != null) { String specificResource = ORule.mapLegacyResourceToSpecificResource(resource); if (specificResource == null || specificResource.equals("*")) { specificResource = null; } role = user.checkIfAllowed(rg, specificResource, ORole.PERMISSION_EXECUTE); } return role != null; } } } catch (Exception ex) { OLogManager.instance().error(this, "isAuthorized()", ex); } return false; }
java
{ "resource": "" }
q173343
OServerShutdownHook.run
test
@Override public void run() { if (server != null) if (!server.shutdown()) { // ALREADY IN SHUTDOWN, WAIT FOR 5 SEC MORE try { Thread.sleep(5000); } catch (InterruptedException e) { } } }
java
{ "resource": "" }
q173344
JavaCharStream.adjustBeginLineColumn
test
public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; }
java
{ "resource": "" }
q173345
OBonsaiBucketAbstract.setBucketPointer
test
protected void setBucketPointer(int pageOffset, OBonsaiBucketPointer value) throws IOException { setLongValue(pageOffset, value.getPageIndex()); setIntValue(pageOffset + OLongSerializer.LONG_SIZE, value.getPageOffset()); }
java
{ "resource": "" }
q173346
OBonsaiBucketAbstract.getBucketPointer
test
protected OBonsaiBucketPointer getBucketPointer(int offset) { final long pageIndex = getLongValue(offset); final int pageOffset = getIntValue(offset + OLongSerializer.LONG_SIZE); return new OBonsaiBucketPointer(pageIndex, pageOffset); }
java
{ "resource": "" }
q173347
OAtomicOperationsManager.endAtomicOperation
test
public OLogSequenceNumber endAtomicOperation(boolean rollback) throws IOException { final OAtomicOperation operation = currentOperation.get(); if (operation == null) { OLogManager.instance().error(this, "There is no atomic operation active", null); throw new ODatabaseException("There is no atomic operation active"); } int counter = operation.getCounter(); operation.decrementCounter(); assert counter > 0; final OLogSequenceNumber lsn; try { if (rollback) { operation.rollback(); } if (counter == 1) { try { final boolean useWal = useWal(); if (!operation.isRollback()) { lsn = operation.commitChanges(useWal ? writeAheadLog : null); } else { lsn = null; } if (trackAtomicOperations) { activeAtomicOperations.remove(operation.getOperationUnitId()); } } finally { final Iterator<String> lockedObjectIterator = operation.lockedObjects().iterator(); while (lockedObjectIterator.hasNext()) { final String lockedObject = lockedObjectIterator.next(); lockedObjectIterator.remove(); lockManager.releaseLock(this, lockedObject, OOneEntryPerKeyLockManager.LOCK.EXCLUSIVE); } currentOperation.set(null); } } else { lsn = null; } } catch (Error e) { final OAbstractPaginatedStorage st = storage; if (st != null) { st.handleJVMError(e); } counter = 1; throw e; } finally { if (counter == 1) { atomicOperationsCount.decrement(); } } return lsn; }
java
{ "resource": "" }
q173348
OAtomicOperationsManager.acquireExclusiveLockTillOperationComplete
test
public void acquireExclusiveLockTillOperationComplete(OAtomicOperation operation, String lockName) { if (operation.containsInLockedObjects(lockName)) { return; } lockManager.acquireLock(lockName, OOneEntryPerKeyLockManager.LOCK.EXCLUSIVE); operation.addLockedObject(lockName); }
java
{ "resource": "" }
q173349
O2QCache.changeMaximumAmountOfMemory
test
public void changeMaximumAmountOfMemory(final long readCacheMaxMemory) throws IllegalStateException { MemoryData memoryData; MemoryData newMemoryData; final int newMemorySize = normalizeMemory(readCacheMaxMemory, pageSize); do { memoryData = memoryDataContainer.get(); if (memoryData.maxSize == newMemorySize) { return; } if ((100 * memoryData.pinnedPages / newMemorySize) > percentOfPinnedPages) { throw new IllegalStateException("Cannot decrease amount of memory used by disk cache " + "because limit of pinned pages will be more than allowed limit " + percentOfPinnedPages); } newMemoryData = new MemoryData(newMemorySize, memoryData.pinnedPages); } while (!memoryDataContainer.compareAndSet(memoryData, newMemoryData)); // if (newMemorySize < memoryData.maxSize) // removeColdestPagesIfNeeded(); OLogManager.instance() .info(this, "Disk cache size was changed from " + memoryData.maxSize + " pages to " + newMemorySize + " pages"); }
java
{ "resource": "" }
q173350
OServerNetworkListener.listen
test
private void listen(final String iHostName, final String iHostPortRange, final String iProtocolName, Class<? extends ONetworkProtocol> protocolClass) { for (int port : getPorts(iHostPortRange)) { inboundAddr = new InetSocketAddress(iHostName, port); try { serverSocket = socketFactory.createServerSocket(port, 0, InetAddress.getByName(iHostName)); if (serverSocket.isBound()) { OLogManager.instance().info(this, "Listening $ANSI{green " + iProtocolName + "} connections on $ANSI{green " + inboundAddr.getAddress().getHostAddress() + ":" + inboundAddr.getPort() + "} (protocol v." + protocolVersion + ", socket=" + socketFactory.getName() + ")"); return; } } catch (BindException be) { OLogManager.instance().warn(this, "Port %s:%d busy, trying the next available...", iHostName, port); } catch (SocketException se) { OLogManager.instance().error(this, "Unable to create socket", se); throw new RuntimeException(se); } catch (IOException ioe) { OLogManager.instance().error(this, "Unable to read data from an open socket", ioe); System.err.println("Unable to read data from an open socket."); throw new RuntimeException(ioe); } } OLogManager.instance() .error(this, "Unable to listen for connections using the configured ports '%s' on host '%s'", null, iHostPortRange, iHostName); throw new OSystemException("Unable to listen for connections using the configured ports '%s' on host '%s'"); }
java
{ "resource": "" }
q173351
OServerNetworkListener.readParameters
test
private void readParameters(final OContextConfiguration iServerConfig, final OServerParameterConfiguration[] iParameters) { configuration = new OContextConfiguration(iServerConfig); // SET PARAMETERS if (iParameters != null && iParameters.length > 0) { // CONVERT PARAMETERS IN MAP TO INTIALIZE THE CONTEXT-CONFIGURATION for (OServerParameterConfiguration param : iParameters) configuration.setValue(param.name, param.value); } socketBufferSize = configuration.getValueAsInteger(OGlobalConfiguration.NETWORK_SOCKET_BUFFER_SIZE); }
java
{ "resource": "" }
q173352
OLogManager.shutdown
test
public void shutdown() { if (shutdownFlag.compareAndSet(false, true)) { try { if (LogManager.getLogManager() instanceof ShutdownLogManager) ((ShutdownLogManager) LogManager.getLogManager()).shutdown(); } catch (NoClassDefFoundError ignore) { // Om nom nom. Some custom class loaders, like Tomcat's one, cannot load classes while in shutdown hooks, since their // runtime is already shutdown. Ignoring the exception, if ShutdownLogManager is not loaded at this point there are no instances // of it anyway and we have nothing to shutdown. } } }
java
{ "resource": "" }
q173353
OClosableLinkedContainer.add
test
public void add(K key, V item) throws InterruptedException { if (!item.isOpen()) throw new IllegalArgumentException("All passed in items should be in open state"); checkOpenFilesLimit(); final OClosableEntry<K, V> closableEntry = new OClosableEntry<K, V>(item); final OClosableEntry<K, V> oldEntry = data.putIfAbsent(key, closableEntry); if (oldEntry != null) { throw new IllegalStateException("Item with key " + key + " already exists"); } logAdd(closableEntry); }
java
{ "resource": "" }
q173354
OClosableLinkedContainer.remove
test
public V remove(K key) { final OClosableEntry<K, V> removed = data.remove(key); if (removed != null) { long preStatus = removed.makeRetired(); if (OClosableEntry.isOpen(preStatus)) { countClosedFiles(); } logRemoved(removed); return removed.get(); } return null; }
java
{ "resource": "" }
q173355
OClosableLinkedContainer.acquire
test
public OClosableEntry<K, V> acquire(K key) throws InterruptedException { checkOpenFilesLimit(); final OClosableEntry<K, V> entry = data.get(key); if (entry == null) return null; boolean logOpen = false; entry.acquireStateLock(); try { if (entry.isRetired() || entry.isDead()) { return null; } else if (entry.isClosed()) { entry.makeAcquiredFromClosed(entry.get()); logOpen = true; } else if (entry.isOpen()) { entry.makeAcquiredFromOpen(); } else { entry.incrementAcquired(); } } finally { entry.releaseStateLock(); } if (logOpen) { logOpen(entry); } else { logAcquire(entry); } assert entry.get().isOpen(); return entry; }
java
{ "resource": "" }
q173356
OClosableLinkedContainer.get
test
public V get(K key) { final OClosableEntry<K, V> entry = data.get(key); if (entry != null) return entry.get(); return null; }
java
{ "resource": "" }
q173357
OClosableLinkedContainer.clear
test
public void clear() { lruLock.lock(); try { data.clear(); openFiles.set(0); for (int n = 0; n < NUMBER_OF_READ_BUFFERS; n++) { final AtomicReference<OClosableEntry<K, V>>[] buffer = readBuffers[n]; for (int i = 0; i < READ_BUFFER_SIZE; i++) { buffer[i].set(null); } readBufferReadCount[n] = 0; readBufferWriteCount[n].set(0); readBufferDrainAtWriteCount[n].set(0); } stateBuffer.clear(); while (lruList.poll() != null) ; } finally { lruLock.unlock(); } }
java
{ "resource": "" }
q173358
OClosableLinkedContainer.close
test
public boolean close(K key) { emptyBuffers(); final OClosableEntry<K, V> entry = data.get(key); if (entry == null) return true; if (entry.makeClosed()) { countClosedFiles(); return true; } return false; }
java
{ "resource": "" }
q173359
OClosableLinkedContainer.emptyReadBuffers
test
private void emptyReadBuffers() { for (int n = 0; n < NUMBER_OF_READ_BUFFERS; n++) { AtomicReference<OClosableEntry<K, V>>[] buffer = readBuffers[n]; long writeCount = readBufferDrainAtWriteCount[n].get(); long counter = readBufferReadCount[n]; while (true) { final int bufferIndex = (int) (counter & READ_BUFFER_INDEX_MASK); final AtomicReference<OClosableEntry<K, V>> eref = buffer[bufferIndex]; final OClosableEntry<K, V> entry = eref.get(); if (entry == null) break; applyRead(entry); counter++; eref.lazySet(null); } readBufferReadCount[n] = counter; readBufferDrainAtWriteCount[n].lazySet(writeCount); } }
java
{ "resource": "" }
q173360
OClosableLinkedContainer.afterWrite
test
private void afterWrite(Runnable task) { stateBuffer.add(task); drainStatus.lazySet(DrainStatus.REQUIRED); tryToDrainBuffers(); }
java
{ "resource": "" }
q173361
OClosableLinkedContainer.afterRead
test
private void afterRead(OClosableEntry<K, V> entry) { final int bufferIndex = readBufferIndex(); final long writeCount = putEntryInReadBuffer(entry, bufferIndex); drainReadBuffersIfNeeded(bufferIndex, writeCount); }
java
{ "resource": "" }
q173362
OClosableLinkedContainer.putEntryInReadBuffer
test
private long putEntryInReadBuffer(OClosableEntry<K, V> entry, int bufferIndex) { //next index to write for this buffer AtomicLong writeCounter = readBufferWriteCount[bufferIndex]; final long counter = writeCounter.get(); //we do not use CAS operations to limit contention between threads //it is normal that because of duplications of indexes some of items will be lost writeCounter.lazySet(counter + 1); final AtomicReference<OClosableEntry<K, V>>[] buffer = readBuffers[bufferIndex]; AtomicReference<OClosableEntry<K, V>> bufferEntry = buffer[(int) (counter & READ_BUFFER_INDEX_MASK)]; bufferEntry.lazySet(entry); return counter + 1; }
java
{ "resource": "" }
q173363
OClosableLinkedContainer.closestPowerOfTwo
test
private static int closestPowerOfTwo(int value) { int n = value - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= (1 << 30)) ? 1 << 30 : n + 1; }
java
{ "resource": "" }
q173364
OLiveQueryClientListener.onEvent
test
public boolean onEvent(OLiveQueryPushRequest pushRequest) { ODatabaseDocumentInternal old = ODatabaseRecordThreadLocal.instance().getIfDefined(); try { database.activateOnCurrentThread(); if (pushRequest.getStatus() == OLiveQueryPushRequest.ERROR) { onError(pushRequest.getErrorCode().newException(pushRequest.getErrorMessage(), null)); return true; } else { for (OLiveQueryResult result : pushRequest.getEvents()) { switch (result.getEventType()) { case OLiveQueryResult.CREATE_EVENT: listener.onCreate(database, result.getCurrentValue()); break; case OLiveQueryResult.UPDATE_EVENT: listener.onUpdate(database, result.getOldValue(), result.getCurrentValue()); break; case OLiveQueryResult.DELETE_EVENT: listener.onDelete(database, result.getCurrentValue()); break; } } if (pushRequest.getStatus() == OLiveQueryPushRequest.END) { onEnd(); return true; } } return false; } finally { ODatabaseRecordThreadLocal.instance().set(old); } }
java
{ "resource": "" }
q173365
OObjectEnumLazyMap.convert
test
private void convert(final Object iKey) { if (converted) return; if (super.containsKey(iKey)) return; Object o = underlying.get(String.valueOf(iKey)); if (o instanceof Number) super.put(iKey, enumClass.getEnumConstants()[((Number) o).intValue()]); else super.put(iKey, Enum.valueOf(enumClass, o.toString())); }
java
{ "resource": "" }
q173366
OObjectEnumLazyMap.convertAll
test
protected void convertAll() { if (converted) return; for (java.util.Map.Entry<Object, Object> e : underlying.entrySet()) { if (e.getValue() instanceof Number) super.put(e.getKey(), enumClass.getEnumConstants()[((Number) e.getValue()).intValue()]); else super.put(e.getKey(), Enum.valueOf(enumClass, e.getValue().toString())); } converted = true; }
java
{ "resource": "" }
q173367
OBinarySerializerFactory.getObjectSerializer
test
@SuppressWarnings("unchecked") public <T> OBinarySerializer<T> getObjectSerializer(final OType type) { return (OBinarySerializer<T>) serializerTypeMap.get(type); }
java
{ "resource": "" }
q173368
Orient.initShutdownQueue
test
private void initShutdownQueue() { addShutdownHandler(new OShutdownWorkersHandler()); addShutdownHandler(new OShutdownOrientDBInstancesHandler()); addShutdownHandler(new OShutdownPendingThreadsHandler()); addShutdownHandler(new OShutdownProfilerHandler()); addShutdownHandler(new OShutdownCallListenersHandler()); }
java
{ "resource": "" }
q173369
Orient.getEngine
test
public OEngine getEngine(final String engineName) { engineLock.readLock().lock(); try { return engines.get(engineName); } finally { engineLock.readLock().unlock(); } }
java
{ "resource": "" }
q173370
OProfileStorageStatement.executeSimple
test
@Override public OResultSet executeSimple(OCommandContext ctx) { OResultInternal result = new OResultInternal(); result.setProperty("operation", "optimize database"); OStorage storage = ((ODatabaseInternal) ctx.getDatabase()).getStorage(); if (on) { // activate the profiler ((OAbstractPaginatedStorage) storage).startGatheringPerformanceStatisticForCurrentThread(); result.setProperty("value", "on"); } else { // stop the profiler and return the stats final OSessionStoragePerformanceStatistic performanceStatistic = ((OAbstractPaginatedStorage) storage) .completeGatheringPerformanceStatisticForCurrentThread(); result.setProperty("value", "off"); if (performanceStatistic != null) { result.setProperty("result", performanceStatistic.toDocument()); } else { result.setProperty("result", "error"); result.setProperty("errorMessage", "profiling of storage was not started"); } } OInternalResultSet rs = new OInternalResultSet(); rs.add(result); return rs; }
java
{ "resource": "" }
q173371
OProfileStorageStatement.execute
test
@Override public Object execute(OSQLAsynchQuery<ODocument> request, OCommandContext context, OProgressListener progressListener) { try { ODatabaseDocumentInternal db = getDatabase(); final OStorage storage = db.getStorage(); if (on) { // activate the profiler ((OAbstractPaginatedStorage) storage).startGatheringPerformanceStatisticForCurrentThread(); ODocument result = new ODocument(); result.field("result", "OK"); request.getResultListener().result(result); } else { // stop the profiler and return the stats final OSessionStoragePerformanceStatistic performanceStatistic = ((OAbstractPaginatedStorage) storage) .completeGatheringPerformanceStatisticForCurrentThread(); if (performanceStatistic != null) request.getResultListener().result(performanceStatistic.toDocument()); else { ODocument result = new ODocument(); result.field("result", "Error: profiling of storage was not started."); request.getResultListener().result(result); } } return getResult(request); } finally { if (request.getResultListener() != null) { request.getResultListener().end(); } } }
java
{ "resource": "" }
q173372
ScalableRWLock.addState
test
private ReadersEntry addState() { final AtomicInteger state = new AtomicInteger(SRWL_STATE_NOT_READING); final ReadersEntry newEntry = new ReadersEntry(state); entry.set(newEntry); readersStateList.add(state); readersStateArrayRef.set(null); return newEntry; }
java
{ "resource": "" }
q173373
OSecurityShared.authenticate
test
public OUser authenticate(final OToken authToken) { final String dbName = getDatabase().getName(); if (authToken.getIsValid() != true) { throw new OSecurityAccessException(dbName, "Token not valid"); } OUser user = authToken.getUser(getDatabase()); if (user == null && authToken.getUserName() != null) { // Token handler may not support returning an OUser so let's get username (subject) and query: user = getUser(authToken.getUserName()); } if (user == null) { throw new OSecurityAccessException(dbName, "Authentication failed, could not load user from token"); } if (user.getAccountStatus() != STATUSES.ACTIVE) throw new OSecurityAccessException(dbName, "User '" + user.getName() + "' is not active"); return user; }
java
{ "resource": "" }
q173374
OSecurityShared.createMetadata
test
public OUser createMetadata() { final ODatabaseDocument database = getDatabase(); OClass identityClass = database.getMetadata().getSchema().getClass(OIdentity.CLASS_NAME); // SINCE 1.2.0 if (identityClass == null) identityClass = database.getMetadata().getSchema().createAbstractClass(OIdentity.CLASS_NAME); OClass roleClass = createOrUpdateORoleClass(database, identityClass); createOrUpdateOUserClass(database, identityClass, roleClass); // CREATE ROLES AND USERS ORole adminRole = getRole(ORole.ADMIN); if (adminRole == null) { adminRole = createRole(ORole.ADMIN, ORole.ALLOW_MODES.ALLOW_ALL_BUT); adminRole.addRule(ORule.ResourceGeneric.BYPASS_RESTRICTED, null, ORole.PERMISSION_ALL).save(); } OUser adminUser = getUser(OUser.ADMIN); if (adminUser == null) { // This will return the global value if a local storage context configuration value does not exist. boolean createDefUsers = getDatabase().getStorage().getConfiguration().getContextConfiguration() .getValueAsBoolean(OGlobalConfiguration.CREATE_DEFAULT_USERS); if (createDefUsers) { adminUser = createUser(OUser.ADMIN, OUser.ADMIN, adminRole); } } // SINCE 1.2.0 createOrUpdateORestrictedClass(database); return adminUser; }
java
{ "resource": "" }
q173375
OReadersWriterSpinLock.tryAcquireReadLock
test
public boolean tryAcquireReadLock(long timeout) { final OModifiableInteger lHolds = lockHolds.get(); final int holds = lHolds.intValue(); if (holds > 0) { // we have already acquire read lock lHolds.increment(); return true; } else if (holds < 0) { // write lock is acquired before, do nothing return true; } distributedCounter.increment(); WNode wNode = tail.get(); final long start = System.nanoTime(); while (wNode.locked) { distributedCounter.decrement(); while (wNode.locked && wNode == tail.get()) { wNode.waitingReaders.put(Thread.currentThread(), Boolean.TRUE); if (wNode.locked && wNode == tail.get()) { final long parkTimeout = timeout - (System.nanoTime() - start); if (parkTimeout > 0) { LockSupport.parkNanos(this, parkTimeout); } else { return false; } } wNode = tail.get(); if (System.nanoTime() - start > timeout) { return false; } } distributedCounter.increment(); wNode = tail.get(); if (System.nanoTime() - start > timeout) { distributedCounter.decrement(); return false; } } lHolds.increment(); assert lHolds.intValue() == 1; return true; }
java
{ "resource": "" }
q173376
OrientEdge.getVertex
test
@Override public OrientVertex getVertex(final Direction direction) { final OrientBaseGraph graph = setCurrentGraphInThreadLocal(); if (direction.equals(Direction.OUT)) return graph.getVertex(getOutVertex()); else if (direction.equals(Direction.IN)) return graph.getVertex(getInVertex()); else throw ExceptionFactory.bothIsNotSupported(); }
java
{ "resource": "" }
q173377
OrientEdge.getId
test
@Override public Object getId() { if (rawElement == null) // CREATE A TEMPORARY ID return vOut.getIdentity() + "->" + vIn.getIdentity(); setCurrentGraphInThreadLocal(); return super.getId(); }
java
{ "resource": "" }
q173378
OrientEdge.setProperty
test
@Override public void setProperty(final String key, final Object value) { setCurrentGraphInThreadLocal(); if (rawElement == null) // LIGHTWEIGHT EDGE convertToDocument(); super.setProperty(key, value); }
java
{ "resource": "" }
q173379
OrientEdge.removeProperty
test
@Override public <T> T removeProperty(String key) { setCurrentGraphInThreadLocal(); if (rawElement != null) // NON LIGHTWEIGHT EDGE return super.removeProperty(key); return null; }
java
{ "resource": "" }
q173380
OSBTreeBonsaiLocal.clear
test
@Override public void clear() throws IOException { boolean rollback = false; final OAtomicOperation atomicOperation = startAtomicOperation(true); try { final Lock lock = FILE_LOCK_MANAGER.acquireExclusiveLock(fileId); try { final Queue<OBonsaiBucketPointer> subTreesToDelete = new LinkedList<>(); final OCacheEntry cacheEntry = loadPageForWrite(atomicOperation, fileId, rootBucketPointer.getPageIndex(), false, true); try { OSBTreeBonsaiBucket<K, V> rootBucket = new OSBTreeBonsaiBucket<>(cacheEntry, rootBucketPointer.getPageOffset(), keySerializer, valueSerializer, this); addChildrenToQueue(subTreesToDelete, rootBucket); rootBucket.shrink(0); rootBucket = new OSBTreeBonsaiBucket<>(cacheEntry, rootBucketPointer.getPageOffset(), true, keySerializer, valueSerializer, this); rootBucket.setTreeSize(0); } finally { releasePageFromWrite(atomicOperation, cacheEntry); } recycleSubTrees(subTreesToDelete, atomicOperation); } finally { lock.unlock(); } } catch (final Exception e) { rollback = true; throw e; } finally { endAtomicOperation(rollback); } }
java
{ "resource": "" }
q173381
OSBTreeBonsaiLocal.delete
test
@Override public void delete() throws IOException { boolean rollback = false; final OAtomicOperation atomicOperation = startAtomicOperation(false); try { final Lock lock = FILE_LOCK_MANAGER.acquireExclusiveLock(fileId); try { final Queue<OBonsaiBucketPointer> subTreesToDelete = new LinkedList<>(); subTreesToDelete.add(rootBucketPointer); recycleSubTrees(subTreesToDelete, atomicOperation); } finally { lock.unlock(); } } catch (final Exception e) { rollback = true; throw e; } finally { endAtomicOperation(rollback); } }
java
{ "resource": "" }
q173382
OGraphBatchInsertBasic.end
test
public void end() { final OClass vClass = db.getMetadata().getSchema().getClass(vertexClass); try { runningThreads = new AtomicInteger(parallel); for (int i = 0; i < parallel - 1; i++) { Thread t = new BatchImporterJob(i, vClass); t.start(); } Thread t = new BatchImporterJob(parallel - 1, vClass); t.run(); if (runningThreads.get() > 0) { synchronized (runningThreads) { while (runningThreads.get() > 0) { try { runningThreads.wait(); } catch (InterruptedException e) { } } } } } finally { db.activateOnCurrentThread(); db.declareIntent(null); db.close(); if (walActive) OGlobalConfiguration.USE_WAL.setValue(true); } }
java
{ "resource": "" }
q173383
OGraphBatchInsertBasic.createVertex
test
public void createVertex(final Long v) { last = last < v ? v : last; final List<Long> outList = out.get(v); if (outList == null) { out.put(v, new ArrayList<Long>(averageEdgeNumberPerNode <= 0 ? 4 : averageEdgeNumberPerNode)); } }
java
{ "resource": "" }
q173384
OCommandExecutorSQLTraverse.parseStrategy
test
protected boolean parseStrategy(final String w) throws OCommandSQLParsingException { if (!w.equals(KEYWORD_STRATEGY)) return false; final String strategyWord = parserNextWord(true); try { traverse.setStrategy(OTraverse.STRATEGY.valueOf(strategyWord.toUpperCase(Locale.ENGLISH))); } catch (IllegalArgumentException ignore) { throwParsingException("Invalid " + KEYWORD_STRATEGY + ". Use one between " + Arrays.toString(OTraverse.STRATEGY.values())); } return true; }
java
{ "resource": "" }
q173385
ORecordSerializerBinaryV0.getPositionsFromEmbeddedCollection
test
private List<RecordInfo> getPositionsFromEmbeddedCollection(final BytesContainer bytes, int serializerVersion) { List<RecordInfo> retList = new ArrayList<>(); int numberOfElements = OVarIntSerializer.readAsInteger(bytes); //read collection type readByte(bytes); for (int i = 0; i < numberOfElements; i++) { //read element //read data type OType dataType = readOType(bytes, false); int fieldStart = bytes.offset; RecordInfo fieldInfo = new RecordInfo(); fieldInfo.fieldStartOffset = fieldStart; fieldInfo.fieldType = dataType; //TODO find better way to skip data bytes; deserializeValue(bytes, dataType, null, true, -1, serializerVersion, true); fieldInfo.fieldLength = bytes.offset - fieldStart; retList.add(fieldInfo); } return retList; }
java
{ "resource": "" }
q173386
OCommandExecutorSQLInsert.execute
test
public Object execute(final Map<Object, Object> iArgs) { if (newRecords == null && content == null && subQuery == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final OCommandParameters commandParameters = new OCommandParameters(iArgs); if (indexName != null) { if (newRecords == null) throw new OCommandExecutionException("No key/value found"); final OIndex<?> index = getDatabase().getMetadata().getIndexManager().getIndex(indexName); if (index == null) throw new OCommandExecutionException("Target index '" + indexName + "' not found"); // BIND VALUES Map<String, Object> result = new HashMap<String, Object>(); for (Map<String, Object> candidate : newRecords) { Object indexKey = getIndexKeyValue(commandParameters, candidate); OIdentifiable indexValue = getIndexValue(commandParameters, candidate); if (index instanceof OIndexMultiValues) { final Collection<ORID> rids = ((OIndexMultiValues) index).get(indexKey); if (!rids.contains(indexValue.getIdentity())) { index.put(indexKey, indexValue); } } else { index.put(indexKey, indexValue); } result.put(KEYWORD_KEY, indexKey); result.put(KEYWORD_RID, indexValue); } // RETURN LAST ENTRY return prepareReturnItem(new ODocument(result)); } else { // CREATE NEW DOCUMENTS final List<ODocument> docs = new ArrayList<ODocument>(); if (newRecords != null) { for (Map<String, Object> candidate : newRecords) { final ODocument doc = className != null ? new ODocument(className) : new ODocument(); OSQLHelper.bindParameters(doc, candidate, commandParameters, context); saveRecord(doc); docs.add(doc); } if (docs.size() == 1) return prepareReturnItem(docs.get(0)); else return prepareReturnResult(docs); } else if (content != null) { final ODocument doc = className != null ? new ODocument(className) : new ODocument(); doc.merge(content, true, false); saveRecord(doc); return prepareReturnItem(doc); } else if (subQuery != null) { subQuery.execute(); if (queryResult != null) return prepareReturnResult(queryResult); return saved.longValue(); } } return null; }
java
{ "resource": "" }
q173387
ODatabaseRepair.fixLink
test
protected boolean fixLink(final Object fieldValue) { if (fieldValue instanceof OIdentifiable) { final ORID id = ((OIdentifiable) fieldValue).getIdentity(); if (id.getClusterId() == 0 && id.getClusterPosition() == 0) return true; if (id.isValid()) if (id.isPersistent()) { final ORecord connected = ((OIdentifiable) fieldValue).getRecord(); if (connected == null) return true; } else return true; } return false; }
java
{ "resource": "" }
q173388
ORecordInternal.fill
test
public static ORecordAbstract fill(final ORecord record, final ORID iRid, final int iVersion, final byte[] iBuffer, final boolean iDirty) { final ORecordAbstract rec = (ORecordAbstract) record; rec.fill(iRid, iVersion, iBuffer, iDirty); return rec; }
java
{ "resource": "" }
q173389
ORecordInternal.setVersion
test
public static void setVersion(final ORecord record, final int iVersion) { final ORecordAbstract rec = (ORecordAbstract) record; rec.setVersion(iVersion); }
java
{ "resource": "" }
q173390
ORecordInternal.getRecordType
test
public static byte getRecordType(final ORecord record) { if (record instanceof ORecordAbstract) { return ((ORecordAbstract) record).getRecordType(); } final ORecordAbstract rec = (ORecordAbstract) record.getRecord(); return rec.getRecordType(); }
java
{ "resource": "" }
q173391
ODistributedWorker.initDatabaseInstance
test
public void initDatabaseInstance() { if (database == null) { for (int retry = 0; retry < 100; ++retry) { try { database = distributed.getDatabaseInstance(); // OK break; } catch (OStorageException e) { // WAIT FOR A WHILE, THEN RETRY if (!dbNotAvailable(retry)) return; } catch (OConfigurationException e) { // WAIT FOR A WHILE, THEN RETRY if (!dbNotAvailable(retry)) return; } } if (database == null) { ODistributedServerLog.info(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "Database '%s' not present, shutting down database manager", databaseName); distributed.shutdown(); throw new ODistributedException("Cannot open database '" + databaseName + "'"); } } else if (database.isClosed()) { // DATABASE CLOSED, REOPEN IT database.activateOnCurrentThread(); database.close(); database = distributed.getDatabaseInstance(); } }
java
{ "resource": "" }
q173392
OETLContext.printExceptionStackTrace
test
public String printExceptionStackTrace(Exception e, String level) { // copying the exception stack trace in the string Writer writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String s = writer.toString(); switch (level) { case "debug": this.messageHandler.debug(this, "\n" + s + "\n"); break; case "info": this.messageHandler.info(this, "\n" + s + "\n"); break; case "warn": this.messageHandler.warn(this, "\n" + s + "\n"); break; case "error": this.messageHandler.error(this, "\n" + s + "\n"); break; } return s; }
java
{ "resource": "" }
q173393
OQueryOperator.executeIndexQuery
test
public OIndexCursor executeIndexQuery(OCommandContext iContext, OIndex<?> index, final List<Object> keyParams, boolean ascSortOrder) { return null; }
java
{ "resource": "" }
q173394
ORecordLazyMap.convertLink2Record
test
private void convertLink2Record(final Object iKey) { if (status == MULTIVALUE_CONTENT_TYPE.ALL_RECORDS) return; final Object value; if (iKey instanceof ORID) value = iKey; else value = super.get(iKey); if (value != null && value instanceof ORID) { final ORID rid = (ORID) value; marshalling = true; try { try { // OVERWRITE IT ORecord record = rid.getRecord(); if(record != null){ ORecordInternal.unTrack(sourceRecord, rid); ORecordInternal.track(sourceRecord, record); } super.put(iKey, record); } catch (ORecordNotFoundException ignore) { // IGNORE THIS } } finally { marshalling = false; } } }
java
{ "resource": "" }
q173395
OHttpNetworkCommandManager.registerCommand
test
public void registerCommand(final OServerCommand iServerCommandInstance) { for (String name : iServerCommandInstance.getNames()) if (OStringSerializerHelper.contains(name, '{')) { restCommands.put(name, iServerCommandInstance); } else if (OStringSerializerHelper.contains(name, '*')) wildcardCommands.put(name, iServerCommandInstance); else exactCommands.put(name, iServerCommandInstance); iServerCommandInstance.configure(server); }
java
{ "resource": "" }
q173396
ODefaultPasswordAuthenticator.createServerUser
test
protected OServerUserConfiguration createServerUser(final ODocument userDoc) { OServerUserConfiguration userCfg = null; if (userDoc.containsField("username") && userDoc.containsField("resources")) { final String user = userDoc.field("username"); final String resources = userDoc.field("resources"); String password = userDoc.field("password"); if (password == null) password = ""; userCfg = new OServerUserConfiguration(user, password, resources); } return userCfg; }
java
{ "resource": "" }
q173397
OFilterAnalyzer.analyzeCondition
test
public List<OIndexSearchResult> analyzeCondition(OSQLFilterCondition condition, final OClass schemaClass, OCommandContext context) { final List<OIndexSearchResult> indexSearchResults = new ArrayList<OIndexSearchResult>(); OIndexSearchResult lastCondition = analyzeFilterBranch(schemaClass, condition, indexSearchResults, context); if (indexSearchResults.isEmpty() && lastCondition != null) { indexSearchResults.add(lastCondition); } Collections.sort(indexSearchResults, new Comparator<OIndexSearchResult>() { public int compare(final OIndexSearchResult searchResultOne, final OIndexSearchResult searchResultTwo) { return searchResultTwo.getFieldCount() - searchResultOne.getFieldCount(); } }); return indexSearchResults; }
java
{ "resource": "" }
q173398
OFilterAnalyzer.createIndexedProperty
test
private OIndexSearchResult createIndexedProperty(final OSQLFilterCondition iCondition, final Object iItem, OCommandContext ctx) { if (iItem == null || !(iItem instanceof OSQLFilterItemField)) { return null; } if (iCondition.getLeft() instanceof OSQLFilterItemField && iCondition.getRight() instanceof OSQLFilterItemField) { return null; } final OSQLFilterItemField item = (OSQLFilterItemField) iItem; if (item.hasChainOperators() && !item.isFieldChain()) { return null; } boolean inverted = iCondition.getRight() == iItem; final Object origValue = inverted ? iCondition.getLeft() : iCondition.getRight(); OQueryOperator operator = iCondition.getOperator(); if (inverted) { if (operator instanceof OQueryOperatorIn) { operator = new OQueryOperatorContains(); } else if (operator instanceof OQueryOperatorContains) { operator = new OQueryOperatorIn(); } else if (operator instanceof OQueryOperatorMajor) { operator = new OQueryOperatorMinor(); } else if (operator instanceof OQueryOperatorMinor) { operator = new OQueryOperatorMajor(); } else if (operator instanceof OQueryOperatorMajorEquals) { operator = new OQueryOperatorMinorEquals(); } else if (operator instanceof OQueryOperatorMinorEquals) { operator = new OQueryOperatorMajorEquals(); } } if (iCondition.getOperator() instanceof OQueryOperatorBetween || operator instanceof OQueryOperatorIn) { return new OIndexSearchResult(operator, item.getFieldChain(), origValue); } final Object value = OSQLHelper.getValue(origValue, null, ctx); return new OIndexSearchResult(operator, item.getFieldChain(), value); }
java
{ "resource": "" }
q173399
OObjectProxyMethodHandler.attach
test
public void attach(final Object self) throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { for (Class<?> currentClass = self.getClass(); currentClass != Object.class; ) { if (Proxy.class.isAssignableFrom(currentClass)) { currentClass = currentClass.getSuperclass(); continue; } for (Field f : currentClass.getDeclaredFields()) { final String fieldName = f.getName(); final Class<?> declaringClass = f.getDeclaringClass(); if (OObjectEntitySerializer.isTransientField(declaringClass, fieldName) || OObjectEntitySerializer .isVersionField(declaringClass, fieldName) || OObjectEntitySerializer.isIdField(declaringClass, fieldName)) continue; Object value = OObjectEntitySerializer.getFieldValue(f, self); value = setValue(self, fieldName, value); OObjectEntitySerializer.setFieldValue(f, self, value); } currentClass = currentClass.getSuperclass(); if (currentClass == null || currentClass.equals(ODocument.class)) // POJO EXTENDS ODOCUMENT: SPECIAL CASE: AVOID TO CONSIDER // ODOCUMENT FIELDS currentClass = Object.class; } }
java
{ "resource": "" }