@Override
  public OCommandRequestAbstract onAsyncReplicationError(final OAsyncReplicationError iCallback) {
    if (iCallback != null) {
      onAsyncReplicationError = new OAsyncReplicationError() {
        int retry = 0;

        @Override
        public ACTION onAsyncReplicationError(Throwable iException, final int iRetry) {
          switch (iCallback.onAsyncReplicationError(iException, ++retry)) {
          case RETRY:
            execute();
            break;

          case IGNORE:

          }

          return ACTION.IGNORE;
        }
      };
    } else
      onAsyncReplicationError = null;
    return this;
  }

@ Override public OCommandRequestAbstract onAsyncReplicationError ( final OAsyncReplicationError iCallback ) { if ( iCallback != null ) { onAsyncReplicationError = new OAsyncReplicationError ( ) { int retry = 0 ; @ Override public ACTION onAsyncReplicationError ( Throwable iException , final int iRetry ) { switch ( iCallback . onAsyncReplicationError ( iException , ++ retry ) ) { case RETRY : execute ( ) ; break ; case IGNORE : } return ACTION . IGNORE ; } } ; } else onAsyncReplicationError = null ; return this ; }

Defines a callback to call in case of error during the asynchronous replication.

Defines a callback to call in case of error during the asynchronous replication .


public void register(final Class<? extends OCompression> compression) {
    try {
      final OCompression tempInstance = compression.newInstance();

      final String name = tempInstance.name();

      if (compressions.containsKey(name))
        throw new IllegalArgumentException("Compression with name '" + name + "' was already registered");

      if (compressionClasses.containsKey(tempInstance.name()))
        throw new IllegalArgumentException("Compression with name '" + name + "' was already registered");

      compressionClasses.put(name, compression);
    } catch (Exception e) {
      OLogManager.instance().error(this, "Cannot register storage compression algorithm '%s'", e, compression);
    }
  }

Registers a stateless implementations, the same instance will be shared on all the storages.

@param compression Compression class

Registers a stateless implementations the same instance will be shared on all the storages .


public int getOpenFilesLimit(boolean verbose, int recommended, int defLimit) {
    if (Platform.isLinux()) {
      final OCLibrary.Rlimit rlimit = new OCLibrary.Rlimit();
      final int result = C_LIBRARY.getrlimit(OCLibrary.RLIMIT_NOFILE, rlimit);

      if (result == 0 && rlimit.rlim_cur > 0) {
        if (verbose) {
          OLogManager.instance().infoNoDb(this, "Detected limit of amount of simultaneously open files is %d, "
              + " limit of open files for disk cache will be set to %d", rlimit.rlim_cur, rlimit.rlim_cur / 2 - 512);
        }

        if (rlimit.rlim_cur < recommended) {
          OLogManager.instance()
              .warnNoDb(this, "Value of limit of simultaneously open files is too small, recommended value is %d", recommended);
        }

        return (int) rlimit.rlim_cur / 2 - 512;
      } else {
        if (verbose) {
          OLogManager.instance().infoNoDb(this, "Can not detect value of limit of open files.");
        }
      }
    } else if (Platform.isWindows()) {
      if (verbose) {
        OLogManager.instance()
            .infoNoDb(this, "Windows OS is detected, %d limit of open files will be set for the disk cache.", recommended);
      }

      return recommended;
    }

    if (verbose) {
      OLogManager.instance().infoNoDb(this, "Default limit of open files (%d) will be used.", defLimit);
    }

    return defLimit;
  }

Detects limit of limit of open files.

@param recommended recommended value of limit of open files.
@param defLimit    default value for limit of open files.

@return limit of open files, available for the system.


public boolean allowsIndexedFunctionExecutionOnTarget(OFromClause target, OCommandContext context,
      OBinaryCompareOperator operator, Object right) {
    if (this.childExpressions.size() != 1) {
      return false;
    }
    return this.childExpressions.get(0).allowsIndexedFunctionExecutionOnTarget(target, context, operator, right);
  }

public boolean allowsIndexedFunctionExecutionOnTarget ( OFromClause target , OCommandContext context , OBinaryCompareOperator operator , Object right ) { if ( this . childExpressions . size ( ) != 1 ) { return false ; } return this . childExpressions . get ( 0 ) . allowsIndexedFunctionExecutionOnTarget ( target , context , operator , right ) ; }

tests if current expression is an indexed function AND that function can be used on this target

@param target  the query target
@param context the execution context

@return true if current expression is an indexed function AND that function can be used on this target, false otherwise


public void move(final int iFrom, final int iPosition) {
    if (iPosition == 0)
      return;

    final int to = iFrom + iPosition;
    final int size = iPosition > 0 ? buffer.length - to : buffer.length - iFrom;

    System.arraycopy(buffer, iFrom, buffer, to, size);
  }

public void move ( final int iFrom , final int iPosition ) { if ( iPosition == 0 ) return ; final int to = iFrom + iPosition ; final int size = iPosition > 0 ? buffer . length - to : buffer . length - iFrom ; System . arraycopy ( buffer , iFrom , buffer , to , size ) ; }

Move bytes left or right of an offset.

@param iFrom     Starting position
@param iPosition Offset to the iFrom value: positive values mean move right, otherwise move left


public void fill(final int iLength, final byte iFiller) {
    assureSpaceFor(iLength);
    Arrays.fill(buffer, position, position + iLength, iFiller);
    position += iLength;
  }

public void fill ( final int iLength , final byte iFiller ) { assureSpaceFor ( iLength ) ; Arrays . fill ( buffer , position , position + iLength , iFiller ) ; position += iLength ; }

