signature:
public class OCommandExecutorSQLSelect { /** * Use index to order documents by provided fields .
 * @ param iSchemaClass where search for indexes for optimization .
 * @ return true if execution was optimized */
private boolean optimizeSort ( OClass iSchemaClass ) { } }

implementation: OIndexCursor cursor = getOptimizedSortCursor ( iSchemaClass ) ; if ( cursor != null ) { fetchValuesFromIndexCursor ( cursor ) ; return true ; } return false ;


signature:
public class OCommandExecutorSQLSelect { /** * Extract the content of collections and / or links and put it as result */
private void applyExpand ( ) { } }

implementation:
if ( expandTarget == null ) { return ; } final long startExpand = System . currentTimeMillis ( ) ; try { if ( tempResult == null ) { tempResult = new ArrayList < OIdentifiable > ( ) ; if ( expandTarget instanceof OSQLFilterItemVariable ) { Object r = ( ( OSQLFilterItemVariable ) expandTarget ) . getValue ( null , null , context ) ; if ( r != null ) { if ( r instanceof OIdentifiable ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) r ) ; } else if ( r instanceof Iterator || OMultiValue . isMultiValue ( r ) ) { for ( Object o : OMultiValue . getMultiValueIterable ( r ) ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) o ) ; } } } } else if ( expandTarget instanceof OSQLFunctionRuntime && ! hasFieldItemParams ( ( OSQLFunctionRuntime ) expandTarget ) ) { if ( ( ( OSQLFunctionRuntime ) expandTarget ) . aggregateResults ( ) ) { throw new OCommandExecutionException ( "Unsupported operation: aggregate function in expand(" + expandTarget + ")" ) ; } else { Object r = ( ( OSQLFunctionRuntime ) expandTarget ) . execute ( null , null , null , context ) ; if ( r instanceof OIdentifiable ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) r ) ; } else if ( r instanceof Iterator || OMultiValue . isMultiValue ( r ) ) { for ( Object o : OMultiValue . getMultiValueIterable ( r ) ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) o ) ; } } } } } else { if ( tempResult == null ) { tempResult = new ArrayList < OIdentifiable > ( ) ; } final OMultiCollectionIterator < OIdentifiable > finalResult = new OMultiCollectionIterator < OIdentifiable > ( ) ; if ( orderedFields == null || orderedFields . size ( ) == 0 ) { // expand is applied before sorting , so limiting the result set here would give wrong results
int iteratorLimit = 0 ; if ( limit < 0 ) { iteratorLimit = - 1 ; } else { iteratorLimit += limit ; } finalResult . setLimit ( iteratorLimit ) ; finalResult . setSkip ( skip ) ; } for ( OIdentifiable id : tempResult ) { Object fieldValue ; if ( expandTarget instanceof OSQLFilterItem ) { fieldValue = ( ( OSQLFilterItem ) expandTarget ) . getValue ( id . getRecord ( ) , null , context ) ; } else if ( expandTarget instanceof OSQLFunctionRuntime ) { fieldValue = ( ( OSQLFunctionRuntime ) expandTarget ) . getResult ( ) ; } else { fieldValue = expandTarget . toString ( ) ; } if ( fieldValue != null ) { if ( fieldValue instanceof Iterable && ! ( fieldValue instanceof OIdentifiable ) ) { fieldValue = ( ( Iterable ) fieldValue ) . iterator ( ) ; } if ( fieldValue instanceof ODocument ) { ArrayList < ODocument > partial = new ArrayList < ODocument > ( ) ; partial . add ( ( ODocument ) fieldValue ) ; finalResult . add ( partial ) ; } else if ( fieldValue instanceof Collection < ? > || fieldValue . getClass ( ) . isArray ( ) || fieldValue instanceof Iterator < ? > || fieldValue instanceof OIdentifiable || fieldValue instanceof ORidBag ) { finalResult . add ( fieldValue ) ; } else if ( fieldValue instanceof Map < ? , ? > ) { finalResult . add ( ( ( Map < ? , OIdentifiable > ) fieldValue ) . values ( ) ) ; } } } tempResult = finalResult ; } } finally { context . setVariable ( "expandElapsed" , ( System . currentTimeMillis ( ) - startExpand ) ) ; }


signature:
public class OETLJob { /** * Single Job Status
 * @ return ODocument */
public ODocument status ( ) { } }

implementation: synchronized ( listener ) { ODocument status = new ODocument ( ) ; status . field ( "cfg" , cfg ) ; status . field ( "status" , this . status ) ; String lastBatchLog = "" ; if ( this . messageHandler != null ) { lastBatchLog = extractBatchLog ( ) ; } status . field ( "log" , lastBatchLog ) ; if ( this . status == Status . FINISHED ) { listener . notifyAll ( ) ; } return status ; }


signature:
public class OCommandRequestTextAbstract { /** * Delegates the execution to the configured command executor . */
@ SuppressWarnings ( "unchecked" ) public < RET > RET execute ( final Object ... iArgs ) { } }

implementation: setParameters ( iArgs ) ; OExecutionThreadLocal . INSTANCE . get ( ) . onAsyncReplicationOk = onAsyncReplicationOk ; OExecutionThreadLocal . INSTANCE . get ( ) . onAsyncReplicationError = onAsyncReplicationError ; return ( RET ) ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getStorage ( ) . command ( this ) ;


signature:
public class OVertexDelegate { /** * ( Internal only ) Creates a link between a vertices and a Graph Element . */
public static Object createLink ( final ODocument iFromVertex , final OIdentifiable iTo , final String iFieldName ) { } }

implementation:
final Object out ; OType outType = iFromVertex . fieldType ( iFieldName ) ; Object found = iFromVertex . field ( iFieldName ) ; final OClass linkClass = ODocumentInternal . getImmutableSchemaClass ( iFromVertex ) ; if ( linkClass == null ) throw new IllegalArgumentException ( "Class not found in source vertex: " + iFromVertex ) ; final OProperty prop = linkClass . getProperty ( iFieldName ) ; final OType propType = prop != null && prop . getType ( ) != OType . ANY ? prop . getType ( ) : null ; if ( found == null ) { if ( propType == OType . LINKLIST || ( prop != null && "true" . equalsIgnoreCase ( prop . getCustom ( "ordered" ) ) ) ) { // TODO constant
final Collection coll = new ORecordLazyList ( iFromVertex ) ; coll . add ( iTo ) ; out = coll ; outType = OType . LINKLIST ; } else if ( propType == null || propType == OType . LINKBAG ) { final ORidBag bag = new ORidBag ( ) ; bag . add ( iTo ) ; out = bag ; outType = OType . LINKBAG ; } else if ( propType == OType . LINK ) { out = iTo ; outType = OType . LINK ; } else throw new ODatabaseException ( "Type of field provided in schema '" + prop . getType ( ) + "' cannot be used for link creation." ) ; } else if ( found instanceof OIdentifiable ) { if ( prop != null && propType == OType . LINK ) throw new ODatabaseException ( "Type of field provided in schema '" + prop . getType ( ) + "' cannot be used for creation to hold several links." ) ; if ( prop != null && "true" . equalsIgnoreCase ( prop . getCustom ( "ordered" ) ) ) { // TODO constant
final Collection coll = new ORecordLazyList ( iFromVertex ) ; coll . add ( found ) ; coll . add ( iTo ) ; out = coll ; outType = OType . LINKLIST ; } else { final ORidBag bag = new ORidBag ( ) ; bag . add ( ( OIdentifiable ) found ) ; bag . add ( iTo ) ; out = bag ; outType = OType . LINKBAG ; } } else if ( found instanceof ORidBag ) { // ADD THE LINK TO THE COLLECTION
out = null ; ( ( ORidBag ) found ) . add ( iTo . getRecord ( ) ) ; } else if ( found instanceof Collection < ? > ) { // USE THE FOUND COLLECTION
out = null ; ( ( Collection < Object > ) found ) . add ( iTo ) ; } else throw new ODatabaseException ( "Relationship content is invalid on field " + iFieldName + ". Found: " + found ) ; if ( out != null ) // OVERWRITE IT
iFromVertex . field ( iFieldName , out , outType ) ; return out ;


signature:
public class OAbstractPaginatedStorage { /** * That is internal method which is called once we encounter any error inside of JVM . In such case we need to restart JVM to avoid
 * any data corruption . Till JVM is not restarted storage will be put in read - only state . */
public final void handleJVMError ( final Error e ) { } }

implementation: if ( jvmError . compareAndSet ( null , e ) ) { OLogManager . instance ( ) . errorNoDb ( this , "JVM error was thrown" , e ) ; }


signature:
public class OAbstractPaginatedStorage { /** * This method finds all the records which were updated starting from ( but not including ) current LSN and write result in provided
 * output stream . In output stream will be included all thw records which were updated / deleted / created since passed in LSN till
 * the current moment . Deleted records are written in output stream first , then created / updated records . All records are sorted by
 * record id . Data format : < ol > < li > Amount of records ( single entry ) - 8 bytes < / li > < li > Record ' s cluster id - 4 bytes < / li >
 * < li > Record ' s cluster position - 8 bytes < / li > < li > Delete flag , 1 if record is deleted - 1 byte < / li > < li > Record version , only
 * if record is not deleted - 4 bytes < / li > < li > Record type , only if record is not deleted - 1 byte < / li > < li > Length of binary
 * presentation of record , only if record is not deleted - 4 bytes < / li > < li > Binary presentation of the record , only if record is
 * not deleted - length of content is provided in above entity < / li > < / ol >
 * @ param lsn LSN from which we should find changed records
 * @ see OGlobalConfiguration # STORAGE _ TRACK _ CHANGED _ RECORDS _ IN _ WAL */
public OBackgroundDelta recordsChangedAfterLSN ( final OLogSequenceNumber lsn , final OCommandOutputListener outputListener ) { } }

implementation:
final OLogSequenceNumber endLsn ; // container of rids of changed records
final SortedSet < ORID > sortedRids = new TreeSet < > ( ) ; try { if ( ! configuration . getContextConfiguration ( ) . getValueAsBoolean ( OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL ) ) { throw new IllegalStateException ( "Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, " + "to switch it on please set property " + OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL . getKey ( ) + " to the true value, please note that only records" + " which are stored after this property was set will be retrieved" ) ; } stateLock . acquireReadLock ( ) ; try { if ( writeAheadLog == null ) { return null ; } // we iterate till the last record is contained in wal at the moment when we call this method
endLsn = writeAheadLog . end ( ) ; if ( endLsn == null || lsn . compareTo ( endLsn ) > 0 ) { OLogManager . instance ( ) . warn ( this , "Cannot find requested LSN=%s for database sync operation. Last available LSN is %s" , lsn , endLsn ) ; return null ; } if ( lsn . equals ( endLsn ) ) { // nothing has changed
return new OBackgroundDelta ( endLsn ) ; } List < OWriteableWALRecord > records = writeAheadLog . next ( lsn , 1 ) ; if ( records . isEmpty ( ) ) { OLogManager . instance ( ) . info ( this , "Cannot find requested LSN=%s for database sync operation (last available LSN is %s)" , lsn , endLsn ) ; return null ; } final OLogSequenceNumber freezeLsn = records . get ( 0 ) . getLsn ( ) ; writeAheadLog . addCutTillLimit ( freezeLsn ) ; try { records = writeAheadLog . next ( lsn , 1_000 ) ; if ( records . isEmpty ( ) ) { OLogManager . instance ( ) . info ( this , "Cannot find requested LSN=%s for database sync operation (last available LSN is %s)" , lsn , endLsn ) ; return null ; } // all information about changed records is contained in atomic operation metadata
long read = 0 ; readLoop : while ( ! records . isEmpty ( ) ) { for ( final OWALRecord record : records ) { final OLogSequenceNumber recordLSN = record . getLsn ( ) ; if ( endLsn . compareTo ( recordLSN ) >= 0 ) { if ( record instanceof OFileCreatedWALRecord ) { throw new ODatabaseException ( "Cannot execute delta-sync because a new file has been added. Filename: '" + ( ( OFileCreatedWALRecord ) record ) . getFileName ( ) + "' (id=" + ( ( OFileCreatedWALRecord ) record ) . getFileId ( ) + ")" ) ; } if ( record instanceof OFileDeletedWALRecord ) { throw new ODatabaseException ( "Cannot execute delta-sync because a file has been deleted. File id: " + ( ( OFileDeletedWALRecord ) record ) . getFileId ( ) ) ; } if ( record instanceof OAtomicUnitEndRecord ) { final OAtomicUnitEndRecord atomicUnitEndRecord = ( OAtomicUnitEndRecord ) record ; if ( atomicUnitEndRecord . getAtomicOperationMetadata ( ) . containsKey ( ORecordOperationMetadata . RID_METADATA_KEY ) ) { final ORecordOperationMetadata recordOperationMetadata = ( ORecordOperationMetadata ) atomicUnitEndRecord . getAtomicOperationMetadata ( ) . get ( ORecordOperationMetadata . RID_METADATA_KEY ) ; final Set < ORID > rids = recordOperationMetadata . getValue ( ) ; sortedRids . addAll ( rids ) ; } } read ++ ; if ( outputListener != null ) { outputListener . onMessage ( "read " + read + " records from WAL and collected " + sortedRids . size ( ) + " records" ) ; } } else { break readLoop ; } } records = writeAheadLog . next ( records . get ( records . size ( ) - 1 ) . getLsn ( ) , 1_000 ) ; } } finally { writeAheadLog . removeCutTillLimit ( freezeLsn ) ; } } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( "Error of reading of records changed after LSN " + lsn ) , e ) ; } finally { stateLock . releaseReadLock ( ) ; } OBackgroundDelta b = new OBackgroundDelta ( this , outputListener , sortedRids , lsn , endLsn ) ; return b ; } catch ( final RuntimeException e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Error e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * This method finds all the records changed in the last X transactions .
 * @ param maxEntries Maximum number of entries to check back from last log .
 * @ return A set of record ids of the changed records
 * @ see OGlobalConfiguration # STORAGE _ TRACK _ CHANGED _ RECORDS _ IN _ WAL */
public Set < ORecordId > recordsChangedRecently ( final int maxEntries ) { } }

implementation:
final SortedSet < ORecordId > result = new TreeSet < > ( ) ; try { if ( ! OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL . getValueAsBoolean ( ) ) { throw new IllegalStateException ( "Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, " + "to switch it on please set property " + OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL . getKey ( ) + " to the true value, please note that only records" + " which are stored after this property was set will be retrieved" ) ; } stateLock . acquireReadLock ( ) ; try { if ( writeAheadLog == null ) { OLogManager . instance ( ) . warn ( this , "No WAL found for database '%s'" , name ) ; return null ; } OLogSequenceNumber startLsn = writeAheadLog . begin ( ) ; if ( startLsn == null ) { OLogManager . instance ( ) . warn ( this , "The WAL is empty for database '%s'" , name ) ; return result ; } final OLogSequenceNumber freezeLSN = startLsn ; writeAheadLog . addCutTillLimit ( freezeLSN ) ; try { // reread because log may be already truncated
startLsn = writeAheadLog . begin ( ) ; if ( startLsn == null ) { OLogManager . instance ( ) . warn ( this , "The WAL is empty for database '%s'" , name ) ; return result ; } final OLogSequenceNumber endLsn = writeAheadLog . end ( ) ; if ( endLsn == null ) { OLogManager . instance ( ) . warn ( this , "The WAL is empty for database '%s'" , name ) ; return result ; } List < OWriteableWALRecord > walRecords = writeAheadLog . read ( startLsn , 1_000 ) ; if ( walRecords . isEmpty ( ) ) { OLogManager . instance ( ) . info ( this , "Cannot find requested LSN=%s for database sync operation (record in WAL is absent)" , startLsn ) ; return null ; } // KEEP LAST MAX - ENTRIES TRANSACTIONS ' LSN
final List < OAtomicUnitEndRecord > lastTx = new ArrayList < > ( 1024 ) ; readLoop : while ( ! walRecords . isEmpty ( ) ) { for ( final OWriteableWALRecord walRecord : walRecords ) { final OLogSequenceNumber recordLSN = walRecord . getLsn ( ) ; if ( endLsn . compareTo ( recordLSN ) >= 0 ) { if ( walRecord instanceof OAtomicUnitEndRecord ) { if ( lastTx . size ( ) >= maxEntries ) { lastTx . remove ( 0 ) ; } lastTx . add ( ( OAtomicUnitEndRecord ) walRecord ) ; } } else { break readLoop ; } } walRecords = writeAheadLog . next ( walRecords . get ( walRecords . size ( ) - 1 ) . getLsn ( ) , 1_000 ) ; } // COLLECT ALL THE MODIFIED RECORDS
for ( final OAtomicUnitEndRecord atomicUnitEndRecord : lastTx ) { if ( atomicUnitEndRecord . getAtomicOperationMetadata ( ) . containsKey ( ORecordOperationMetadata . RID_METADATA_KEY ) ) { final ORecordOperationMetadata recordOperationMetadata = ( ORecordOperationMetadata ) atomicUnitEndRecord . getAtomicOperationMetadata ( ) . get ( ORecordOperationMetadata . RID_METADATA_KEY ) ; final Set < ORID > rids = recordOperationMetadata . getValue ( ) ; for ( final ORID rid : rids ) { result . add ( ( ORecordId ) rid ) ; } } } OLogManager . instance ( ) . info ( this , "Found %d records changed in last %d operations" , result . size ( ) , lastTx . size ( ) ) ; return result ; } finally { writeAheadLog . removeCutTillLimit ( freezeLSN ) ; } } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( "Error on reading last changed records" ) , e ) ; } finally { stateLock . releaseReadLock ( ) ; } } catch ( final RuntimeException e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Error e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * Starts to gather information about storage performance for current thread . Details which performance characteristics are
 * gathered can be found at { @ link OSessionStoragePerformanceStatistic } .
 * @ see # completeGatheringPerformanceStatisticForCurrentThread ( ) */
public void startGatheringPerformanceStatisticForCurrentThread ( ) { } }