Fills the stream from current position writing iLength times the iFiller byte

@param iLength Bytes to jump
@param iFiller Byte to use to fill the space


public OExecutionStepInternal executeUntilReturn() {
    if (steps.size() > 0) {
      lastStep = steps.get(steps.size() - 1);
    }
    for (int i = 0; i < steps.size() - 1; i++) {
      ScriptLineStep step = steps.get(i);
      if (step.containsReturn()) {
        OExecutionStepInternal returnStep = step.executeUntilReturn(ctx);
        if (returnStep != null) {
          lastStep = returnStep;
          return lastStep;
        }
      }
      OResultSet lastResult = step.syncPull(ctx, 100);

      while (lastResult.hasNext()) {
        while (lastResult.hasNext()) {
          lastResult.next();
        }
        lastResult = step.syncPull(ctx, 100);
      }
    }
    this.lastStep = steps.get(steps.size() - 1);
    return lastStep;
  }

public OExecutionStepInternal executeUntilReturn ( ) { if ( steps . size ( ) > 0 ) { lastStep = steps . get ( steps . size ( ) - 1 ) ; } for ( int i = 0 ; i < steps . size ( ) - 1 ; i ++ ) { ScriptLineStep step = steps . get ( i ) ; if ( step . containsReturn ( ) ) { OExecutionStepInternal returnStep = step . executeUntilReturn ( ctx ) ; if ( returnStep != null ) { lastStep = returnStep ; return lastStep ; } } OResultSet lastResult = step . syncPull ( ctx , 100 ) ; while ( lastResult . hasNext ( ) ) { while ( lastResult . hasNext ( ) ) { lastResult . next ( ) ; } lastResult = step . syncPull ( ctx , 100 ) ; } } this . lastStep = steps . get ( steps . size ( ) - 1 ) ; return lastStep ; }

executes all the script and returns last statement execution step, so that it can be executed from outside

@return

executes all the script and returns last statement execution step so that it can be executed from outside


public OExecutionStepInternal executeFull() {
    for (int i = 0; i < steps.size(); i++) {
      ScriptLineStep step = steps.get(i);
      if (step.containsReturn()) {
        OExecutionStepInternal returnStep = step.executeUntilReturn(ctx);
        if (returnStep != null) {
          return returnStep;
        }
      }
      OResultSet lastResult = step.syncPull(ctx, 100);

      while (lastResult.hasNext()) {
        while (lastResult.hasNext()) {
          lastResult.next();
        }
        lastResult = step.syncPull(ctx, 100);
      }
    }

    return null;
  }

public OExecutionStepInternal executeFull ( ) { for ( int i = 0 ; i < steps . size ( ) ; i ++ ) { ScriptLineStep step = steps . get ( i ) ; if ( step . containsReturn ( ) ) { OExecutionStepInternal returnStep = step . executeUntilReturn ( ctx ) ; if ( returnStep != null ) { return returnStep ; } } OResultSet lastResult = step . syncPull ( ctx , 100 ) ; while ( lastResult . hasNext ( ) ) { while ( lastResult . hasNext ( ) ) { lastResult . next ( ) ; } lastResult = step . syncPull ( ctx , 100 ) ; } } return null ; }

executes the whole script and returns last statement ONLY if it's a RETURN, otherwise it returns null;

@return

executes the whole script and returns last statement ONLY if it s a RETURN otherwise it returns null ;


@Override
  public Object evaluateRecord(final OIdentifiable iRecord, ODocument iCurrentResult, final OSQLFilterCondition iCondition,
      final Object iLeft, final Object iRight, OCommandContext iContext, final ODocumentSerializer serializer) {
    return true;
  }

@ Override public Object evaluateRecord ( final OIdentifiable iRecord , ODocument iCurrentResult , final OSQLFilterCondition iCondition , final Object iLeft , final Object iRight , OCommandContext iContext , final ODocumentSerializer serializer ) { return true ; }

At run-time the evaluation per record must return always true since the recordset are filtered at the beginning unless an
operator can work in both modes. In this case sub-class must extend it.

At run - time the evaluation per record must return always true since the recordset are filtered at the beginning unless an operator can work in both modes . In this case sub - class must extend it .


public Object execute(final Map<Object, Object> iArgs) {

    ODatabaseDocumentInternal db = getDatabase();

    db.begin();

    if (className == null && clusterName == null)
      throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");

    OModifiableBoolean shutdownGraph = new OModifiableBoolean();
    final boolean txAlreadyBegun = getDatabase().getTransaction().isActive();

    try {
      final Set<OIdentifiable> sourceRIDs = OSQLEngine.getInstance().parseRIDTarget(db, source, context, iArgs);

      // CREATE EDGES
      final List<ODocument> result = new ArrayList<ODocument>(sourceRIDs.size());

      for (OIdentifiable from : sourceRIDs) {
        final OVertex fromVertex = toVertex(from);
        if (fromVertex == null)
          continue;

        final ORID oldVertex = fromVertex.getIdentity().copy();
        final ORID newVertex = fromVertex.moveTo(className, clusterName);

        final ODocument newVertexDoc = newVertex.getRecord();

        if (fields != null) {
          // EVALUATE FIELDS
          for (final OPair<String, Object> f : fields) {
            if (f.getValue() instanceof OSQLFunctionRuntime)
              f.setValue(((OSQLFunctionRuntime) f.getValue()).getValue(newVertex.getRecord(), null, context));
          }

          OSQLHelper.bindParameters(newVertexDoc, fields, new OCommandParameters(iArgs), context);
        }

        if (merge != null)
          newVertexDoc.merge(merge, true, false);

        // SAVE CHANGES
        newVertexDoc.save();

        // PUT THE MOVE INTO THE RESULT
        result
            .add(new ODocument().setTrackingChanges(false).field("old", oldVertex, OType.LINK).field("new", newVertex, OType.LINK));

        if (batch > 0 && result.size() % batch == 0) {
            db.commit();
            db.begin();
        }
      }

        db.commit();

      return result;
    } finally {
//      if (!txAlreadyBegun)
//        db.commit();

    }
  }