implementation: try { performanceStatisticManager . startThreadMonitoring ( ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * Completes gathering performance characteristics for current thread initiated by call of { @ link
 * # startGatheringPerformanceStatisticForCurrentThread ( ) }
 * @ return Performance statistic gathered after call of { @ link # startGatheringPerformanceStatisticForCurrentThread ( ) } or
 * < code > null < / code > if profiling of storage was not started . */
public OSessionStoragePerformanceStatistic completeGatheringPerformanceStatisticForCurrentThread ( ) { } }

implementation: try { return performanceStatisticManager . stopThreadMonitoring ( ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * Scan the given transaction for new record and allocate a record id for them , the relative record id is inserted inside the
 * transaction for future use .
 * @ param clientTx the transaction of witch allocate rids */
public void preallocateRids ( final OTransactionInternal clientTx ) { } }

implementation:
try { checkOpenness ( ) ; checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) ; final Iterable < ORecordOperation > entries = clientTx . getRecordOperations ( ) ; final TreeMap < Integer , OCluster > clustersToLock = new TreeMap < > ( ) ; final Set < ORecordOperation > newRecords = new TreeSet < > ( COMMIT_RECORD_OPERATION_COMPARATOR ) ; for ( final ORecordOperation txEntry : entries ) { if ( txEntry . type == ORecordOperation . CREATED ) { newRecords . add ( txEntry ) ; final int clusterId = txEntry . getRID ( ) . getClusterId ( ) ; clustersToLock . put ( clusterId , getClusterById ( clusterId ) ) ; } } stateLock . acquireReadLock ( ) ; try { checkOpenness ( ) ; makeStorageDirty ( ) ; boolean rollback = false ; atomicOperationsManager . startAtomicOperation ( ( String ) null , true ) ; try { lockClusters ( clustersToLock ) ; for ( final ORecordOperation txEntry : newRecords ) { final ORecord rec = txEntry . getRecord ( ) ; if ( ! rec . getIdentity ( ) . isPersistent ( ) ) { if ( rec . isDirty ( ) ) { // This allocate a position for a new record
final ORecordId rid = ( ORecordId ) rec . getIdentity ( ) . copy ( ) ; final ORecordId oldRID = rid . copy ( ) ; final OCluster cluster = getClusterById ( rid . getClusterId ( ) ) ; final OPhysicalPosition ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; rid . setClusterPosition ( ppos . clusterPosition ) ; clientTx . updateIdentityAfterCommit ( oldRID , rid ) ; } } else { // This allocate position starting from a valid rid , used in distributed for allocate the same position on other nodes
final ORecordId rid = ( ORecordId ) rec . getIdentity ( ) ; final OPaginatedCluster cluster = ( OPaginatedCluster ) getClusterById ( rid . getClusterId ( ) ) ; OPaginatedCluster . RECORD_STATUS recordStatus = cluster . getRecordStatus ( rid . getClusterPosition ( ) ) ; if ( recordStatus == OPaginatedCluster . RECORD_STATUS . NOT_EXISTENT ) { OPhysicalPosition ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; while ( ppos . clusterPosition < rid . getClusterPosition ( ) ) { ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; } if ( ppos . clusterPosition != rid . getClusterPosition ( ) ) { throw new OConcurrentCreateException ( rid , new ORecordId ( rid . getClusterId ( ) , ppos . clusterPosition ) ) ; } } else if ( recordStatus == OPaginatedCluster . RECORD_STATUS . PRESENT || recordStatus == OPaginatedCluster . RECORD_STATUS . REMOVED ) { final OPhysicalPosition ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; throw new OConcurrentCreateException ( rid , new ORecordId ( rid . getClusterId ( ) , ppos . clusterPosition ) ) ; } } } } catch ( final Exception e ) { rollback = true ; throw e ; } finally { atomicOperationsManager . endAtomicOperation ( rollback ) ; } } catch ( final IOException | RuntimeException ioe ) { throw OException . wrapException ( new OStorageException ( "Could not preallocate RIDs" ) , ioe ) ; } finally { stateLock . releaseReadLock ( ) ; } } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * The commit operation can be run in 3 different conditions , embedded commit , pre - allocated commit , other node commit .
 * < bold > Embedded commit < / bold > is the basic commit where the operation is run in embedded or server side , the transaction arrive
 * with invalid rids that get allocated and committed .
 * < bold > pre - allocated commit < / bold > is the commit that happen after an preAllocateRids call is done , this is usually run by the
 * coordinator of a tx in distributed .
 * < bold > other node commit < / bold > is the commit that happen when a node execute a transaction of another node where all the rids
 * are already allocated in the other node .
 * @ param transaction the transaction to commit
 * @ param allocated true if the operation is pre - allocated commit
 * @ return The list of operations applied by the transaction */
private List < ORecordOperation > commit ( final OTransactionInternal transaction , final boolean allocated ) { } }

implementation:
// XXX : At this moment , there are two implementations of the commit method . One for regular client transactions and one for
// implicit micro - transactions . The implementations are quite identical , but operate on slightly different data . If you change
// this method don ' t forget to change its counterpart :
// OAbstractPaginatedStorage . commit ( com . orientechnologies . orient . core . storage . impl . local . OMicroTransaction )
try { checkOpenness ( ) ; checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) ; txBegun . incrementAndGet ( ) ; final ODatabaseDocumentInternal database = transaction . getDatabase ( ) ; final OIndexManager indexManager = database . getMetadata ( ) . getIndexManager ( ) ; final TreeMap < String , OTransactionIndexChanges > indexOperations = getSortedIndexOperations ( transaction ) ; database . getMetadata ( ) . makeThreadLocalSchemaSnapshot ( ) ; final Collection < ORecordOperation > recordOperations = transaction . getRecordOperations ( ) ; final TreeMap < Integer , OCluster > clustersToLock = new TreeMap < > ( ) ; final Map < ORecordOperation , Integer > clusterOverrides = new IdentityHashMap < > ( 8 ) ; final Set < ORecordOperation > newRecords = new TreeSet < > ( COMMIT_RECORD_OPERATION_COMPARATOR ) ; for ( final ORecordOperation recordOperation : recordOperations ) { if ( recordOperation . type == ORecordOperation . CREATED || recordOperation . type == ORecordOperation . UPDATED ) { final ORecord record = recordOperation . getRecord ( ) ; if ( record instanceof ODocument ) { ( ( ODocument ) record ) . validate ( ) ; } } if ( recordOperation . type == ORecordOperation . UPDATED || recordOperation . type == ORecordOperation . DELETED ) { final int clusterId = recordOperation . getRecord ( ) . getIdentity ( ) . getClusterId ( ) ; clustersToLock . put ( clusterId , getClusterById ( clusterId ) ) ; } else if ( recordOperation . type == ORecordOperation . CREATED ) { newRecords . add ( recordOperation ) ; final ORecord record = recordOperation . getRecord ( ) ; final ORID rid = record . getIdentity ( ) ; int clusterId = rid . getClusterId ( ) ; if ( record . isDirty ( ) && clusterId == ORID . CLUSTER_ID_INVALID && record instanceof ODocument ) { // TRY TO FIX CLUSTER ID TO THE DEFAULT CLUSTER ID DEFINED IN SCHEMA CLASS
final OImmutableClass class_ = ODocumentInternal . getImmutableSchemaClass ( ( ( ODocument ) record ) ) ; if ( class_ != null ) { clusterId = class_ . getClusterForNewInstance ( ( ODocument ) record ) ; clusterOverrides . put ( recordOperation , clusterId ) ; } } clustersToLock . put ( clusterId , getClusterById ( clusterId ) ) ; } } final List < ORecordOperation > result = new ArrayList < > ( 8 ) ; stateLock . acquireReadLock ( ) ; try { if ( modificationLock ) { final List < ORID > recordLocks = new ArrayList < > ( ) ; for ( final ORecordOperation recordOperation : recordOperations ) { if ( recordOperation . type == ORecordOperation . UPDATED || recordOperation . type == ORecordOperation . DELETED ) { recordLocks . add ( recordOperation . getRID ( ) ) ; } } final Set < ORID > locked = transaction . getLockedRecords ( ) ; if ( locked != null ) { recordLocks . removeAll ( locked ) ; } Collections . sort ( recordLocks ) ; for ( final ORID rid : recordLocks ) { acquireWriteLock ( rid ) ; } } try { checkOpenness ( ) ; makeStorageDirty ( ) ; boolean rollback = false ; startStorageTx ( transaction ) ; try { final OAtomicOperation atomicOperation = OAtomicOperationsManager . getCurrentOperation ( ) ; lockClusters ( clustersToLock ) ; checkReadOnlyConditions ( ) ; final Map < ORecordOperation , OPhysicalPosition > positions = new IdentityHashMap < > ( 8 ) ; for ( final ORecordOperation recordOperation : newRecords ) { final ORecord rec = recordOperation . getRecord ( ) ; if ( allocated ) { if ( rec . getIdentity ( ) . isPersistent ( ) ) { positions . put ( recordOperation , new OPhysicalPosition ( rec . getIdentity ( ) . getClusterPosition ( ) ) ) ; } else { throw new OStorageException ( "Impossible to commit a transaction with not valid rid in pre-allocated commit" ) ; } } else if ( rec . isDirty ( ) && ! rec . getIdentity ( ) . isPersistent ( ) ) { final ORecordId rid = ( ORecordId ) rec . getIdentity ( ) . copy ( ) ; final ORecordId oldRID = rid . copy ( ) ; final Integer clusterOverride = clusterOverrides . get ( recordOperation ) ; final int clusterId = clusterOverride == null ? rid . getClusterId ( ) : clusterOverride ; final OCluster cluster = getClusterById ( clusterId ) ; assert atomicOperation . getCounter ( ) == 1 ; OPhysicalPosition physicalPosition = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; assert atomicOperation . getCounter ( ) == 1 ; rid . setClusterId ( cluster . getId ( ) ) ; if ( rid . getClusterPosition ( ) > - 1 ) { // CREATE EMPTY RECORDS UNTIL THE POSITION IS REACHED . THIS IS THE CASE WHEN A SERVER IS OUT OF SYNC
// BECAUSE A TRANSACTION HAS BEEN ROLLED BACK BEFORE TO SEND THE REMOTE CREATES . SO THE OWNER NODE DELETED
// RECORD HAVING A HIGHER CLUSTER POSITION
while ( rid . getClusterPosition ( ) > physicalPosition . clusterPosition ) { assert atomicOperation . getCounter ( ) == 1 ; physicalPosition = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; assert atomicOperation . getCounter ( ) == 1 ; } if ( rid . getClusterPosition ( ) != physicalPosition . clusterPosition ) { throw new OConcurrentCreateException ( rid , new ORecordId ( rid . getClusterId ( ) , physicalPosition . clusterPosition ) ) ; } } positions . put ( recordOperation , physicalPosition ) ; rid . setClusterPosition ( physicalPosition . clusterPosition ) ; transaction . updateIdentityAfterCommit ( oldRID , rid ) ; } } lockRidBags ( clustersToLock , indexOperations , indexManager ) ; checkReadOnlyConditions ( ) ; for ( final ORecordOperation recordOperation : recordOperations ) { assert atomicOperation . getCounter ( ) == 1 ; commitEntry ( recordOperation , positions . get ( recordOperation ) , database . getSerializer ( ) ) ; assert atomicOperation . getCounter ( ) == 1 ; result . add ( recordOperation ) ; } lockIndexes ( indexOperations ) ; checkReadOnlyConditions ( ) ; commitIndexes ( indexOperations , atomicOperation ) ; } catch ( final IOException | RuntimeException e ) { rollback = true ; if ( e instanceof RuntimeException ) { throw ( ( RuntimeException ) e ) ; } else { throw OException . wrapException ( new OStorageException ( "Error during transaction commit" ) , e ) ; } } finally { if ( rollback ) { rollback ( transaction ) ; } else { endStorageTx ( transaction , recordOperations ) ; } this . transaction . set ( null ) ; } } finally { atomicOperationsManager . ensureThatComponentsUnlocked ( ) ; database . getMetadata ( ) . clearThreadLocalSchemaSnapshot ( ) ; } } finally { try { if ( modificationLock ) { final List < ORID > recordLocks = new ArrayList < > ( ) ; for ( final ORecordOperation recordOperation : recordOperations ) { if ( recordOperation . type == ORecordOperation . UPDATED || recordOperation . type == ORecordOperation . DELETED ) { recordLocks . add ( recordOperation . getRID ( ) ) ; } } final Set < ORID > locked = transaction . getLockedRecords ( ) ; if ( locked != null ) { recordLocks . removeAll ( locked ) ; } for ( final ORID rid : recordLocks ) { releaseWriteLock ( rid ) ; } } } finally { stateLock . releaseReadLock ( ) ; } } if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) { OLogManager . instance ( ) . debug ( this , "%d Committed transaction %d on database '%s' (result=%s)" , Thread . currentThread ( ) . getId ( ) , transaction . getId ( ) , database . getName ( ) , result ) ; } return result ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { handleJVMError ( ee ) ; OAtomicOperationsManager . alarmClearOfAtomicOperation ( ) ; throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * Puts the given value under the given key into this storage for the index with the given index id . Validates the operation using
 * the provided validator .
 * @ param indexId the index id of the index to put the value into .
 * @ param key the key to put the value under .
 * @ param value the value to put .
 * @ param validator the operation validator .
 * @ return { @ code true } if the validator allowed the put , { @ code false } otherwise .
 * @ see OBaseIndexEngine . Validator # validate ( Object , Object , Object ) */
@ SuppressWarnings ( "UnusedReturnValue" ) public boolean validatedPutIndexValue ( int indexId , final Object key , final ORID value , final OBaseIndexEngine . Validator < Object , ORID > validator ) throws OInvalidIndexEngineIdException { } }

implementation: indexId = extractInternalId ( indexId ) ; try { if ( transaction . get ( ) != null ) { return doValidatedPutIndexValue ( indexId , key , value , validator ) ; } checkOpenness ( ) ; stateLock . acquireReadLock ( ) ; try { checkOpenness ( ) ; checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) ; return doValidatedPutIndexValue ( indexId , key , value , validator ) ; } finally { stateLock . releaseReadLock ( ) ; } } catch ( final OInvalidIndexEngineIdException ie ) { throw logAndPrepareForRethrow ( ie ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * Rollbacks the given micro - transaction .
 * @ param microTransaction the micro - transaction to rollback . */
public void rollback ( final OMicroTransaction microTransaction ) { } }

implementation: try { checkOpenness ( ) ; stateLock . acquireReadLock ( ) ; try { try { checkOpenness ( ) ; if ( transaction . get ( ) == null ) { return ; } if ( transaction . get ( ) . getMicroTransaction ( ) . getId ( ) != microTransaction . getId ( ) ) { throw new OStorageException ( "Passed in and active micro-transaction are different micro-transactions. Passed in micro-transaction cannot be " + "rolled back." ) ; } makeStorageDirty ( ) ; rollbackStorageTx ( ) ; microTransaction . updateRecordCacheAfterRollback ( ) ; txRollback . incrementAndGet ( ) ; } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( "Error during micro-transaction rollback" ) , e ) ; } finally { transaction . set ( null ) ; } } finally { stateLock . releaseReadLock ( ) ; } } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * Method that completes the cluster rename operation . < strong > IT WILL NOT RENAME A CLUSTER , IT JUST CHANGES THE NAME IN THE
 * INTERNAL MAPPING < / strong > */
public final void renameCluster ( final String oldName , final String newName ) { } }

implementation: try { clusterMap . put ( newName . toLowerCase ( configuration . getLocaleInstance ( ) ) , clusterMap . remove ( oldName . toLowerCase ( configuration . getLocaleInstance ( ) ) ) ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * Executes the command request and return the result back . */
@ Override public final Object command ( final OCommandRequestText iCommand ) { } }

implementation:
try { while ( true ) { try { final OCommandExecutor executor = OCommandManager . instance ( ) . getExecutor ( iCommand ) ; // COPY THE CONTEXT FROM THE REQUEST
executor . setContext ( iCommand . getContext ( ) ) ; executor . setProgressListener ( iCommand . getProgressListener ( ) ) ; executor . parse ( iCommand ) ; return executeCommand ( iCommand , executor ) ; } catch ( final ORetryQueryException ignore ) { if ( iCommand instanceof OQueryAbstract ) { final OQueryAbstract query = ( OQueryAbstract ) iCommand ; query . reset ( ) ; } } } } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee , false ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; }


signature:
public class OAbstractPaginatedStorage { /** * Register the cluster internally .
 * @ param cluster OCluster implementation
 * @ return The id ( physical position into the array ) of the new cluster just created . First is 0. */
private int registerCluster ( final OCluster cluster ) { } }

implementation:
final int id ; if ( cluster != null ) { // CHECK FOR DUPLICATION OF NAMES
if ( clusterMap . containsKey ( cluster . getName ( ) . toLowerCase ( configuration . getLocaleInstance ( ) ) ) ) { throw new OConfigurationException ( "Cannot add cluster '" + cluster . getName ( ) + "' because it is already registered in database '" + name + "'" ) ; } // CREATE AND ADD THE NEW REF SEGMENT
clusterMap . put ( cluster . getName ( ) . toLowerCase ( configuration . getLocaleInstance ( ) ) , cluster ) ; id = cluster . getId ( ) ; } else { id = clusters . size ( ) ; } setCluster ( id , cluster ) ; return id ;


signature:
public class OAbstractPaginatedStorage { /** * Method which is called before any data modification operation to check alarm conditions such as : < ol > < li > Low disk space < / li >
 * < li > Exception during data flush in background threads < / li > < li > Broken files < / li > < / ol >
 * If one of those conditions are satisfied data modification operation is aborted and storage is switched in " read only " mode . */
private void checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) { } }

implementation: if ( transaction . get ( ) != null ) { return ; } if ( lowDiskSpace != null ) { if ( checkpointInProgress . compareAndSet ( false , true ) ) { try { if ( writeCache . checkLowDiskSpace ( ) ) { OLogManager . instance ( ) . error ( this , "Not enough disk space, force sync will be called" , null ) ; synch ( ) ; if ( writeCache . checkLowDiskSpace ( ) ) { throw new OLowDiskSpaceException ( "Error occurred while executing a write operation to database '" + name + "' due to limited free space on the disk (" + ( lowDiskSpace . freeSpace / ( 1024 * 1024 ) ) + " MB). The database is now working in read-only mode." + " Please close the database (or stop OrientDB), make room on your hard drive and then reopen the database. " + "The minimal required space is " + ( lowDiskSpace . requiredSpace / ( 1024 * 1024 ) ) + " MB. " + "Required space is now set to " + configuration . getContextConfiguration ( ) . getValueAsInteger ( OGlobalConfiguration . DISK_CACHE_FREE_SPACE_LIMIT ) + "MB (you can change it by setting parameter " + OGlobalConfiguration . DISK_CACHE_FREE_SPACE_LIMIT . getKey ( ) + ") ." ) ; } else { lowDiskSpace = null ; } } else { lowDiskSpace = null ; } } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( "Error during low disk space handling" ) , e ) ; } finally { checkpointInProgress . set ( false ) ; } } } checkReadOnlyConditions ( ) ;