Executes the command and return the ODocument object created.

Executes the command and return the ODocument object created .


public OStorageConfigurationImpl load(final OContextConfiguration configuration) throws OSerializationException {
    lock.acquireWriteLock();
    try {
      initConfiguration(configuration);

      final byte[] record = storage.readRecord(CONFIG_RID, null, false, false, null).getResult().buffer;

      if (record == null)
        throw new OStorageException("Cannot load database configuration. The database seems corrupted");

      fromStream(record, 0, record.length, streamCharset);
    } finally {
      lock.releaseWriteLock();
    }

    return this;
  }

This method load the record information by the internal cluster segment. It's for compatibility with older database than
0.9.25.

This method load the record information by the internal cluster segment . It s for compatibility with older database than 0 . 9 . 25 .


@Override
  public <RET extends OCommandExecutor> RET parse(OCommandRequest iRequest) {
    final OCommandRequestText textRequest = (OCommandRequestText) iRequest;
    if (iRequest instanceof OSQLSynchQuery) {
      request = (OSQLSynchQuery<ODocument>) iRequest;
    } else if (iRequest instanceof OSQLAsynchQuery) {
      request = (OSQLAsynchQuery<ODocument>) iRequest;
    } else {
      // BUILD A QUERY OBJECT FROM THE COMMAND REQUEST
      request = new OSQLSynchQuery<ODocument>(textRequest.getText());
      if (textRequest.getResultListener() != null) {
        request.setResultListener(textRequest.getResultListener());
      }
    }
    String queryText = textRequest.getText();

    // please, do not look at this... refactor this ASAP with new executor structure
    final InputStream is = new ByteArrayInputStream(queryText.getBytes());
    OrientSql osql = null;
    try {
      ODatabaseDocumentInternal db = getDatabase();
      if (db == null) {
        osql = new OrientSql(is);
      } else {
        osql = new OrientSql(is, db.getStorage().getConfiguration().getCharset());
      }
    } catch (UnsupportedEncodingException e) {
      OLogManager.instance().warn(this,
          "Invalid charset for database " + getDatabase() + " " + getDatabase().getStorage().getConfiguration().getCharset());
      osql = new OrientSql(is);
    }

    try {
      OMatchStatement result = (OMatchStatement) osql.parse();
      this.matchExpressions = result.matchExpressions;
      this.notMatchExpressions = result.notMatchExpressions;
      this.returnItems = result.returnItems;
      this.returnAliases = result.returnAliases;
      this.limit = result.limit;
    } catch (ParseException e) {
      OCommandSQLParsingException ex = new OCommandSQLParsingException(e, queryText);
      OErrorCode.QUERY_PARSE_ERROR.throwException(ex.getMessage(), ex);
    }

    buildPatterns();
    pattern.validate();
    return (RET) this;
  }

this method parses the statement

@param iRequest Command request implementation.
@param <RET>

@return


@Override
  public Object execute(Map<Object, Object> iArgs) {
    this.context.setInputParameters(iArgs);
    return execute(this.request, this.context, this.progressListener);
  }

@ Override public Object execute ( Map < Object , Object > iArgs ) { this . context . setInputParameters ( iArgs ) ; return execute ( this . request , this . context , this . progressListener ) ; }

this method works statefully, using request and context variables from current Match statement. This method will be deprecated
in next releases

@param iArgs Optional variable arguments to pass to the command.

@return

this method works statefully using request and context variables from current Match statement . This method will be deprecated in next releases