signature:
public class OPartitionedDatabasePool { /** * Sets a property value
 * @ param iName Property name
 * @ param iValue new value to set
 * @ return The previous value if any , otherwise null */
public Object setProperty ( final String iName , final Object iValue ) { } }

implementation: if ( iValue != null ) { return properties . put ( iName . toLowerCase ( Locale . ENGLISH ) , iValue ) ; } else { return properties . remove ( iName . toLowerCase ( Locale . ENGLISH ) ) ; }


signature:
public class OCommandExecutorSQLCreateClass { /** * Execute the CREATE CLASS . */
public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation: if ( className == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseDocument database = getDatabase ( ) ; boolean alreadyExists = database . getMetadata ( ) . getSchema ( ) . existsClass ( className ) ; if ( ! alreadyExists || ! ifNotExists ) { if ( clusters != null ) database . getMetadata ( ) . getSchema ( ) . createClass ( className , clusters , superClasses . toArray ( new OClass [ 0 ] ) ) ; else database . getMetadata ( ) . getSchema ( ) . createClass ( className , clusterIds , superClasses . toArray ( new OClass [ 0 ] ) ) ; } return database . getMetadata ( ) . getSchema ( ) . getClasses ( ) . size ( ) ;


signature:
public class OrientVertexQuery { /** * ( Blueprints Extension ) Counts the total items found . This method is more efficient than executing the query and browse the
 * returning Iterable .
 * @ return */
@ Override public long count ( ) { } }

implementation:
if ( hasContainers . isEmpty ( ) ) { // NO CONDITIONS : USE THE FAST COUNT
long counter = ( ( OrientVertex ) vertex ) . countEdges ( direction , labels ) ; if ( limit != Integer . MAX_VALUE && counter > limit ) return limit ; return counter ; } // ITERATE EDGES TO MATCH CONDITIONS
return super . count ( ) ;


signature:
public class OCommandExecutorSQLHASyncDatabase { /** * Execute the SYNC DATABASE . */
public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation: final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . DATABASE , "sync" , ORole . PERMISSION_UPDATE ) ; final OStorage stg = database . getStorage ( ) ; if ( ! ( stg instanceof ODistributedStorage ) ) throw new ODistributedException ( "SYNC DATABASE command cannot be executed against a non distributed server" ) ; final ODistributedStorage dStg = ( ODistributedStorage ) stg ; final OHazelcastPlugin dManager = ( OHazelcastPlugin ) dStg . getDistributedManager ( ) ; if ( dManager == null || ! dManager . isEnabled ( ) ) throw new OCommandExecutionException ( "OrientDB is not started in distributed mode" ) ; final String databaseName = database . getName ( ) ; return dManager . installDatabase ( true , databaseName , parsedStatement . isForce ( ) , ! parsedStatement . isFull ( ) ) ;


signature:
public class OLiveCommandExecutorSQLFactory { /** * { @ inheritDoc } */
public OCommandExecutorSQLAbstract createCommand ( final String name ) throws OCommandExecutionException { } }

implementation: final Class < ? extends OCommandExecutorSQLAbstract > clazz = COMMANDS . get ( name ) ; if ( clazz == null ) { throw new OCommandExecutionException ( "Unknowned command name :" + name ) ; } try { return clazz . newInstance ( ) ; } catch ( Exception e ) { throw OException . wrapException ( new OCommandExecutionException ( "Error in creation of command " + name + "(). Probably there is not an empty constructor or the constructor generates errors" ) , e ) ; }


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < RET extends ORecord > RET load ( final ORID iRecordId , final String iFetchPlan , final boolean iIgnoreCache ) { } }

implementation: return ( RET ) executeReadRecord ( ( ORecordId ) iRecordId , null , - 1 , iFetchPlan , iIgnoreCache , ! iIgnoreCache , false , OStorage . LOCKING_STRATEGY . DEFAULT , new SimpleRecordReader ( prefetchRecords ) ) ;


signature:
public class ODatabaseDocumentAbstract { /** * Deletes the record checking the version . */
public ODatabase < ORecord > delete ( final ORID iRecord , final int iVersion ) { } }

implementation: ORecord record = load ( iRecord ) ; ORecordInternal . setVersion ( record , iVersion ) ; delete ( record ) ; return this ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
@ Override @ Deprecated public < REC extends ORecord > ORecordIteratorCluster < REC > browseCluster ( final String iClusterName , final Class < REC > iRecordClass , final long startClusterPosition , final long endClusterPosition , final boolean loadTombstones ) { } }

implementation: checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; checkIfActive ( ) ; final int clusterId = getClusterIdByName ( iClusterName ) ; return new ORecordIteratorCluster < REC > ( this , clusterId , startClusterPosition , endClusterPosition , OStorage . LOCKING_STRATEGY . DEFAULT ) ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public OCommandRequest command ( final OCommandRequest iCommand ) { } }

implementation: checkSecurity ( ORule . ResourceGeneric . COMMAND , ORole . PERMISSION_READ ) ; checkIfActive ( ) ; final OCommandRequestInternal command = ( OCommandRequestInternal ) iCommand ; try { command . reset ( ) ; return command ; } catch ( Exception e ) { throw OException . wrapException ( new ODatabaseException ( "Error on command execution" ) , e ) ; }


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < RET extends List < ? > > RET query ( final OQuery < ? > iCommand , final Object ... iArgs ) { } }

implementation: checkIfActive ( ) ; iCommand . reset ( ) ; return ( RET ) iCommand . execute ( iArgs ) ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
@ Override public long countClusterElements ( int [ ] iClusterIds , boolean countTombstones ) { } }

implementation: checkIfActive ( ) ; String name ; for ( int iClusterId : iClusterIds ) { name = getClusterNameById ( iClusterId ) ; checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , name ) ; } return getStorage ( ) . count ( iClusterIds , countTombstones ) ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
@ Override public long countClusterElements ( final String iClusterName ) { } }

implementation: checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; checkIfActive ( ) ; final int clusterId = getClusterIdByName ( iClusterName ) ; if ( clusterId < 0 ) throw new IllegalArgumentException ( "Cluster '" + iClusterName + "' was not found" ) ; return getStorage ( ) . count ( clusterId ) ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < DB extends ODatabaseDocument > DB checkSecurity ( final ORule . ResourceGeneric resourceGeneric , final String resourceSpecific , final int iOperation ) { } }

implementation: if ( user != null ) { try { user . allow ( resourceGeneric , resourceSpecific , iOperation ) ; } catch ( OSecurityAccessException e ) { if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . debug ( this , "User '%s' tried to access the reserved resource '%s.%s', operation '%s'" , getUser ( ) , resourceGeneric , resourceSpecific , iOperation ) ; throw e ; } } return ( DB ) this ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < DB extends ODatabaseDocument > DB checkSecurity ( final ORule . ResourceGeneric iResourceGeneric , final int iOperation , final Object ... iResourcesSpecific ) { } }

implementation: if ( user != null ) { try { if ( iResourcesSpecific . length != 0 ) { for ( Object target : iResourcesSpecific ) { if ( target != null ) { user . allow ( iResourceGeneric , target . toString ( ) , iOperation ) ; } else user . allow ( iResourceGeneric , null , iOperation ) ; } } else user . allow ( iResourceGeneric , null , iOperation ) ; } catch ( OSecurityAccessException e ) { if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . debug ( this , "[checkSecurity] User '%s' tried to access the reserved resource '%s', target(s) '%s', operation '%s'" , getUser ( ) , iResourceGeneric , Arrays . toString ( iResourcesSpecific ) , iOperation ) ; throw e ; } } return ( DB ) this ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < DB extends ODatabaseDocument > DB checkSecurity ( final ORule . ResourceGeneric iResourceGeneric , final int iOperation , final Object iResourceSpecific ) { } }

implementation: checkOpenness ( ) ; if ( user != null ) { try { if ( iResourceSpecific != null ) user . allow ( iResourceGeneric , iResourceSpecific . toString ( ) , iOperation ) ; else user . allow ( iResourceGeneric , null , iOperation ) ; } catch ( OSecurityAccessException e ) { if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . debug ( this , "[checkSecurity] User '%s' tried to access the reserved resource '%s', target '%s', operation '%s'" , getUser ( ) , iResourceGeneric , iResourceSpecific , iOperation ) ; throw e ; } } return ( DB ) this ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < DB extends ODatabase > DB setStatus ( final STATUS status ) { } }

implementation: checkIfActive ( ) ; setStatusInternal ( status ) ; return ( DB ) this ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public void setUser ( final OSecurityUser user ) { } }

implementation: checkIfActive ( ) ; if ( user instanceof OUser ) { OMetadata metadata = getMetadata ( ) ; if ( metadata != null ) { final OSecurity security = metadata . getSecurity ( ) ; this . user = new OImmutableUser ( security . getVersion ( ) , ( OUser ) user ) ; } else this . user = new OImmutableUser ( - 1 , ( OUser ) user ) ; } else this . user = ( OImmutableUser ) user ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < DB extends ODatabase < ? > > DB registerHook ( final ORecordHook iHookImpl , final ORecordHook . HOOK_POSITION iPosition ) { } }

implementation: checkOpenness ( ) ; checkIfActive ( ) ; final Map < ORecordHook , ORecordHook . HOOK_POSITION > tmp = new LinkedHashMap < ORecordHook , ORecordHook . HOOK_POSITION > ( hooks ) ; tmp . put ( iHookImpl , iPosition ) ; hooks . clear ( ) ; for ( ORecordHook . HOOK_POSITION p : ORecordHook . HOOK_POSITION . values ( ) ) { for ( Map . Entry < ORecordHook , ORecordHook . HOOK_POSITION > e : tmp . entrySet ( ) ) { if ( e . getValue ( ) == p ) hooks . put ( e . getKey ( ) , e . getValue ( ) ) ; } } compileHooks ( ) ; return ( DB ) this ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < DB extends ODatabase < ? > > DB registerHook ( final ORecordHook iHookImpl ) { } }

implementation: return ( DB ) registerHook ( iHookImpl , ORecordHook . HOOK_POSITION . REGULAR ) ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < DB extends ODatabase < ? > > DB unregisterHook ( final ORecordHook iHookImpl ) { } }

implementation: checkIfActive ( ) ; if ( iHookImpl != null ) { iHookImpl . onUnregister ( ) ; hooks . remove ( iHookImpl ) ; compileHooks ( ) ; } return ( DB ) this ;


signature:
public class ODatabaseDocumentAbstract { /** * Callback the registered hooks if any .
 * @ param type Hook type . Define when hook is called .
 * @ param id Record received in the callback
 * @ return True if the input record is changed , otherwise false */
public ORecordHook . RESULT callbackHooks ( final ORecordHook . TYPE type , final OIdentifiable id ) { } }

implementation:
if ( id == null || hooks . isEmpty ( ) || id . getIdentity ( ) . getClusterId ( ) == 0 ) return ORecordHook . RESULT . RECORD_NOT_CHANGED ; final ORecordHook . SCOPE scope = ORecordHook . SCOPE . typeToScope ( type ) ; final int scopeOrdinal = scope . ordinal ( ) ; final ORID identity = id . getIdentity ( ) . copy ( ) ; if ( ! pushInHook ( identity ) ) return ORecordHook . RESULT . RECORD_NOT_CHANGED ; try { final ORecord rec = id . getRecord ( ) ; if ( rec == null ) return ORecordHook . RESULT . RECORD_NOT_CHANGED ; final OScenarioThreadLocal . RUN_MODE runMode = OScenarioThreadLocal . INSTANCE . getRunMode ( ) ; boolean recordChanged = false ; for ( ORecordHook hook : hooksByScope [ scopeOrdinal ] ) { switch ( runMode ) { case DEFAULT : // NON _ DISTRIBUTED OR PROXIED DB
if ( getStorage ( ) . isDistributed ( ) && hook . getDistributedExecutionMode ( ) == ORecordHook . DISTRIBUTED_EXECUTION_MODE . TARGET_NODE ) // SKIP
continue ; break ; // TARGET NODE
case RUNNING_DISTRIBUTED : if ( hook . getDistributedExecutionMode ( ) == ORecordHook . DISTRIBUTED_EXECUTION_MODE . SOURCE_NODE ) continue ; } final ORecordHook . RESULT res = hook . onTrigger ( type , rec ) ; if ( res == ORecordHook . RESULT . RECORD_CHANGED ) recordChanged = true ; else if ( res == ORecordHook . RESULT . SKIP_IO ) // SKIP IO OPERATION
return res ; else if ( res == ORecordHook . RESULT . SKIP ) // SKIP NEXT HOOKS AND RETURN IT
return res ; else if ( res == ORecordHook . RESULT . RECORD_REPLACED ) return res ; } return recordChanged ? ORecordHook . RESULT . RECORD_CHANGED : ORecordHook . RESULT . RECORD_NOT_CHANGED ; } finally { popInHook ( identity ) ; }


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < DB extends ODatabaseDocument > DB setValidationEnabled ( final boolean iEnabled ) { } }

implementation: set ( ATTRIBUTES . VALIDATION , iEnabled ) ; return ( DB ) this ;


signature:
public class ODatabaseDocumentAbstract { /** * Deletes the record without checking the version . */
public ODatabaseDocument delete ( final ORID iRecord ) { } }

implementation: checkOpenness ( ) ; checkIfActive ( ) ; final ORecord rec = load ( iRecord ) ; if ( rec != null ) delete ( rec ) ; return this ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public < RET extends ORecord > RET load ( final ORecord iRecord , final String iFetchPlan , final boolean iIgnoreCache ) { } }

implementation: return ( RET ) executeReadRecord ( ( ORecordId ) iRecord . getIdentity ( ) , iRecord , - 1 , iFetchPlan , iIgnoreCache , ! iIgnoreCache , false , OStorage . LOCKING_STRATEGY . NONE , new SimpleRecordReader ( prefetchRecords ) ) ;


signature:
public class ODatabaseDocumentAbstract { /** * This method is internal , it can be subject to signature change or be removed , do not use .
 * @ Internal */
public boolean executeHideRecord ( OIdentifiable record , final OPERATION_MODE iMode ) { } }

implementation:
checkOpenness ( ) ; checkIfActive ( ) ; final ORecordId rid = ( ORecordId ) record . getIdentity ( ) ; if ( rid == null ) throw new ODatabaseException ( "Cannot hide record because it has no identity. Probably was created from scratch or contains projections of fields rather than a full record" ) ; if ( ! rid . isValid ( ) ) return false ; checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_DELETE , getClusterNameById ( rid . getClusterId ( ) ) ) ; getMetadata ( ) . makeThreadLocalSchemaSnapshot ( ) ; if ( record instanceof ODocument ) ODocumentInternal . checkClass ( ( ODocument ) record , this ) ; ORecordSerializationContext . pushContext ( ) ; try { final OStorageOperationResult < Boolean > operationResult ; operationResult = getStorage ( ) . hideRecord ( rid , iMode . ordinal ( ) , null ) ; // REMOVE THE RECORD FROM 1 AND 2 LEVEL CACHES
if ( ! operationResult . isMoved ( ) ) getLocalCache ( ) . deleteRecord ( rid ) ; return operationResult . getResult ( ) ; } finally { ORecordSerializationContext . pullContext ( ) ; getMetadata ( ) . clearThreadLocalSchemaSnapshot ( ) ; }


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
@ Override public void freeze ( final boolean throwException ) { } }

implementation: checkOpenness ( ) ; if ( ! ( getStorage ( ) instanceof OFreezableStorageComponent ) ) { OLogManager . instance ( ) . error ( this , "Only local paginated storage supports freeze. If you are using remote client please use OServerAdmin instead" , null ) ; return ; } final long startTime = Orient . instance ( ) . getProfiler ( ) . startChrono ( ) ; final OFreezableStorageComponent storage = getFreezableStorage ( ) ; if ( storage != null ) { storage . freeze ( throwException ) ; } Orient . instance ( ) . getProfiler ( ) . stopChrono ( "db." + getName ( ) + ".freeze" , "Time to freeze the database" , startTime , "db.*.freeze" ) ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
public ORecordIteratorClass < ODocument > browseClass ( final String iClassName , final boolean iPolymorphic ) { } }

implementation: if ( getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getClass ( iClassName ) == null ) throw new IllegalArgumentException ( "Class '" + iClassName + "' not found in current database" ) ; checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_READ , iClassName ) ; return new ORecordIteratorClass < ODocument > ( this , iClassName , iPolymorphic , false ) ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
@ Override public ORecordIteratorCluster < ODocument > browseCluster ( final String iClusterName ) { } }

implementation: checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; return new ORecordIteratorCluster < ODocument > ( this , getClusterIdByName ( iClusterName ) ) ;


signature:
public class ODatabaseDocumentAbstract { /** * { @ inheritDoc } */
@ Override @ Deprecated public ORecordIteratorCluster < ODocument > browseCluster ( String iClusterName , long startClusterPosition , long endClusterPosition , boolean loadTombstones ) { } }

implementation: checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; return new ORecordIteratorCluster < ODocument > ( this , getClusterIdByName ( iClusterName ) , startClusterPosition , endClusterPosition , OStorage . LOCKING_STRATEGY . DEFAULT ) ;


signature:
public class ODatabaseDocumentAbstract { /** * Saves a document to the database . Behavior depends by the current running transaction if any . If no transaction is running then
 * changes apply immediately . If an Optimistic transaction is running then the record will be changed at commit time . The current
 * transaction will continue to see the record as modified , while others not . If a Pessimistic transaction is running , then an
 * exclusive lock is acquired against the record . Current transaction will continue to see the record as modified , while others
 * cannot access to it since it ' s locked .
 * If MVCC is enabled and the version of the document is different by the version stored in the database , then a { @ link
 * OConcurrentModificationException } exception is thrown . Before to save the document it must be valid following the constraints
 * declared in the schema if any ( can work also in schema - less mode ) . To validate the document the { @ link ODocument # validate ( ) } is
 * called .
 * @ param iRecord Record to save .
 * @ return The Database instance itself giving a " fluent interface " . Useful to call multiple methods in chain .
 * @ throws OConcurrentModificationException if the version of the document is different by the version contained in the database .
 * @ throws OValidationException if the document breaks some validation constraints defined in the schema
 * @ see # setMVCC ( boolean ) , { @ link # isMVCC ( ) } */
@ Override public < RET extends ORecord > RET save ( final ORecord iRecord ) { } }

implementation: return ( RET ) save ( iRecord , null , OPERATION_MODE . SYNCHRONOUS , false , null , null ) ;