private void updateScheduleStartingAt(PatternNode startNode, Set<PatternNode> visitedNodes, Set<PatternEdge> visitedEdges,
      Map<String, Set<String>> remainingDependencies, List<EdgeTraversal> resultingSchedule) {
    // OrientDB requires the schedule to contain all edges present in the query, which is a stronger condition
    // than simply visiting all nodes in the query. Consider the following example query:
    //     MATCH {
    //         class: A,
    //         as: foo
    //     }.in() {
    //         as: bar
    //     }, {
    //         class: B,
    //         as: bar
    //     }.out() {
    //         as: foo
    //     } RETURN $matches
    // The schedule for the above query must have two edges, even though there are only two nodes and they can both
    // be visited with the traversal of a single edge.
    //
    // To satisfy it, we obey the following for each non-optional node:
    // - ignore edges to neighboring nodes which have unsatisfied dependencies;
    // - for visited neighboring nodes, add their edge if it wasn't already present in the schedule, but do not
    //   recurse into the neighboring node;
    // - for unvisited neighboring nodes with satisfied dependencies, add their edge and recurse into them.
    visitedNodes.add(startNode);
    for (Set<String> dependencies : remainingDependencies.values()) {
      dependencies.remove(startNode.alias);
    }

    Map<PatternEdge, Boolean> edges = new LinkedHashMap<PatternEdge, Boolean>();
    for (PatternEdge outEdge : startNode.out) {
      edges.put(outEdge, true);
    }
    for (PatternEdge inEdge : startNode.in) {
      edges.put(inEdge, false);
    }

    for (Map.Entry<PatternEdge, Boolean> edgeData : edges.entrySet()) {
      PatternEdge edge = edgeData.getKey();
      boolean isOutbound = edgeData.getValue();
      PatternNode neighboringNode = isOutbound ? edge.in : edge.out;

      if (!remainingDependencies.get(neighboringNode.alias).isEmpty()) {
        // Unsatisfied dependencies, ignore this neighboring node.
        continue;
      }

      if (visitedNodes.contains(neighboringNode)) {
        if (!visitedEdges.contains(edge)) {
          // If we are executing in this block, we are in the following situation:
          // - the startNode has not been visited yet;
          // - it has a neighboringNode that has already been visited;
          // - the edge between the startNode and the neighboringNode has not been scheduled yet.
          //
          // The isOutbound value shows us whether the edge is outbound from the point of view of the startNode.
          // However, if there are edges to the startNode, we must visit the startNode from an already-visited
          // neighbor, to preserve the validity of the traversal. Therefore, we negate the value of isOutbound
          // to ensure that the edge is always scheduled in the direction from the already-visited neighbor
          // toward the startNode. Notably, this is also the case when evaluating "optional" nodes -- we always
          // visit the optional node from its non-optional and already-visited neighbor.
          //
          // The only exception to the above is when we have edges with "while" conditions. We are not allowed
          // to flip their directionality, so we leave them as-is.
          boolean traversalDirection;
          if (startNode.optional || edge.item.isBidirectional()) {
            traversalDirection = !isOutbound;
          } else {
            traversalDirection = isOutbound;
          }

          visitedEdges.add(edge);
          resultingSchedule.add(new EdgeTraversal(edge, traversalDirection));
        }
      } else if (!startNode.optional) {
        // If the neighboring node wasn't visited, we don't expand the optional node into it, hence the above check.
        // Instead, we'll allow the neighboring node to add the edge we failed to visit, via the above block.
        if (visitedEdges.contains(edge)) {
          // Should never happen.
          throw new AssertionError("The edge was visited, but the neighboring vertex was not: " + edge + " " + neighboringNode);
        }

        visitedEdges.add(edge);
        resultingSchedule.add(new EdgeTraversal(edge, isOutbound));
        updateScheduleStartingAt(neighboringNode, visitedNodes, visitedEdges, remainingDependencies, resultingSchedule);
      }
    }
  }

Start a depth-first traversal from the starting node, adding all viable unscheduled edges and vertices.

@param startNode             the node from which to start the depth-first traversal
@param visitedNodes          set of nodes that are already visited (mutated in this function)
@param visitedEdges          set of edges that are already visited and therefore don't need to be scheduled (mutated in this
function)
@param remainingDependencies dependency map including only the dependencies that haven't yet been satisfied (mutated in this
function)
@param resultingSchedule     the schedule being computed i.e. appended to (mutated in this function)

Start a depth - first traversal from the starting node adding all viable unscheduled edges and vertices .


public void addIndex(final OIndexDefinition indexDefinition) {
    indexDefinitions.add(indexDefinition);
    if (indexDefinition instanceof OIndexDefinitionMultiValue) {
      if (multiValueDefinitionIndex == -1)
        multiValueDefinitionIndex = indexDefinitions.size() - 1;
      else
        throw new OIndexException("Composite key cannot contain more than one collection item");
    }

    collate.addCollate(indexDefinition.getCollate());
  }

Add new indexDefinition in current composite.

@param indexDefinition Index to add.

Add new indexDefinition in current composite .


public OProjectionItem splitForAggregation(AggregateProjectionSplit aggregateSplit, OCommandContext ctx) {
    if (isAggregate()) {
      OProjectionItem result = new OProjectionItem(-1);
      result.alias = getProjectionAlias();
      result.expression = expression.splitForAggregation(aggregateSplit, ctx);
      result.nestedProjection = nestedProjection;
      return result;
    } else {
      return this;
    }
  }

public OProjectionItem splitForAggregation ( AggregateProjectionSplit aggregateSplit , OCommandContext ctx ) { if ( isAggregate ( ) ) { OProjectionItem result = new OProjectionItem ( - 1 ) ; result . alias = getProjectionAlias ( ) ; result . expression = expression . splitForAggregation ( aggregateSplit , ctx ) ; result . nestedProjection = nestedProjection ; return result ; } else { return this ; } }

INTERNAL USE ONLY this has to be invoked ONLY if the item is aggregate!!!

@param aggregateSplit


public Object toObjectDetermineType(OResult source, OCommandContext ctx){
    String className = getClassNameForDocument(ctx);
    String type = getTypeForDocument(ctx);
    if (className != null || (type != null && "d".equalsIgnoreCase(type))) {
      return toDocument(source, ctx, className);
    }
    else{
      return toMap(source, ctx);
    }
  }

public Object toObjectDetermineType ( OResult source , OCommandContext ctx ) { String className = getClassNameForDocument ( ctx ) ; String type = getTypeForDocument ( ctx ) ; if ( className != null || ( type != null && "d" . equalsIgnoreCase ( type ) ) ) { return toDocument ( source , ctx , className ) ; } else { return toMap ( source , ctx ) ; } }

choosing return type is based on existence of @class and @type field in JSON
@param source
@param ctx
@return


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();
  }

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 ( ) ; }

get the collate of this expression, based on the fully evaluated field chain starting from the passed object.

@param doc the root element (document?) of this field chain
@return the collate, null if no collate is defined

get the collate of this expression based on the fully evaluated field chain starting from the passed object .


public String getStringValue() {
    if (value == null) {
      return null;
    }
    if (value.contains("`")) {
      return value.replaceAll("\\\\`", "`");
    }
    return value;
  }

public String getStringValue ( ) { if ( value == null ) { return null ; } if ( value . contains ( "`" ) ) { return value . replaceAll ( "\\\\`" , "`" ) ; } return value ; }

returns the plain string representation of this identifier, with quoting removed from back-ticks

@return

returns the plain string representation of this identifier with quoting removed from back - ticks


private int advanceProbe(int probe) {
    probe ^= probe << 13; // xorshift
    probe ^= probe >>> 17;
    probe ^= probe << 5;

    this.probe.get().set(probe);
    return probe;
  }

private
int
advanceProbe
(
int
probe
)
{
probe
^=
probe
<<
13
;
// xorshift
probe
^=
probe
>>>
17
;
probe
^=
probe
<<
5
;
this
.
probe
.
get
(
)
.
set
(
probe
)
;
return
probe
;
}

Pseudo-randomly advances and records the given probe value for the given thread.

Pseudo - randomly advances and records the given probe value for the given thread .


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;
  }


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;

  }

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 ; }

It returns a ODocument starting from a json file.

@param filePath

@return ODocument (null if the file does not exist or problem are encountered during the reading)

It returns a ODocument starting from a json file .


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));
  }

Checks if an hash string matches a password, based on the algorithm found on hash string.

@param iHash
Hash string. Can contain the algorithm as prefix in the format <code>{ALGORITHM}-HASH</code>.
@param iPassword
@return

Checks if an hash string matches a password based on the algorithm found on hash string .


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();
  }

public
String
createHash
(
final
String
iInput
,
final
String
iAlgorithm
,
final
boolean
iIncludeAlgorithm
)
{
if
(
iInput
==
)
throw
new
IllegalArgumentException
(
"Input string is null"
)
;
if
(
iAlgorithm
==
)
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
(
)
;
}

Hashes the input string.

@param iInput
String to hash
@param iIncludeAlgorithm
Include the algorithm used or not
@return


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;
  }

Returns true if the algorithm is supported by the current version of Java


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;
  }

Creates the index.

@param clusterIndexName Cluster name where to place the TreeMap


@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()));
  }

Returns the result set of the query as iterable vertices.

Returns the result set of the query as iterable vertices .


@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()));
  }

Returns the result set of the query as iterable edges.

Returns the result set of the query as iterable edges .


@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;
  }

Return the partition keys of all the sub-tasks.

Return the partition keys of all the sub - tasks .


@Override
  public long getDistributedTimeout() {
    final long to = OGlobalConfiguration.DISTRIBUTED_CRUD_TASK_SYNCH_TIMEOUT.getValueAsLong();
    return to + ((to / 2) * tasks.size());
  }

@ Override public long getDistributedTimeout ( ) { final long to = OGlobalConfiguration . DISTRIBUTED_CRUD_TASK_SYNCH_TIMEOUT . getValueAsLong ( ) ; return to + ( ( to / 2 ) * tasks . size ( ) ) ; }

Computes the timeout according to the transaction size.

@return

Computes the timeout according to the transaction size .


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;
  }

Returns the current Graph settings.

@return Features object


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;
  }

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 ; }

This check if a file was trimmed or trunked in the current atomic operation.

@param changesContainer changes container to check
@param pageIndex        limit to check against the changes

@return true if there are no changes or pageIndex still fit, false if the pageIndex do not fit anymore

This check if a file was trimmed or trunked in the current atomic operation .


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;
  }


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;
  }


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();
    }
  }

Adds the specified cluster to the class, if it doesn't already exist.

Adds the specified cluster to the class if it doesn t already exist .


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);
  }

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 ) ; }

Remove all records belonging to specified cluster

@param cid
identifier of cluster


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");

  }

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"
)
;
}

All operations running at cache initialization stage


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");
    }
  }

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" ) ; } }

All operations running at cache destruction stage


public static OScriptResultSet singleton(Object entity, OScriptTransformer transformer) {
    return new OScriptResultSet(Collections.singletonList(entity).iterator(), transformer);
  }

public static OScriptResultSet singleton ( Object entity , OScriptTransformer transformer ) { return new OScriptResultSet ( Collections . singletonList ( entity ) . iterator ( ) , transformer ) ; }

Result set with a single result;

@return


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;
  }

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 ; }

Grant a permission to the resource.

@return


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;
  }

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 ; }


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());
    }
  }


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()));
      }
    }
  }

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 ( ) ) ) ; } } }


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);
  }

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 ) ; }

Reduces every counter by half of its original value.

Reduces every counter by half of its original value .


private int indexOf(final int item, final int i) {
    long hash = SEED[i] * item;
    hash += hash >> 32;
    return ((int) hash) & tableMask;
  }

private int indexOf ( final int item , final int i ) { long hash = SEED [ i ] * item ; hash += hash >> 32 ; return ( ( int ) hash ) & tableMask ; }

Returns the table index for the counter at the specified depth.

@param item the element's hash
@param i    the counter depth

@return the table index

Returns the table index for the counter at the specified depth .


private int spread(int x) {
    x = ((x >>> 16) ^ x) * 0x45d9f3b;
    x = ((x >>> 16) ^ x) * randomSeed;
    return (x >>> 16) ^ x;
  }

private int spread ( int x ) { x = ( ( x >>> 16 ) ^ x ) * 0x45d9f3b ; x = ( ( x >>> 16 ) ^ x ) * randomSeed ; return ( x >>> 16 ) ^ x ; }