signature:
public class ODatabaseDocumentAbstract { /** * Saves a document to the database . Behavior depends by the current running transaction if any . If no transaction is running then
 * changes apply immediately . If an Optimistic transaction is running then the record will be changed at commit time . The current
 * transaction will continue to see the record as modified , while others not . If a Pessimistic transaction is running , then an
 * exclusive lock is acquired against the record . Current transaction will continue to see the record as modified , while others
 * cannot access to it since it ' s locked .
 * If MVCC is enabled and the version of the document is different by the version stored in the database , then a { @ link
 * OConcurrentModificationException } exception is thrown . Before to save the document it must be valid following the constraints
 * declared in the schema if any ( can work also in schema - less mode ) . To validate the document the { @ link ODocument # validate ( ) } is
 * called .
 * @ param iRecord Record to save .
 * @ param iForceCreate Flag that indicates that record should be created . If record with current rid already exists ,
 * exception is thrown
 * @ param iRecordCreatedCallback callback that is called after creation of new record
 * @ param iRecordUpdatedCallback callback that is called after record update
 * @ return The Database instance itself giving a " fluent interface " . Useful to call multiple methods in chain .
 * @ throws OConcurrentModificationException if the version of the document is different by the version contained in the database .
 * @ throws OValidationException if the document breaks some validation constraints defined in the schema
 * @ see # setMVCC ( boolean ) , { @ link # isMVCC ( ) } */
@ Override public < RET extends ORecord > RET save ( final ORecord iRecord , final OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { } }

implementation: return save ( iRecord , null , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ;


signature:
public class ODatabaseDocumentAbstract { /** * Saves a document specifying a cluster where to store the record . Behavior depends by the current running transaction if any . If
 * no transaction is running then changes apply immediately . If an Optimistic transaction is running then the record will be
 * changed at commit time . The current transaction will continue to see the record as modified , while others not . If a Pessimistic
 * transaction is running , then an exclusive lock is acquired against the record . Current transaction will continue to see the
 * record as modified , while others cannot access to it since it ' s locked .
 * If MVCC is enabled and the version of the document is different by the version stored in the database , then a { @ link
 * OConcurrentModificationException } exception is thrown . Before to save the document it must be valid following the constraints
 * declared in the schema if any ( can work also in schema - less mode ) . To validate the document the { @ link ODocument # validate ( ) } is
 * called .
 * @ param iRecord Record to save
 * @ param iClusterName Cluster name where to save the record
 * @ param iMode Mode of save : synchronous ( default ) or asynchronous
 * @ param iForceCreate Flag that indicates that record should be created . If record with current rid already exists ,
 * exception is thrown
 * @ param iRecordCreatedCallback callback that is called after creation of new record
 * @ param iRecordUpdatedCallback callback that is called after record update
 * @ return The Database instance itself giving a " fluent interface " . Useful to call multiple methods in chain .
 * @ throws OConcurrentModificationException if the version of the document is different by the version contained in the database .
 * @ throws OValidationException if the document breaks some validation constraints defined in the schema
 * @ see # setMVCC ( boolean ) , { @ link # isMVCC ( ) } , ODocument # validate ( ) */
@ Override public < RET extends ORecord > RET save ( ORecord iRecord , String iClusterName , final OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { } }

implementation: checkOpenness ( ) ; if ( iRecord instanceof OVertex ) { iRecord = iRecord . getRecord ( ) ; } if ( iRecord instanceof OEdge ) { if ( ( ( OEdge ) iRecord ) . isLightweight ( ) ) { iRecord = ( ( OEdge ) iRecord ) . getFrom ( ) ; } else { iRecord = iRecord . getRecord ( ) ; } } ODirtyManager dirtyManager = ORecordInternal . getDirtyManager ( iRecord ) ; if ( iRecord instanceof OElement && dirtyManager != null && dirtyManager . getReferences ( ) != null && ! dirtyManager . getReferences ( ) . isEmpty ( ) ) { if ( ( ( ( OElement ) iRecord ) . isVertex ( ) || ( ( OElement ) iRecord ) . isEdge ( ) ) && ! getTransaction ( ) . isActive ( ) && inHook . isEmpty ( ) ) { return saveGraph ( iRecord , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; } } return saveInternal ( iRecord , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ;


signature:
public class ODatabaseDocumentAbstract { /** * Returns the number of the records of the class iClassName . */
public long countView ( final String viewName ) { } }

implementation: final OView cls = getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getView ( viewName ) ; if ( cls == null ) throw new IllegalArgumentException ( "View '" + cls + "' not found in database" ) ; return countClass ( cls , false ) ;


signature:
public class ODatabaseDocumentAbstract { /** * Returns the number of the records of the class iClassName considering also sub classes if polymorphic is true . */
public long countClass ( final String iClassName , final boolean iPolymorphic ) { } }

implementation: final OClass cls = getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getClass ( iClassName ) ; if ( cls == null ) throw new IllegalArgumentException ( "Class '" + cls + "' not found in database" ) ; return countClass ( cls , iPolymorphic ) ;


signature:
public class ODatabaseDocumentAbstract { /** * Activates current database instance on current thread . */
@ Override public ODatabaseDocumentAbstract activateOnCurrentThread ( ) { } }

implementation: final ODatabaseRecordThreadLocal tl = ODatabaseRecordThreadLocal . instance ( ) ; if ( tl != null ) tl . set ( this ) ; return this ;


signature:
public class OEncryptionFactory { /** * Registers a stateful implementations , a new instance will be created for each storage .
 * @ param iEncryption
 * Encryption instance */
public void register ( final OEncryption iEncryption ) { } }

implementation: try { final String name = iEncryption . name ( ) ; if ( instances . containsKey ( name ) ) throw new IllegalArgumentException ( "Encryption with name '" + name + "' was already registered" ) ; if ( classes . containsKey ( name ) ) throw new IllegalArgumentException ( "Encryption with name '" + name + "' was already registered" ) ; instances . put ( name , iEncryption ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Cannot register storage encryption algorithm '%s'" , e , iEncryption ) ; }


signature:
public class OrientBlob { /** * ( non - Javadoc )
 * @ see java . sql . Blob # getBytes ( long , int ) */
public byte [ ] getBytes ( long pos , int length ) throws SQLException { } }

implementation:
if ( pos < 1 ) throw new SQLException ( "The position of the first byte in the BLOB value to be " + "extracted cannot be less than 1" ) ; if ( length < 0 ) throw new SQLException ( "The number of the consecutive bytes in the BLOB value to " + "be extracted cannot be a negative number" ) ; int relativeIndex = this . getRelativeIndex ( pos ) ; ByteBuffer buffer = ByteBuffer . allocate ( length ) ; int j ; for ( j = 0 ; j < length ; j ++ ) { if ( relativeIndex == currentChunk . length ) { // go to the next chunk , if any . . .
currentChunkIndex ++ ; if ( currentChunkIndex < binaryDataChunks . size ( ) ) { // the next chunk exists so we update the relative index and
// the current chunk reference
relativeIndex = 0 ; currentChunk = binaryDataChunks . get ( currentChunkIndex ) ; } else // exit from the loop : there are no more bytes to be read
break ; } buffer . put ( currentChunk [ relativeIndex ] ) ; relativeIndex ++ ; } return buffer . array ( ) ;


signature:
public class OrientBlob { /** * Calculates the index within a binary chunk corresponding to the given absolute position within this BLOB
 * @ param pos
 * @ return */
private int getRelativeIndex ( long pos ) { } }

implementation:
int currentSize = 0 ; currentChunkIndex = 0 ; // loop until we find the chuks holding the given position
while ( pos >= ( currentSize += binaryDataChunks . get ( currentChunkIndex ) . length ) ) currentChunkIndex ++ ; currentChunk = binaryDataChunks . get ( currentChunkIndex ) ; currentSize -= currentChunk . length ; // the position referred to the target binary chunk
int relativePosition = ( int ) ( pos - currentSize ) ; // the index of the first byte to be returned
return relativePosition - 1 ;


signature:
public class OBaseParser { /** * Parses the next word . It returns the word parsed if any .
 * @ param iUpperCase
 * True if must return UPPERCASE , otherwise false
 * @ return The word parsed if any , otherwise null */
protected String parserOptionalWord ( final boolean iUpperCase ) { } }

implementation: parserPreviousPos = parserCurrentPos ; parserNextWord ( iUpperCase ) ; if ( parserLastWord . length ( ) == 0 ) return null ; return parserLastWord . toString ( ) ;


signature:
public class OBaseParser { /** * Parses the next word . If no word is found or the parsed word is not present in the word array received as parameter then a
 * SyntaxError exception with the custom message received as parameter is thrown . It returns the word parsed if any .
 * @ param iUpperCase
 * True if must return UPPERCASE , otherwise false
 * @ param iCustomMessage
 * Custom message to include in case of SyntaxError exception
 * @ param iSeparators
 * Separator characters
 * @ return The word parsed */
protected String parserRequiredWord ( final boolean iUpperCase , final String iCustomMessage , String iSeparators ) { } }

implementation: if ( iSeparators == null ) iSeparators = " ()=><,\r\n" ; parserNextWord ( iUpperCase , iSeparators ) ; if ( parserLastWord . length ( ) == 0 ) throwSyntaxErrorException ( iCustomMessage ) ; if ( parserLastWord . charAt ( 0 ) == '`' && parserLastWord . charAt ( parserLastWord . length ( ) - 1 ) == '`' ) { return parserLastWord . substring ( 1 , parserLastWord . length ( ) - 1 ) ; } return parserLastWord . toString ( ) ;


signature:
public class OBaseParser { /** * Parses the next sequence of chars .
 * @ return The position of the word matched if any , otherwise - 1 or an exception if iMandatory is true */
protected int parserNextChars ( final boolean iUpperCase , final boolean iMandatory , final String ... iCandidateWords ) { } }

implementation:
parserPreviousPos = parserCurrentPos ; parserSkipWhiteSpaces ( ) ; parserEscapeSequenceCount = 0 ; parserLastWord . setLength ( 0 ) ; final String [ ] processedWords = Arrays . copyOf ( iCandidateWords , iCandidateWords . length ) ; // PARSE THE CHARS
final String text2Use = iUpperCase ? parserTextUpperCase : parserText ; final int max = text2Use . length ( ) ; parserCurrentPos = parserCurrentPos + parserTextUpperCase . length ( ) - parserText . length ( ) ; // PARSE TILL 1 CHAR AFTER THE END TO SIMULATE A SEPARATOR AS EOF
for ( int i = 0 ; parserCurrentPos <= max ; ++ i ) { final char ch = parserCurrentPos < max ? text2Use . charAt ( parserCurrentPos ) : '\n' ; final boolean separator = ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t' || ch == '(' ; if ( ! separator ) parserLastWord . append ( ch ) ; // CLEAR CANDIDATES
int candidatesWordsCount = 0 ; int candidatesWordsPos = - 1 ; for ( int c = 0 ; c < processedWords . length ; ++ c ) { final String w = processedWords [ c ] ; if ( w != null ) { final int wordSize = w . length ( ) ; if ( ( separator && wordSize > i ) || ( ! separator && ( i > wordSize - 1 || w . charAt ( i ) != ch ) ) ) // DISCARD IT
processedWords [ c ] = null ; else { candidatesWordsCount ++ ; if ( candidatesWordsCount == 1 ) // REMEMBER THE POSITION
candidatesWordsPos = c ; } } } if ( candidatesWordsCount == 1 ) { // ONE RESULT , CHECKING IF FOUND
final String w = processedWords [ candidatesWordsPos ] ; if ( w . length ( ) == i + ( separator ? 0 : 1 ) && ! Character . isLetter ( ch ) ) // FOUND !
return candidatesWordsPos ; } if ( candidatesWordsCount == 0 || separator ) break ; parserCurrentPos ++ ; } if ( iMandatory ) throwSyntaxErrorException ( "Found unexpected keyword '" + parserLastWord + "' while it was expected '" + Arrays . toString ( iCandidateWords ) + "'" ) ; return - 1 ;


signature:
public class OBaseParser { /** * Parses optional keywords between the iWords . If a keyword is found but doesn ' t match with iWords then a SyntaxError is raised .
 * @ param iWords
 * Optional words to match as keyword . If at least one is passed , then the check is made
 * @ return true if a keyword was found , otherwise false */
protected boolean parserOptionalKeyword ( final String ... iWords ) { } }

implementation:
parserNextWord ( true , " \r\n," ) ; if ( parserLastWord . length ( ) == 0 ) return false ; // FOUND : CHECK IF IT ' S IN RANGE
boolean found = iWords . length == 0 ; for ( String w : iWords ) { if ( parserLastWord . toString ( ) . equals ( w ) ) { found = true ; break ; } } if ( ! found ) throwSyntaxErrorException ( "Found unexpected keyword '" + parserLastWord + "' while it was expected '" + Arrays . toString ( iWords ) + "'" ) ; return true ;


signature:
public class OBaseParser { /** * Check for a separator
 * @ param c
 * @ param iSeparatorChars
 * @ return */
private boolean parserCheckSeparator ( final char c , final String iSeparatorChars ) { } }

implementation: for ( int sepIndex = 0 ; sepIndex < iSeparatorChars . length ( ) ; ++ sepIndex ) { if ( iSeparatorChars . charAt ( sepIndex ) == c ) { parserLastSeparator = c ; return true ; } } return false ;


signature:
public class OSQLFunctionPathFinder { /** * This method returns the path from the source to the selected target and NULL if no path exists */
public LinkedList < OrientVertex > getPath ( ) { } }

implementation:
final LinkedList < OrientVertex > path = new LinkedList < OrientVertex > ( ) ; OrientVertex step = paramDestinationVertex ; // Check if a path exists
if ( predecessors . get ( step . getIdentity ( ) ) == null ) return null ; path . add ( step ) ; while ( predecessors . get ( step . getIdentity ( ) ) != null ) { step = predecessors . get ( step . getIdentity ( ) ) ; path . add ( step ) ; } // Put it into the correct order
Collections . reverse ( path ) ; return path ;


signature:
public class OCommandExecutorSQLDropClass { /** * Execute the DROP CLASS . */
public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation:
if ( className == null ) { throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; } final ODatabaseDocument database = getDatabase ( ) ; if ( ifExists && ! database . getMetadata ( ) . getSchema ( ) . existsClass ( className ) ) { return true ; } final OClass cls = database . getMetadata ( ) . getSchema ( ) . getClass ( className ) ; if ( cls == null ) { return null ; } final long records = cls . count ( true ) ; if ( records > 0 && ! unsafe ) { // NOT EMPTY , CHECK IF CLASS IS OF VERTEX OR EDGES
if ( cls . isSubClassOf ( "V" ) ) { // FOUND VERTEX CLASS
throw new OCommandExecutionException ( "'DROP CLASS' command cannot drop class '" + className + "' because it contains Vertices. Use 'DELETE VERTEX' command first to avoid broken edges in a database, or apply the 'UNSAFE' keyword to force it" ) ; } else if ( cls . isSubClassOf ( "E" ) ) { // FOUND EDGE CLASS
throw new OCommandExecutionException ( "'DROP CLASS' command cannot drop class '" + className + "' because it contains Edges. Use 'DELETE EDGE' command first to avoid broken vertices in a database, or apply the 'UNSAFE' keyword to force it" ) ; } } database . getMetadata ( ) . getSchema ( ) . dropClass ( className ) ; if ( records > 0 && unsafe ) { // NOT EMPTY , CHECK IF CLASS IS OF VERTEX OR EDGES
if ( cls . isSubClassOf ( "V" ) ) { // FOUND VERTICES
if ( unsafe ) OLogManager . instance ( ) . warn ( this , "Dropped class '%s' containing %d vertices using UNSAFE mode. Database could contain broken edges" , className , records ) ; } else if ( cls . isSubClassOf ( "E" ) ) { // FOUND EDGES
OLogManager . instance ( ) . warn ( this , "Dropped class '%s' containing %d edges using UNSAFE mode. Database could contain broken vertices" , className , records ) ; } } return true ;


signature:
public class OStorageConfigurationSegment { /** * Remove both backup and primary configuration files on delete
 * @ see # update ( ) */
private void clearConfigurationFiles ( ) throws IOException { } }

implementation: final Path file = storagePath . resolve ( NAME ) ; Files . deleteIfExists ( file ) ; final Path backupFile = storagePath . resolve ( BACKUP_NAME ) ; Files . deleteIfExists ( backupFile ) ;


signature:
public class OObjectLazyList { /** * Convert the item requested .
 * @ param iIndex
 * Position of the item to convert */
private void convert ( final int iIndex ) { } }

implementation: if ( converted || ! convertToRecord ) return ; Object o = super . get ( iIndex ) ; if ( o == null ) { final ODatabaseDocument database = getDatabase ( ) . getUnderlying ( ) ; o = recordList . get ( iIndex ) ; ODocument doc ; if ( o instanceof ORID ) { doc = database . load ( ( ORID ) o , fetchPlan ) ; } else { doc = ( ODocument ) o ; } if ( o == null ) { OLogManager . instance ( ) . warn ( this , "Record " + ( ( OObjectProxyMethodHandler ) sourceRecord . getHandler ( ) ) . getDoc ( ) . getIdentity ( ) + " references a deleted instance" ) ; return ; } super . set ( iIndex , ( TYPE ) OObjectEntityEnhancer . getInstance ( ) . getProxiedInstance ( doc . getClassName ( ) , getDatabase ( ) . getEntityManager ( ) , doc , sourceRecord ) ) ; }


signature:
public class OMemoryInputStream { /** * Browse the stream but just return the begin of the byte array . This is used to lazy load the information only when needed . */
public int getAsByteArrayOffset ( ) { } }

implementation: if ( position >= length ) return - 1 ; final int begin = position ; final int size = OBinaryProtocol . bytes2int ( buffer , position ) ; position += OBinaryProtocol . SIZE_INT + size ; return begin ;


signature:
public class OAuth2FeignRequestInterceptor { /** * Extracts the token extract id the access token exists or returning an empty extract
 * if there is no one on the context it may occasionally causes Unauthorized response
 * since the token extract is empty .
 * @ param tokenType type name of token
 * @ return token value from context if it exists otherwise empty String */
protected String extract ( String tokenType ) { } }

implementation: OAuth2AccessToken accessToken = getToken ( ) ; return String . format ( "%s %s" , tokenType , accessToken . getValue ( ) ) ;


signature:
public class OAuth2FeignRequestInterceptor { /** * Extract the access token within the request or try to acquire a new one by
 * delegating it to { @ link # acquireAccessToken ( ) } .
 * @ return valid token */
public OAuth2AccessToken getToken ( ) { } }

implementation: OAuth2AccessToken accessToken = oAuth2ClientContext . getAccessToken ( ) ; if ( accessToken == null || accessToken . isExpired ( ) ) { try { accessToken = acquireAccessToken ( ) ; } catch ( UserRedirectRequiredException e ) { oAuth2ClientContext . setAccessToken ( null ) ; String stateKey = e . getStateKey ( ) ; if ( stateKey != null ) { Object stateToPreserve = e . getStateToPreserve ( ) ; if ( stateToPreserve == null ) { stateToPreserve = "NONE" ; } oAuth2ClientContext . setPreservedState ( stateKey , stateToPreserve ) ; } throw e ; } } return accessToken ;


signature:
public class OAuth2FeignRequestInterceptor { /** * Try to acquire the token using a access token provider .
 * @ return valid access token
 * @ throws UserRedirectRequiredException in case the user needs to be redirected to an
 * approval page or login page */
protected OAuth2AccessToken acquireAccessToken ( ) throws UserRedirectRequiredException { } }

implementation: AccessTokenRequest tokenRequest = oAuth2ClientContext . getAccessTokenRequest ( ) ; if ( tokenRequest == null ) { throw new AccessTokenRequiredException ( "Cannot find valid context on request for resource '" + resource . getId ( ) + "'." , resource ) ; } String stateKey = tokenRequest . getStateKey ( ) ; if ( stateKey != null ) { tokenRequest . setPreservedState ( oAuth2ClientContext . removePreservedState ( stateKey ) ) ; } OAuth2AccessToken existingToken = oAuth2ClientContext . getAccessToken ( ) ; if ( existingToken != null ) { oAuth2ClientContext . setAccessToken ( existingToken ) ; } OAuth2AccessToken obtainableAccessToken ; obtainableAccessToken = accessTokenProvider . obtainAccessToken ( resource , tokenRequest ) ; if ( obtainableAccessToken == null || obtainableAccessToken . getValue ( ) == null ) { throw new IllegalStateException ( " Access token provider returned a null token, which is illegal according to the contract." ) ; } oAuth2ClientContext . setAccessToken ( obtainableAccessToken ) ; return obtainableAccessToken ;


signature:
public class AccessTokenContextRelay { /** * Attempt to copy an access token from the security context into the oauth2 context .
 * @ return true if the token was copied */
public boolean copyToken ( ) { } }

implementation: if ( context . getAccessToken ( ) == null ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication != null ) { Object details = authentication . getDetails ( ) ; if ( details instanceof OAuth2AuthenticationDetails ) { OAuth2AuthenticationDetails holder = ( OAuth2AuthenticationDetails ) details ; String token = holder . getTokenValue ( ) ; DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken ( token ) ; String tokenType = holder . getTokenType ( ) ; if ( tokenType != null ) { accessToken . setTokenType ( tokenType ) ; } context . setAccessToken ( accessToken ) ; return true ; } } } return false ;


signature:
public class SpringContext { /** * 向spring添加bean的定义 */
public void put ( String name , Class < ? > clazz ) { } }

implementation: BeanDefinition definition = new RootBeanDefinition ( clazz ) ; beanFactory . registerBeanDefinition ( name , definition ) ;


signature:
public class TaskParser { /** * 由于任务节点需要解析form 、 assignee属性 , 这里覆盖抽象类方法实现 */
protected void parseNode ( NodeModel node , Element element ) { } }

implementation: TaskModel task = ( TaskModel ) node ; task . setForm ( element . getAttribute ( ATTR_FORM ) ) ; task . setAssignee ( element . getAttribute ( ATTR_ASSIGNEE ) ) ; task . setExpireTime ( element . getAttribute ( ATTR_EXPIRETIME ) ) ; task . setAutoExecute ( element . getAttribute ( ATTR_AUTOEXECUTE ) ) ; task . setCallback ( element . getAttribute ( ATTR_CALLBACK ) ) ; task . setReminderTime ( element . getAttribute ( ATTR_REMINDERTIME ) ) ; task . setReminderRepeat ( element . getAttribute ( ATTR_REMINDERREPEAT ) ) ; task . setPerformType ( element . getAttribute ( ATTR_PERFORMTYPE ) ) ; task . setTaskType ( element . getAttribute ( ATTR_TASKTYPE ) ) ; task . setAssignmentHandler ( element . getAttribute ( ATTR_ASSIGNEE_HANDLER ) ) ; NodeList fieldList = element . getElementsByTagName ( ATTR_FIELD ) ; List < FieldModel > fields = new ArrayList < FieldModel > ( ) ; for ( int i = 0 ; i < fieldList . getLength ( ) ; i ++ ) { Element item = ( Element ) fieldList . item ( i ) ; FieldModel fieldModel = new FieldModel ( ) ; fieldModel . setName ( item . getAttribute ( ATTR_NAME ) ) ; fieldModel . setDisplayName ( item . getAttribute ( ATTR_DISPLAYNAME ) ) ; fieldModel . setType ( item . getAttribute ( ATTR_TYPE ) ) ; NodeList attrList = item . getElementsByTagName ( ATTR_ATTR ) ; for ( int j = 0 ; j < attrList . getLength ( ) ; j ++ ) { Node attr = attrList . item ( j ) ; fieldModel . addAttr ( ( ( Element ) attr ) . getAttribute ( ATTR_NAME ) , ( ( Element ) attr ) . getAttribute ( ATTR_VALUE ) ) ; } fields . add ( fieldModel ) ; } task . setFields ( fields ) ;


signature:
public class DateHelper { /** * 解析日期时间对象
 * @ param date
 * @ return */
public static String parseTime ( Object date ) { } }

implementation: if ( date == null ) return null ; if ( date instanceof Date ) { return new DateTime ( ( Date ) date ) . toString ( DATE_FORMAT_DEFAULT ) ; } else if ( date instanceof String ) { return String . valueOf ( date ) ; } return "" ;


signature:
public class DateHelper { /** * 对时限数据进行处理
 * 1 、 运行时设置的date型数据直接返回
 * 2 、 模型设置的需要特殊转换成date类型
 * 3 、 运行时设置的转换为date型
 * @ param args 运行时参数
 * @ param parameter 模型参数
 * @ return Date类型 */
public static Date processTime ( Map < String , Object > args , String parameter ) { } }

implementation:
if ( StringHelper . isEmpty ( parameter ) ) return null ; Object data = args . get ( parameter ) ; if ( data == null ) data = parameter ; Date result = null ; if ( data instanceof Date ) { return ( Date ) data ; } else if ( data instanceof Long ) { return new Date ( ( Long ) data ) ; } else if ( data instanceof String ) { // TODO 1.4 - dev ignore
} return result ;


signature:
public class JfinalAccess { /** * 从jfinal的threadlocal中获取数据库连接 */
protected Connection getConnection ( ) throws SQLException { } }

implementation: Config config = JfinalHelper . getConfig ( ) ; Connection conn = config . getThreadLocalConnection ( ) ; if ( conn == null ) { conn = config . getConnection ( ) ; conn . setAutoCommit ( true ) ; } return conn ;


signature:
public class TaskService { /** * 完成指定任务 */
public Task complete ( String taskId , String operator ) { } }

implementation: return complete ( taskId , operator , null ) ;


signature:
public class TaskService { /** * 完成指定任务
 * 该方法仅仅结束活动任务 , 并不能驱动流程继续执行
 * @ see SnakerEngineImpl # executeTask ( String , String , java . util . Map ) */
public Task complete ( String taskId , String operator , Map < String , Object > args ) { } }

implementation: Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , "指定的任务[id=" + taskId + "]不存在" ) ; task . setVariable ( JsonHelper . toJson ( args ) ) ; if ( ! isAllowed ( task , operator ) ) { throw new SnakerException ( "当前参与者[" + operator + "]不允许执行任务[taskId=" + taskId + "]" ) ; } HistoryTask history = new HistoryTask ( task ) ; history . setFinishTime ( DateHelper . getTime ( ) ) ; history . setTaskState ( STATE_FINISH ) ; history . setOperator ( operator ) ; if ( history . getActorIds ( ) == null ) { List < TaskActor > actors = access ( ) . getTaskActorsByTaskId ( task . getId ( ) ) ; String [ ] actorIds = new String [ actors . size ( ) ] ; for ( int i = 0 ; i < actors . size ( ) ; i ++ ) { actorIds [ i ] = actors . get ( i ) . getActorId ( ) ; } history . setActorIds ( actorIds ) ; } access ( ) . saveHistory ( history ) ; access ( ) . deleteTask ( task ) ; Completion completion = getCompletion ( ) ; if ( completion != null ) { completion . complete ( history ) ; } return task ;


signature:
public class TaskService { /** * 任务历史记录方法
 * @ param execution 执行对象
 * @ param model 自定义节点模型
 * @ return 历史任务对象 */
public HistoryTask history ( Execution execution , CustomModel model ) { } }

implementation: HistoryTask historyTask = new HistoryTask ( ) ; historyTask . setId ( StringHelper . getPrimaryKey ( ) ) ; historyTask . setOrderId ( execution . getOrder ( ) . getId ( ) ) ; String currentTime = DateHelper . getTime ( ) ; historyTask . setCreateTime ( currentTime ) ; historyTask . setFinishTime ( currentTime ) ; historyTask . setDisplayName ( model . getDisplayName ( ) ) ; historyTask . setTaskName ( model . getName ( ) ) ; historyTask . setTaskState ( STATE_FINISH ) ; historyTask . setTaskType ( TaskType . Record . ordinal ( ) ) ; historyTask . setParentTaskId ( execution . getTask ( ) == null ? START : execution . getTask ( ) . getId ( ) ) ; historyTask . setVariable ( JsonHelper . toJson ( execution . getArgs ( ) ) ) ; access ( ) . saveHistory ( historyTask ) ; return historyTask ;


signature:
public class TaskService { /** * 提取指定任务 , 设置完成时间及操作人 , 状态不改变 */
public Task take ( String taskId , String operator ) { } }

implementation: Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , "指定的任务[id=" + taskId + "]不存在" ) ; if ( ! isAllowed ( task , operator ) ) { throw new SnakerException ( "当前参与者[" + operator + "]不允许提取任务[taskId=" + taskId + "]" ) ; } task . setOperator ( operator ) ; task . setFinishTime ( DateHelper . getTime ( ) ) ; access ( ) . updateTask ( task ) ; return task ;


signature:
public class TaskService { /** * 唤醒指定的历史任务 */
public Task resume ( String taskId , String operator ) { } }

implementation: HistoryTask histTask = access ( ) . getHistTask ( taskId ) ; AssertHelper . notNull ( histTask , "指定的历史任务[id=" + taskId + "]不存在" ) ; boolean isAllowed = true ; if ( StringHelper . isNotEmpty ( histTask . getOperator ( ) ) ) { isAllowed = histTask . getOperator ( ) . equals ( operator ) ; } if ( isAllowed ) { Task task = histTask . undoTask ( ) ; task . setId ( StringHelper . getPrimaryKey ( ) ) ; task . setCreateTime ( DateHelper . getTime ( ) ) ; access ( ) . saveTask ( task ) ; assignTask ( task . getId ( ) , task . getOperator ( ) ) ; return task ; } else { throw new SnakerException ( "当前参与者[" + operator + "]不允许唤醒历史任务[taskId=" + taskId + "]" ) ; }


signature:
public class TaskService { /** * 向指定任务添加参与者
 * 该方法根据performType类型判断是否需要创建新的活动任务 */
public void addTaskActor ( String taskId , Integer performType , String ... actors ) { } }

implementation: Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , "指定的任务[id=" + taskId + "]不存在" ) ; if ( ! task . isMajor ( ) ) return ; if ( performType == null ) performType = task . getPerformType ( ) ; if ( performType == null ) performType = 0 ; switch ( performType ) { case 0 : assignTask ( task . getId ( ) , actors ) ; Map < String , Object > data = task . getVariableMap ( ) ; String oldActor = ( String ) data . get ( Task . KEY_ACTOR ) ; data . put ( Task . KEY_ACTOR , oldActor + "," + StringHelper . getStringByArray ( actors ) ) ; task . setVariable ( JsonHelper . toJson ( data ) ) ; access ( ) . updateTask ( task ) ; break ; case 1 : try { for ( String actor : actors ) { Task newTask = ( Task ) task . clone ( ) ; newTask . setId ( StringHelper . getPrimaryKey ( ) ) ; newTask . setCreateTime ( DateHelper . getTime ( ) ) ; newTask . setOperator ( actor ) ; Map < String , Object > taskData = task . getVariableMap ( ) ; taskData . put ( Task . KEY_ACTOR , actor ) ; task . setVariable ( JsonHelper . toJson ( taskData ) ) ; access ( ) . saveTask ( newTask ) ; assignTask ( newTask . getId ( ) , actor ) ; } } catch ( CloneNotSupportedException ex ) { throw new SnakerException ( "任务对象不支持复制" , ex . getCause ( ) ) ; } break ; default : break ; }


signature:
public class TaskService { /** * 向指定任务移除参与者 */
public void removeTaskActor ( String taskId , String ... actors ) { } }

implementation: Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , "指定的任务[id=" + taskId + "]不存在" ) ; if ( actors == null || actors . length == 0 ) return ; if ( task . isMajor ( ) ) { access ( ) . removeTaskActor ( task . getId ( ) , actors ) ; Map < String , Object > taskData = task . getVariableMap ( ) ; String actorStr = ( String ) taskData . get ( Task . KEY_ACTOR ) ; if ( StringHelper . isNotEmpty ( actorStr ) ) { String [ ] actorArray = actorStr . split ( "," ) ; StringBuilder newActor = new StringBuilder ( actorStr . length ( ) ) ; boolean isMatch ; for ( String actor : actorArray ) { isMatch = false ; if ( StringHelper . isEmpty ( actor ) ) continue ; for ( String removeActor : actors ) { if ( actor . equals ( removeActor ) ) { isMatch = true ; break ; } } if ( isMatch ) continue ; newActor . append ( actor ) . append ( "," ) ; } newActor . deleteCharAt ( newActor . length ( ) - 1 ) ; taskData . put ( Task . KEY_ACTOR , newActor . toString ( ) ) ; task . setVariable ( JsonHelper . toJson ( taskData ) ) ; access ( ) . updateTask ( task ) ; } }


signature:
public class TaskService { /** * 撤回指定的任务 */
public Task withdrawTask ( String taskId , String operator ) { } }

implementation: HistoryTask hist = access ( ) . getHistTask ( taskId ) ; AssertHelper . notNull ( hist , "指定的历史任务[id=" + taskId + "]不存在" ) ; List < Task > tasks ; if ( hist . isPerformAny ( ) ) { tasks = access ( ) . getNextActiveTasks ( hist . getId ( ) ) ; } else { tasks = access ( ) . getNextActiveTasks ( hist . getOrderId ( ) , hist . getTaskName ( ) , hist . getParentTaskId ( ) ) ; } if ( tasks == null || tasks . isEmpty ( ) ) { throw new SnakerException ( "后续活动任务已完成或不存在，无法撤回." ) ; } for ( Task task : tasks ) { access ( ) . deleteTask ( task ) ; } Task task = hist . undoTask ( ) ; task . setId ( StringHelper . getPrimaryKey ( ) ) ; task . setCreateTime ( DateHelper . getTime ( ) ) ; access ( ) . saveTask ( task ) ; assignTask ( task . getId ( ) , task . getOperator ( ) ) ; return task ;


signature:
public class TaskService { /** * 驳回任务 */
public Task rejectTask ( ProcessModel model , Task currentTask ) { } }

implementation: String parentTaskId = currentTask . getParentTaskId ( ) ; if ( StringHelper . isEmpty ( parentTaskId ) || parentTaskId . equals ( START ) ) { throw new SnakerException ( "上一步任务ID为空，无法驳回至上一步处理" ) ; } NodeModel current = model . getNode ( currentTask . getTaskName ( ) ) ; HistoryTask history = access ( ) . getHistTask ( parentTaskId ) ; NodeModel parent = model . getNode ( history . getTaskName ( ) ) ; if ( ! NodeModel . canRejected ( current , parent ) ) { throw new SnakerException ( "无法驳回至上一步处理，请确认上一步骤并非fork、join、suprocess以及会签任务" ) ; } Task task = history . undoTask ( ) ; task . setId ( StringHelper . getPrimaryKey ( ) ) ; task . setCreateTime ( DateHelper . getTime ( ) ) ; task . setOperator ( history . getOperator ( ) ) ; access ( ) . saveTask ( task ) ; assignTask ( task . getId ( ) , task . getOperator ( ) ) ; return task ;


signature:
public class TaskService { /** * 对指定的任务分配参与者 。 参与者可以为用户 、 部门 、 角色
 * @ param taskId 任务id
 * @ param actorIds 参与者id集合 */
private void assignTask ( String taskId , String ... actorIds ) { } }

implementation:
if ( actorIds == null || actorIds . length == 0 ) return ; for ( String actorId : actorIds ) { // 修复当actorId为null的bug
if ( StringHelper . isEmpty ( actorId ) ) continue ; TaskActor taskActor = new TaskActor ( ) ; taskActor . setTaskId ( taskId ) ; taskActor . setActorId ( actorId ) ; access ( ) . saveTaskActor ( taskActor ) ; }


signature:
public class TaskService { /** * 根据已有任务 、 任务类型 、 参与者创建新的任务
 * 适用于转派 , 动态协办处理 */
public List < Task > createNewTask ( String taskId , int taskType , String ... actors ) { } }

implementation: Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , "指定的任务[id=" + taskId + "]不存在" ) ; List < Task > tasks = new ArrayList < Task > ( ) ; try { Task newTask = ( Task ) task . clone ( ) ; newTask . setTaskType ( taskType ) ; newTask . setCreateTime ( DateHelper . getTime ( ) ) ; newTask . setParentTaskId ( taskId ) ; tasks . add ( saveTask ( newTask , actors ) ) ; } catch ( CloneNotSupportedException e ) { throw new SnakerException ( "任务对象不支持复制" , e . getCause ( ) ) ; } return tasks ;


signature:
public class TaskService { /** * 获取任务模型
 * @ param taskId 任务id
 * @ return TaskModel */
public TaskModel getTaskModel ( String taskId ) { } }

implementation: Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task ) ; Order order = access ( ) . getOrder ( task . getOrderId ( ) ) ; AssertHelper . notNull ( order ) ; Process process = ServiceContext . getEngine ( ) . process ( ) . getProcessById ( order . getProcessId ( ) ) ; ProcessModel model = process . getModel ( ) ; NodeModel nodeModel = model . getNode ( task . getTaskName ( ) ) ; AssertHelper . notNull ( nodeModel , "任务id无法找到节点模型." ) ; if ( nodeModel instanceof TaskModel ) { return ( TaskModel ) nodeModel ; } else { throw new IllegalArgumentException ( "任务id找到的节点模型不匹配" ) ; }


signature:
public class TaskService { /** * 由DBAccess实现类创建task , 并根据model类型决定是否分配参与者
 * @ param taskModel 模型
 * @ param execution 执行对象
 * @ return List < Task > 任务列表 */
public List < Task > createTask ( TaskModel taskModel , Execution execution ) { } }

implementation:
List < Task > tasks = new ArrayList < Task > ( ) ; Map < String , Object > args = execution . getArgs ( ) ; if ( args == null ) args = new HashMap < String , Object > ( ) ; Date expireDate = DateHelper . processTime ( args , taskModel . getExpireTime ( ) ) ; Date remindDate = DateHelper . processTime ( args , taskModel . getReminderTime ( ) ) ; String form = ( String ) args . get ( taskModel . getForm ( ) ) ; String actionUrl = StringHelper . isEmpty ( form ) ? taskModel . getForm ( ) : form ; String [ ] actors = getTaskActors ( taskModel , execution ) ; args . put ( Task . KEY_ACTOR , StringHelper . getStringByArray ( actors ) ) ; Task task = createTaskBase ( taskModel , execution ) ; task . setActionUrl ( actionUrl ) ; task . setExpireDate ( expireDate ) ; task . setExpireTime ( DateHelper . parseTime ( expireDate ) ) ; task . setVariable ( JsonHelper . toJson ( args ) ) ; if ( taskModel . isPerformAny ( ) ) { // 任务执行方式为参与者中任何一个执行即可驱动流程继续流转 , 该方法只产生一个task
task = saveTask ( task , actors ) ; task . setRemindDate ( remindDate ) ; tasks . add ( task ) ; } else if ( taskModel . isPerformAll ( ) ) { // 任务执行方式为参与者中每个都要执行完才可驱动流程继续流转 , 该方法根据参与者个数产生对应的task数量
for ( String actor : actors ) { Task singleTask ; try { singleTask = ( Task ) task . clone ( ) ; } catch ( CloneNotSupportedException e ) { singleTask = task ; } singleTask = saveTask ( singleTask , actor ) ; singleTask . setRemindDate ( remindDate ) ; tasks . add ( singleTask ) ; } } return tasks ;


signature:
public class TaskService { /** * 根据模型 、 执行对象 、 任务类型构建基本的task对象
 * @ param model 模型
 * @ param execution 执行对象
 * @ return Task任务对象 */
private Task createTaskBase ( TaskModel model , Execution execution ) { } }

implementation: Task task = new Task ( ) ; task . setOrderId ( execution . getOrder ( ) . getId ( ) ) ; task . setTaskName ( model . getName ( ) ) ; task . setDisplayName ( model . getDisplayName ( ) ) ; task . setCreateTime ( DateHelper . getTime ( ) ) ; if ( model . isMajor ( ) ) { task . setTaskType ( TaskType . Major . ordinal ( ) ) ; } else { task . setTaskType ( TaskType . Aidant . ordinal ( ) ) ; } task . setParentTaskId ( execution . getTask ( ) == null ? START : execution . getTask ( ) . getId ( ) ) ; task . setModel ( model ) ; return task ;


signature:
public class TaskService { /** * 由DBAccess实现类持久化task对象 */
private Task saveTask ( Task task , String ... actors ) { } }

implementation: task . setId ( StringHelper . getPrimaryKey ( ) ) ; task . setPerformType ( PerformType . ANY . ordinal ( ) ) ; access ( ) . saveTask ( task ) ; assignTask ( task . getId ( ) , actors ) ; task . setActorIds ( actors ) ; return task ;


signature:
public class TaskService { /** * 根据Task模型的assignee 、 assignmentHandler属性以及运行时数据 , 确定参与者
 * @ param model 模型
 * @ param execution 执行对象
 * @ return 参与者数组 */
private String [ ] getTaskActors ( TaskModel model , Execution execution ) { } }

implementation: Object assigneeObject = null ; AssignmentHandler handler = model . getAssignmentHandlerObject ( ) ; if ( StringHelper . isNotEmpty ( model . getAssignee ( ) ) ) { assigneeObject = execution . getArgs ( ) . get ( model . getAssignee ( ) ) ; } else if ( handler != null ) { if ( handler instanceof Assignment ) { assigneeObject = ( ( Assignment ) handler ) . assign ( model , execution ) ; } else { assigneeObject = handler . assign ( execution ) ; } } return getTaskActors ( assigneeObject == null ? model . getAssignee ( ) : assigneeObject ) ;