Applies a supplemental hash function to a given hashCode, which defends against poor quality
hash functions.

Applies a supplemental hash function to a given hashCode which defends against poor quality hash functions .


public OIndex<?> createIndex(final String iType) {
    acquireSchemaReadLock();
    try {
      return owner.createIndex(getFullName(), iType, globalRef.getName());
    } finally {
      releaseSchemaReadLock();
    }
  }

public OIndex < ? > createIndex ( final String iType ) { acquireSchemaReadLock ( ) ; try { return owner . createIndex ( getFullName ( ) , iType , globalRef . getName ( ) ) ; } finally { releaseSchemaReadLock ( ) ; } }

Creates an index on this property. Indexes speed up queries but slow down insert and update operations. For massive inserts we
suggest to remove the index, make the massive insert and recreate it.

@param iType

@return

@see {@link OClass#createIndex(String, OClass.INDEX_TYPE, String...)} instead.

Creates an index on this property . Indexes speed up queries but slow down insert and update operations . For massive inserts we suggest to remove the index make the massive insert and recreate it .


@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();
    }
  }

Remove the index on property

@deprecated Use {@link OIndexManager#dropIndex(String)} instead.


@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();
    }
  }

@ 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 ( ) ; } }

Returns the first index defined for the property.

@deprecated Use {@link OClass#getInvolvedIndexes(String...)} instead.

Returns the first index defined for the property .


public OClass getLinkedClass() {
    acquireSchemaReadLock();
    try {
      if (linkedClass == null && linkedClassName != null)
        linkedClass = owner.owner.getClass(linkedClassName);
      return linkedClass;
    } finally {
      releaseSchemaReadLock();
    }
  }

public OClass getLinkedClass ( ) { acquireSchemaReadLock ( ) ; try { if ( linkedClass == null && linkedClassName != null ) linkedClass = owner . owner . getClass ( linkedClassName ) ; return linkedClass ; } finally { releaseSchemaReadLock ( ) ; } }

Returns the linked class in lazy mode because while unmarshalling the class could be not loaded yet.

@return

Returns the linked class in lazy mode because while unmarshalling the class could be not loaded yet .


@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();
    }
  }

@ 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 ( ) ; } }


protected void removeListener(final ORecordListener listener) {
    if (_listeners != null) {
      _listeners.remove(listener);
      if (_listeners.isEmpty())
        _listeners = null;
    }
  }

protected void removeListener ( final ORecordListener listener ) { if ( _listeners != null ) { _listeners . remove ( listener ) ; if ( _listeners . isEmpty ( ) ) _listeners = null ; } }

Remove the current event listener.

@see ORecordListener


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());
  }

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 ( ) ) ; }

Creates a distributed database instance if not defined yet.

Creates a distributed database instance if not defined yet .


public void timeoutRequest(final long msgId) {
    final ODistributedResponseManager asynchMgr = responsesByRequestIds.remove(msgId);
    if (asynchMgr != null)
      asynchMgr.timeout();
  }

public void timeoutRequest ( final long msgId ) { final ODistributedResponseManager asynchMgr = responsesByRequestIds . remove ( msgId ) ; if ( asynchMgr != null ) asynchMgr . timeout ( ) ; }

Removes a response manager because in timeout.

Removes a response manager because in timeout .


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;
  }

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 ; }

Returns a copy of current database if it's open. The returned instance can be used by another thread without affecting current
instance. The database copy is not set in thread local.

Returns a copy of current database if it s open . The returned instance can be used by another thread without affecting current instance . The database copy is not set in thread local .


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;
  }

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 ; }


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;
  }

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 ; }

Silently replace delegate by tree implementation.

@param pointer new collection pointer

Silently replace delegate by tree implementation .


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;
  }

Manages cross compiler compatibility issues.

@param result Result to transform

Manages cross compiler compatibility issues .


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);
      }
    }
  }


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();
    }
  }

public
void
close
(
)
{
lock
(
)
;
try
{
if
(
this
.
evictionTask
!=
)
{
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
(
)
;
}
}


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();
    }
  }

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 ( ) ; } }

Removes from memory the pool associated to the closed storage. This avoids pool open against closed storages.

Removes from memory the pool associated to the closed storage . This avoids pool open against closed storages .


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;
  }

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 ; }

Iterates on all factories and append all function names.

@return Set of all function names.

Iterates on all factories and append all function names .


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;
  }

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 ; }

Iterates on all factories and append all collate names.

@return Set of all colate names.

Iterates on all factories and append all collate names .


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;
  }

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 ; }

Iterates on all factories and append all command names.

@return Set of all command names.

Iterates on all factories and append all command names .


private Tuple<Integer, OType> getFieldSizeAndTypeFromCurrentPosition(BytesContainer bytes) {
    int fieldSize = OVarIntSerializer.readAsInteger(bytes);
    OType type = readOType(bytes, false);
    return new Tuple<>(fieldSize, type);
  }

private Tuple < Integer , OType > getFieldSizeAndTypeFromCurrentPosition ( BytesContainer bytes ) { int fieldSize = OVarIntSerializer . readAsInteger ( bytes ) ; OType type = readOType ( bytes , false ) ; return new Tuple <> ( fieldSize , type ) ; }


public OHttpResponseWrapper writeStatus(final int iHttpCode, final String iReason) throws IOException {
    response.writeStatus(iHttpCode, iReason);
    return this;
  }

public OHttpResponseWrapper writeStatus ( final int iHttpCode , final String iReason ) throws IOException { response . writeStatus ( iHttpCode , iReason ) ; return this ; }

Sets the response's status as HTTP code and reason.

@param iHttpCode
Response's HTTP code
@param iReason
Response's reason
@return The object itself for fluent chained calls

Sets the response s status as HTTP code and reason .


public OHttpResponseWrapper writeHeaders(final String iContentType, final boolean iKeepAlive) throws IOException {
    response.writeHeaders(iContentType, iKeepAlive);
    return this;
  }

public OHttpResponseWrapper writeHeaders ( final String iContentType , final boolean iKeepAlive ) throws IOException { response . writeHeaders ( iContentType , iKeepAlive ) ; return this ; }

Sets the response's headers specifying when using the keep-alive or not.

@param iContentType
Response's content type
@param iKeepAlive
Use the keep-alive of the connection
@return The object itself for fluent chained calls

Sets the response s headers specifying when using the keep - alive or not .


public OHttpResponseWrapper writeRecords(final Object iRecords, final String iFetchPlan) throws IOException {
    response.writeRecords(iRecords, iFetchPlan);
    return this;
  }

public OHttpResponseWrapper writeRecords ( final Object iRecords , final String iFetchPlan ) throws IOException { response . writeRecords ( iRecords , iFetchPlan ) ; return this ; }

Writes records as response specifying a fetch-plan to serialize nested records. The records are serialized in JSON format.

@param iRecords
List of records to serialize
@param iFetchPlan
Fetch plan to specify nested records
@return The object itself for fluent chained calls

Writes records as response specifying a fetch - plan to serialize nested records . The records are serialized in JSON format .


public OHttpResponseWrapper writeRecord(final ORecord iRecord, final String iFetchPlan) throws IOException {
    response.writeRecord(iRecord, iFetchPlan, null);
    return this;
  }

public OHttpResponseWrapper writeRecord ( final ORecord iRecord , final String iFetchPlan ) throws IOException { response . writeRecord ( iRecord , iFetchPlan , null ) ; return this ; }

Writes a record as response. The record is serialized in JSON format.

@param iRecord
Record to serialize
@param iFetchPlan
Fetch plan to specify nested records
@return The object itself for fluent chained calls

Writes a record as response . The record is serialized in JSON format .


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;
  }

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 ; }

Sends the complete HTTP response in one call.

@param iCode
HTTP response's Code
@param iReason
Response's reason
@param iContentType
Response's content type
@param iContent
Content to send. Content can be a string for plain text, binary data to return directly binary information,
OIdentifiable for a single record and Collection<OIdentifiable> for a collection of records
@return The object itself for fluent chained calls

Sends the complete HTTP response in one call .


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;
  }

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 ; }

Sends the complete HTTP response in one call specifying a stream as content.

@param iCode
HTTP response's Code
@param iReason
Response's reason
@param iContentType
Response's content type
@param iContent
java.io.InputStream object
@param iSize
Content size in bytes
@return The object itself for fluent chained calls

Sends the complete HTTP response in one call specifying a stream as content .


public ODatabaseObject open(String name, String user, String password) {
    return new OObjectDatabaseTx((ODatabaseDocumentInternal) orientDB.open(name, user, password));
  }

public ODatabaseObject open ( String name , String user , String password ) { return new OObjectDatabaseTx ( ( ODatabaseDocumentInternal ) orientDB . open ( name , user , password ) ) ; }

Open a database specified by name using the username and password if needed

@param name     of the database to open
@param user     the username allowed to open the database
@param password related to the specified username

@return the opened database


@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();
  }

Avoid to close it but rather release itself to the owner pool.

Avoid to close it but rather release itself to the owner pool .


@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;
  }

@ 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 ; }

Change UUID to null to prevent its serialization to disk.

Change UUID to null to prevent its serialization to disk .


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);
    }
  }

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 ) ; } }

Indicates that the most earliest component in stack of components has completed it's operation, so performance data for this
component is stopped to be gathered.

@see #startComponentOperation(String, ComponentType)

Indicates that the most earliest component in stack of components has completed it s operation so performance data for this component is stopped to be gathered .


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);
    }
  }

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 ) ; } }

Takes performance data are split by components from last snapshot and aggregates them with data passed inside method as
parameter. Result of aggregation of performance data is returned inside of passed in performance data.

@param counters Performance data for each component.

Takes performance data are split by components from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data .


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;
  }

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 ; }

Takes write cache performance data from last snapshot and aggregates them with data passed inside method as parameter. Result
of aggregation of performance data is returned inside of passed in performance data and as result of this method call.

@param holder Performance data for write cache may be null

@return Result of aggregation of performance data

Takes write cache performance data from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data and as result of this method call .


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;
  }

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 ; }

Takes storage performance data from last snapshot and aggregates them with data passed inside method as parameter. Result of
aggregation of performance data is returned inside of passed in performance data and as result of this method call.

@param holder Performance data for storage may be null

@return Result of aggregation of performance data

Takes storage performance data from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data and as result of this method call .


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;
  }

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 ; }

Takes write ahead log data from last snapshot and aggregates them with data passed inside method as parameter. Result of
aggregation of performance data is returned inside of passed in performance data and as result of this method call.

@param holder Performance data for write ahead log may be null

@return Result of aggregation of performance data

Takes write ahead log data from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data and as result of this method call .


public void pushComponentCounters(String name, PerformanceCountersHolder holder) {
    if (snapshot == null)
      return;

    final PerformanceCountersHolder countersHolder = snapshot.countersByComponent.get(name);

    if (countersHolder != null) {
      countersHolder.pushData(holder);
    }
  }

public void pushComponentCounters ( String name , PerformanceCountersHolder holder ) { if ( snapshot == null ) return ; final PerformanceCountersHolder countersHolder = snapshot . countersByComponent . get ( name ) ; if ( countersHolder != null ) { countersHolder . pushData ( holder ) ; } }

Takes performance data for component from last snapshot and aggregates them with data passed inside method as parameter. Result
of aggregation of performance data is returned inside of passed in performance data.

@param name   Name of component for which performance data are gathered.
@param holder Performance data for given component.

Takes performance data for component from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data .


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);
  }

Stops and records results of timer which counts how much time was spent on operation of flush pages in write cache.

@param pagesFlushed Amount of pages were flushed during this operation.

Stops and records results of timer which counts how much time was spent on operation of flush pages in write cache .


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);
  }

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 ) ; }

Stops and records results of timer which counts how much time was spent on fuzzy checkpoint operation.

Stops and records results of timer which counts how much time was spent on fuzzy checkpoint operation .


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);
  }

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 ) ; }

Stops and records results of timer which counts how much time was spent on full checkpoint operation.

Stops and records results of timer which counts how much time was spent on full checkpoint operation .


public void stopCommitTimer() {
    final long endTs = nanoTimer.getNano();
    final long timeDiff = (endTs - timeStamps.pop());

    performanceCountersHolder.commitTime += timeDiff;
    performanceCountersHolder.commitCount++;

    makeSnapshotIfNeeded(endTs);
  }

public void stopCommitTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; performanceCountersHolder . commitTime += timeDiff ; performanceCountersHolder . commitCount ++ ; makeSnapshotIfNeeded ( endTs ) ; }

Stops and records results of timer which counts how much time was spent on atomic operation commit.

Stops and records results of timer which counts how much time was spent on atomic operation commit .


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);
  }

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 ) ; }

Stops and records results of timer which counts how much time was spent on logging of single write ahead log record.

@param isStartRecord Indicates whether we logged "start atomic operation" record
@param isStopRecord  Indicates whether we logged "stop atomic operation" record

Stops and records results of timer which counts how much time was spent on logging of single write ahead log record .


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);
  }

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 ) ; }

Stops timer and records how much time was spent on flushing of data from write ahead log cache.

Stops timer and records how much time was spent on flushing of data from write ahead log cache .


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;
  }

protected
static
OStatement
parse
(
String
statement
)
throws
OCommandSQLParsingException
{
try
{
ODatabaseDocumentInternal
db
=
ODatabaseRecordThreadLocal
.
instance
(
)
.
getIfDefined
(
)
;
InputStream
is
;
if
(
db
==
)
{
is
=
new
ByteArrayInputStream
(
statement
.
getBytes
(
)
)
;
}
else
{
try
{
is
=
new
ByteArrayInputStream
(
statement
.
getBytes
(
db
.
getStorage
(
)
.
getConfiguration
(
)
.
getCharset
(
)
)
)
;
}
catch
(
UnsupportedEncodingException
e2
)
{
OLogManager
.
instance
(
)
.
warn
(
,
"Unsupported charset for database "
+
db
+
" "
+
db
.
getStorage
(
)
.
getConfiguration
(
)
.
getCharset
(
)
)
;
is
=
new
ByteArrayInputStream
(
statement
.
getBytes
(
)
)
;
}
}
OrientSql
osql
=
;
if
(
db
==
)
{
osql
=
new
OrientSql
(
is
)
;
}
else
{
try
{
osql
=
new
OrientSql
(
is
,
db
.
getStorage
(
)
.
getConfiguration
(
)
.
getCharset
(
)
)
;
}
catch
(
UnsupportedEncodingException
e2
)
{
OLogManager
.
instance
(
)
.
warn
(
,
"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
;
}

parses an SQL statement and returns the corresponding executor

@param statement the SQL statement

@return the corresponding executor

@throws OCommandSQLParsingException if the input parameter is not a valid SQL statement


protected void initReceiveMessages() throws IOException {
    messageThread = new Thread(() -> {
      while (!Thread.interrupted()) {
        receiveMessages();
      }
    });
    messageThread.setName("OrientDB_DistributedDiscoveryThread");
    messageThread.setDaemon(true);
    messageThread.start();
  }

protected void initReceiveMessages ( ) throws IOException { messageThread = new Thread ( ( ) -> { while ( ! Thread . interrupted ( ) ) { receiveMessages ( ) ; } } ) ; messageThread . setName ( "OrientDB_DistributedDiscoveryThread" ) ; messageThread . setDaemon ( true ) ; messageThread . start ( ) ; }

inits the procedure that listens to pings from other servers, eg. that discovers other nodes in the network

@throws IOException

inits the procedure that listens to pings from other servers eg . that discovers other nodes in the network


protected void initCheckDisconnect() {
    disconnectTimer = new TimerTask() {
      public void run() {
        try {
          checkIfKnownServersAreAlive();
          if (running) {
            initCheckDisconnect();
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    };
    taskScheduler.scheduleOnce(disconnectTimer, discoveryPingIntervalMillis);
  }

protected void initCheckDisconnect ( ) { disconnectTimer = new TimerTask ( ) { public void run ( ) { try { checkIfKnownServersAreAlive ( ) ; if ( running ) { initCheckDisconnect ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; taskScheduler . scheduleOnce ( disconnectTimer , discoveryPingIntervalMillis ) ; }

inits the procedure that checks if a server is no longer available, ie. if he did not ping for a long time

inits the procedure that checks if a server is no longer available ie . if he did not ping for a long time