signature:
public class ODatabaseWrapperAbstract { /** * Executes a backup of the database . During the backup the database will be frozen in read - only mode .
 * @ param out OutputStream used to write the backup content . Use a FileOutputStream to make the backup persistent on
 * disk
 * @ param options Backup options as Map < String , Object > object
 * @ param callable Callback to execute when the database is locked
 * @ param iListener Listener called for backup messages
 * @ param compressionLevel ZIP Compression level between 0 ( no compression ) and 9 ( maximum ) . The bigger is the compression , the
 * smaller will be the final backup content , but will consume more CPU and time to execute
 * @ param bufferSize Buffer size in bytes , the bigger is the buffer , the more efficient will be the compression
 * @ throws IOException */
@ Override public List < String > backup ( OutputStream out , Map < String , Object > options , Callable < Object > callable , final OCommandOutputListener iListener , int compressionLevel , int bufferSize ) throws IOException { } }

implementation: return underlying . backup ( out , options , callable , iListener , compressionLevel , bufferSize ) ;


signature:
public class OSystemUser { /** * Derived classes can override createRole ( ) to return an extended ORole implementation . */
protected ORole createRole ( final ODocument roleDoc ) { } }

implementation:
ORole role = null ; // If databaseName is set , then only allow roles with the same databaseName .
if ( databaseName != null && ! databaseName . isEmpty ( ) ) { if ( roleDoc != null && roleDoc . containsField ( OSystemRole . DB_FILTER ) && roleDoc . fieldType ( OSystemRole . DB_FILTER ) == OType . EMBEDDEDLIST ) { List < String > dbNames = roleDoc . field ( OSystemRole . DB_FILTER , OType . EMBEDDEDLIST ) ; for ( String dbName : dbNames ) { if ( dbName != null && ! dbName . isEmpty ( ) && ( dbName . equalsIgnoreCase ( databaseName ) || dbName . equals ( "*" ) ) ) { role = new OSystemRole ( roleDoc ) ; break ; } } } } // If databaseName is not set , only return roles without a OSystemRole . DB _ FILTER property or if set to " * " .
else { if ( roleDoc != null ) { if ( ! roleDoc . containsField ( OSystemRole . DB_FILTER ) ) { role = new OSystemRole ( roleDoc ) ; } else { // It does use the dbFilter property .
if ( roleDoc . fieldType ( OSystemRole . DB_FILTER ) == OType . EMBEDDEDLIST ) { List < String > dbNames = roleDoc . field ( OSystemRole . DB_FILTER , OType . EMBEDDEDLIST ) ; for ( String dbName : dbNames ) { if ( dbName != null && ! dbName . isEmpty ( ) && dbName . equals ( "*" ) ) { role = new OSystemRole ( roleDoc ) ; break ; } } } } } } return role ;


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

implementation:
final ODatabaseDocument database = getDatabase ( ) ; if ( attribute == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final OClassImpl cls = ( OClassImpl ) database . getMetadata ( ) . getSchema ( ) . getClass ( className ) ; if ( cls == null ) throw new OCommandExecutionException ( "Cannot alter class '" + className + "' because not found" ) ; if ( ! unsafe && attribute == ATTRIBUTES . NAME && cls . isSubClassOf ( "E" ) ) throw new OCommandExecutionException ( "Cannot alter class '" + className + "' because is an Edge class and could break vertices. Use UNSAFE if you want to force it" ) ; // REMOVE CACHE OF COMMAND RESULTS
for ( int clId : cls . getPolymorphicClusterIds ( ) ) getDatabase ( ) . getMetadata ( ) . getCommandCache ( ) . invalidateResultsOfCluster ( getDatabase ( ) . getClusterNameById ( clId ) ) ; if ( value != null && attribute == ATTRIBUTES . SUPERCLASS ) { checkClassExists ( database , className , decodeClassName ( value ) ) ; } if ( value != null && attribute == ATTRIBUTES . SUPERCLASSES ) { List < String > classes = Arrays . asList ( value . split ( ",\\s*" ) ) ; for ( String cName : classes ) { checkClassExists ( database , className , decodeClassName ( cName ) ) ; } } if ( ! unsafe && value != null && attribute == ATTRIBUTES . NAME ) { if ( ! cls . getIndexes ( ) . isEmpty ( ) ) { throw new OCommandExecutionException ( "Cannot rename class '" + className + "' because it has indexes defined on it. Drop indexes before or use UNSAFE (at your won risk)" ) ; } } cls . set ( attribute , value ) ; return Boolean . TRUE ;


signature:
public class OCommandExecutorScript { /** * TODO : CREATE A REGULAR JSR223 SCRIPT IMPL */
protected Object executeSQL ( ) { } }

implementation: ODatabaseDocument db = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { return executeSQLScript ( parserText , db ) ; } catch ( IOException e ) { throw OException . wrapException ( new OCommandExecutionException ( "Error on executing command: " + parserText ) , e ) ; }


signature:
public class OCommandExecutorScript { /** * Wait before to retry */
protected void waitForNextRetry ( ) { } }

implementation: try { Thread . sleep ( new Random ( ) . nextInt ( MAX_DELAY - 1 ) + 1 ) ; } catch ( InterruptedException e ) { OLogManager . instance ( ) . error ( this , "Wait was interrupted" , e ) ; }


signature:
public class OHttpRequestWrapper { /** * Returns the argument by position
 * @ return Array of arguments */
public String getArgument ( final int iPosition ) { } }

implementation: return args != null && args . length > iPosition ? args [ iPosition ] : null ;


signature:
public class OHttpRequestWrapper { /** * Checks how many parameters have been received .
 * @ return The number of parameters found between the passed ones */
public int hasParameters ( final String ... iNames ) { } }

implementation: int found = 0 ; if ( iNames != null && request . parameters != null ) for ( String name : iNames ) found += request . parameters . containsKey ( name ) ? 1 : 0 ; return found ;


signature:
public class OServerAdmin { /** * Connects to a remote server .
 * @ param iUserName Server ' s user name
 * @ param iUserPassword Server ' s password for the user name used
 * @ return The instance itself . Useful to execute method in chain
 * @ throws IOException */
@ Deprecated public synchronized OServerAdmin connect ( final String iUserName , final String iUserPassword ) throws IOException { } }

implementation: final String username ; final String password ; OCredentialInterceptor ci = OSecurityManager . instance ( ) . newCredentialInterceptor ( ) ; if ( ci != null ) { ci . intercept ( storage . getURL ( ) , iUserName , iUserPassword ) ; username = ci . getUsername ( ) ; password = ci . getPassword ( ) ; } else { username = iUserName ; password = iUserPassword ; } OConnect37Request request = new OConnect37Request ( username , password ) ; networkAdminOperation ( ( network , session ) -> { OStorageRemoteNodeSession nodeSession = session . getOrCreateServerSession ( network . getServerURL ( ) ) ; try { network . beginRequest ( request . getCommand ( ) , session ) ; request . write ( network , session ) ; } finally { network . endRequest ( ) ; } OConnectResponse response = request . createResponse ( ) ; try { network . beginResponse ( nodeSession . getSessionId ( ) , true ) ; response . read ( network , session ) ; } finally { storage . endResponse ( network ) ; } return null ; } , "Cannot connect to the remote server/database '" + storage . getURL ( ) + "'" ) ; return this ;


signature:
public class OServerAdmin { /** * Returns the list of databases on the connected remote server .
 * @ throws IOException */
@ Deprecated public synchronized Map < String , String > listDatabases ( ) throws IOException { } }

implementation: OListDatabasesRequest request = new OListDatabasesRequest ( ) ; OListDatabasesResponse response = networkAdminOperation ( request , "Cannot retrieve the configuration list" ) ; return response . getDatabases ( ) ;


signature:
public class OServerAdmin { /** * Returns the server information in form of document .
 * @ throws IOException */
@ Deprecated public synchronized ODocument getServerInfo ( ) throws IOException { } }

implementation: OServerInfoRequest request = new OServerInfoRequest ( ) ; OServerInfoResponse response = networkAdminOperation ( request , "Cannot retrieve server information" ) ; ODocument res = new ODocument ( ) ; res . fromJSON ( response . getResult ( ) ) ; return res ;


signature:
public class OServerAdmin { /** * Creates a database in a remote server .
 * @ param iDatabaseType ' document ' or ' graph '
 * @ param iStorageMode local or memory
 * @ return The instance itself . Useful to execute method in chain
 * @ throws IOException */
@ Deprecated public synchronized OServerAdmin createDatabase ( final String iDatabaseType , String iStorageMode ) throws IOException { } }

implementation: return createDatabase ( storage . getName ( ) , iDatabaseType , iStorageMode ) ;


signature:
public class OServerAdmin { /** * Creates a database in a remote server .
 * @ param iDatabaseName The database name
 * @ param iDatabaseType ' document ' or ' graph '
 * @ param iStorageMode local or memory
 * @ param backupPath path to incremental backup which will be used to create database ( optional )
 * @ return The instance itself . Useful to execute method in chain
 * @ throws IOException */
public synchronized OServerAdmin createDatabase ( final String iDatabaseName , final String iDatabaseType , final String iStorageMode , final String backupPath ) throws IOException { } }

implementation: if ( iDatabaseName == null || iDatabaseName . length ( ) <= 0 ) { final String message = "Cannot create unnamed remote storage. Check your syntax" ; OLogManager . instance ( ) . error ( this , message , null ) ; throw new OStorageException ( message ) ; } else { String storageMode ; if ( iStorageMode == null ) storageMode = "plocal" ; else storageMode = iStorageMode ; OCreateDatabaseRequest request = new OCreateDatabaseRequest ( iDatabaseName , iDatabaseName , storageMode , backupPath ) ; OCreateDatabaseResponse response = networkAdminOperation ( request , "Cannot create the remote storage: " + storage . getName ( ) ) ; } return this ;


signature:
public class OServerAdmin { /** * Checks if a database exists in the remote server .
 * @ param iDatabaseName The database name
 * @ param storageType Storage type between " plocal " or " memory " .
 * @ return true if exists , otherwise false
 * @ throws IOException */
public synchronized boolean existsDatabase ( final String iDatabaseName , final String storageType ) throws IOException { } }

implementation: OExistsDatabaseRequest request = new OExistsDatabaseRequest ( iDatabaseName , storageType ) ; OExistsDatabaseResponse response = networkAdminOperation ( request , "Error on checking existence of the remote storage: " + storage . getName ( ) ) ; return response . isExists ( ) ;


signature:
public class OServerAdmin { /** * Drops a database from a remote server instance .
 * @ param iDatabaseName The database name
 * @ param storageType Storage type between " plocal " or " memory " .
 * @ return The instance itself . Useful to execute method in chain
 * @ throws IOException */
public synchronized OServerAdmin dropDatabase ( final String iDatabaseName , final String storageType ) throws IOException { } }

implementation: ODropDatabaseRequest request = new ODropDatabaseRequest ( iDatabaseName , storageType ) ; ODropDatabaseResponse response = networkAdminOperation ( request , "Cannot delete the remote storage: " + storage . getName ( ) ) ; OURLConnection connection = OURLHelper . parse ( getURL ( ) ) ; OrientDBRemote remote = ( OrientDBRemote ) ODatabaseDocumentTxInternal . getOrCreateRemoteFactory ( connection . getPath ( ) ) ; remote . forceDatabaseClose ( iDatabaseName ) ; ODatabaseRecordThreadLocal . instance ( ) . remove ( ) ; return this ;


signature:
public class OServerAdmin { /** * Freezes the database by locking it in exclusive mode .
 * @ param storageType Storage type between " plocal " or " memory " .
 * @ return
 * @ throws IOException
 * @ see # releaseDatabase ( String ) */
public synchronized OServerAdmin freezeDatabase ( final String storageType ) throws IOException { } }

implementation: OFreezeDatabaseRequest request = new OFreezeDatabaseRequest ( storage . getName ( ) , storageType ) ; OFreezeDatabaseResponse response = networkAdminOperation ( request , "Cannot freeze the remote storage: " + storage . getName ( ) ) ; return this ;


signature:
public class OServerAdmin { /** * Releases a frozen database .
 * @ param storageType Storage type between " plocal " or " memory " .
 * @ return
 * @ throws IOException
 * @ see # freezeDatabase ( String ) */
public synchronized OServerAdmin releaseDatabase ( final String storageType ) throws IOException { } }

implementation: OReleaseDatabaseRequest request = new OReleaseDatabaseRequest ( storage . getName ( ) , storageType ) ; OReleaseDatabaseResponse response = networkAdminOperation ( request , "Cannot release the remote storage: " + storage . getName ( ) ) ; return this ;


signature:
public class OServerAdmin { /** * Gets the cluster status .
 * @ return the JSON containing the current cluster structure */
public ODocument clusterStatus ( ) { } }

implementation: ODistributedStatusRequest request = new ODistributedStatusRequest ( ) ; ODistributedStatusResponse response = storage . networkOperation ( request , "Error on executing Cluster status " ) ; OLogManager . instance ( ) . debug ( this , "Cluster status %s" , response . getClusterConfig ( ) . toJSON ( "prettyPrint" ) ) ; return response . getClusterConfig ( ) ;


signature:
public class OCommandExecutorSQLCreateIndex { /** * Execute the CREATE INDEX . */
@ SuppressWarnings ( "rawtypes" ) public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation: if ( indexName == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseDocument database = getDatabase ( ) ; final OIndex < ? > idx ; List < OCollate > collatesList = null ; if ( collates != null ) { collatesList = new ArrayList < OCollate > ( ) ; for ( String collate : collates ) { if ( collate != null ) { final OCollate col = OSQLEngine . getCollate ( collate ) ; collatesList . add ( col ) ; } else collatesList . add ( null ) ; } } if ( fields == null || fields . length == 0 ) { OIndexFactory factory = OIndexes . getFactory ( indexType . toString ( ) , null ) ; if ( keyTypes != null ) idx = database . getMetadata ( ) . getIndexManager ( ) . createIndex ( indexName , indexType . toString ( ) , new OSimpleKeyIndexDefinition ( keyTypes , collatesList ) , null , null , metadataDoc , engine ) ; else if ( serializerKeyId != 0 ) { idx = database . getMetadata ( ) . getIndexManager ( ) . createIndex ( indexName , indexType . toString ( ) , new ORuntimeKeyIndexDefinition ( serializerKeyId ) , null , null , metadataDoc , engine ) ; } else { throw new ODatabaseException ( "Impossible to create an index without specify the key type or the associated property" ) ; } } else { if ( ( keyTypes == null || keyTypes . length == 0 ) && collates == null ) { idx = oClass . createIndex ( indexName , indexType . toString ( ) , null , metadataDoc , engine , fields ) ; } else { final List < OType > fieldTypeList ; if ( keyTypes == null ) { for ( final String fieldName : fields ) { if ( ! fieldName . equals ( "@rid" ) && ! oClass . existsProperty ( fieldName ) ) throw new OIndexException ( "Index with name : '" + indexName + "' cannot be created on class : '" + oClass . getName ( ) + "' because field: '" + fieldName + "' is absent in class definition." ) ; } fieldTypeList = ( ( OClassImpl ) oClass ) . extractFieldTypes ( fields ) ; } else fieldTypeList = Arrays . asList ( keyTypes ) ; final OIndexDefinition idxDef = OIndexDefinitionFactory . createIndexDefinition ( oClass , Arrays . asList ( fields ) , fieldTypeList , collatesList , indexType . toString ( ) , null ) ; idx = database . getMetadata ( ) . getIndexManager ( ) . createIndex ( indexName , indexType . name ( ) , idxDef , oClass . getPolymorphicClusterIds ( ) , null , metadataDoc , engine ) ; } } if ( idx != null ) return idx . getSize ( ) ; return null ;


signature:
public class OGraphCommandExecutorSQLFactory { /** * Returns a Transactional OrientGraph implementation from the current database in thread local .
 * @ param autoStartTx Whether returned graph will start transaction before each operation till commit automatically or user should do it
 * explicitly be calling { @ link OrientGraph # getRawGraph ( ) } method { @ link ODatabaseDocumentTx # begin ( ) } .
 * @ return Transactional OrientGraph implementation from the current database in thread local . */
public static OrientGraph getGraph ( final boolean autoStartTx , OModifiableBoolean shouldBeShutDown ) { } }

implementation:
final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; final OrientBaseGraph result = OrientBaseGraph . getActiveGraph ( ) ; if ( result != null && ( result instanceof OrientGraph ) ) { final ODatabaseDocumentInternal graphDb = result . getRawGraph ( ) ; // CHECK IF THE DATABASE + USER IN TL IS THE SAME IN ORDER TO USE IT
if ( canReuseActiveGraph ( graphDb , database ) ) { if ( ! graphDb . isClosed ( ) ) { ODatabaseRecordThreadLocal . instance ( ) . set ( graphDb ) ; if ( autoStartTx && autoTxStartRequired ( graphDb ) ) ( ( OrientGraph ) result ) . begin ( ) ; shouldBeShutDown . setValue ( false ) ; return ( OrientGraph ) result ; } } } // Set it again on ThreadLocal because the getRawGraph ( ) may have set a closed db in the thread - local
ODatabaseRecordThreadLocal . instance ( ) . set ( database ) ; shouldBeShutDown . setValue ( true ) ; final OrientGraph g = ( OrientGraph ) OrientGraphFactory . getTxGraphImplFactory ( ) . getGraph ( database , false ) ; if ( autoStartTx && autoTxStartRequired ( database ) ) g . begin ( ) ; return g ;


signature:
public class OCommandExecutorSQLRetryAbstract { /** * Parses the RETRY number of times */
protected void parseRetry ( ) throws OCommandSQLParsingException { } }

implementation: retry = Integer . parseInt ( parserNextWord ( true ) ) ; String temp = parseOptionalWord ( true ) ; if ( temp . equals ( "WAIT" ) ) { wait = Integer . parseInt ( parserNextWord ( true ) ) ; } else parserGoBack ( ) ;


signature:
public class OSequence { /** * Resets the sequence value to it ' s initialized value . */
long reset ( boolean executeViaDistributed ) throws ODatabaseException { } }

implementation: long retVal ; if ( executeViaDistributed ) { try { retVal = sendSequenceActionOverCluster ( OSequenceAction . RESET , null ) ; } catch ( InterruptedException | ExecutionException exc ) { OLogManager . instance ( ) . error ( this , exc . getMessage ( ) , exc , ( Object [ ] ) null ) ; throw new ODatabaseException ( exc . getMessage ( ) ) ; } } else { retVal = resetWork ( ) ; } return retVal ;


signature:
public class OTransactionNoTx { /** * Update the record .
 * @ param iRecord
 * @ param iForceCreate
 * @ param iRecordCreatedCallback
 * @ param iRecordUpdatedCallback */
public ORecord saveRecord ( final ORecord iRecord , final String iClusterName , final OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { } }

implementation:
try { return database . saveAll ( iRecord , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; } catch ( Exception e ) { // REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS
final ORecordId rid = ( ORecordId ) iRecord . getIdentity ( ) ; if ( rid . isValid ( ) ) database . getLocalCache ( ) . freeRecord ( rid ) ; if ( e instanceof ONeedRetryException ) throw ( ONeedRetryException ) e ; throw OException . wrapException ( new ODatabaseException ( "Error during saving of record" + ( iRecord != null ? " with rid " + iRecord . getIdentity ( ) : "" ) ) , e ) ; }


signature:
public class OTransactionNoTx { /** * Deletes the record . */
public void deleteRecord ( final ORecord iRecord , final OPERATION_MODE iMode ) { } }

implementation:
if ( ! iRecord . getIdentity ( ) . isPersistent ( ) ) return ; try { database . executeDeleteRecord ( iRecord , iRecord . getVersion ( ) , true , iMode , false ) ; } catch ( Exception e ) { // REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS
final ORecordId rid = ( ORecordId ) iRecord . getIdentity ( ) ; if ( rid . isValid ( ) ) database . getLocalCache ( ) . freeRecord ( rid ) ; if ( e instanceof RuntimeException ) throw ( RuntimeException ) e ; throw OException . wrapException ( new ODatabaseException ( "Error during deletion of record" + ( iRecord != null ? " with rid " + iRecord . getIdentity ( ) : "" ) ) , e ) ; }


signature:
public class OSecurityAuthenticatorAbstract { /** * OSecurityComponent */
public void config ( final OServer oServer , final OServerConfigurationManager serverCfg , final ODocument jsonConfig ) { } }

implementation: server = oServer ; serverConfig = serverCfg ; if ( jsonConfig . containsField ( "name" ) ) { name = jsonConfig . field ( "name" ) ; } if ( jsonConfig . containsField ( "debug" ) ) { debug = jsonConfig . field ( "debug" ) ; } if ( jsonConfig . containsField ( "enabled" ) ) { enabled = jsonConfig . field ( "enabled" ) ; } if ( jsonConfig . containsField ( "caseSensitive" ) ) { caseSensitive = jsonConfig . field ( "caseSensitive" ) ; }


signature:
public class OSecurityAuthenticatorAbstract { /** * databaseName may be null . */
public String getAuthenticationHeader ( String databaseName ) { } }

implementation:
String header ; // Default to Basic .
if ( databaseName != null ) header = "WWW-Authenticate: Basic realm=\"OrientDB db-" + databaseName + "\"" ; else header = "WWW-Authenticate: Basic realm=\"OrientDB Server\"" ; return header ;


signature:
public class OSystemUserAuthenticator { /** * OSecurityComponent */
public void config ( final OServer oServer , final OServerConfigurationManager serverCfg , final ODocument jsonConfig ) { } }

implementation: super . config ( oServer , serverCfg , jsonConfig ) ; try { } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , "config()" , ex ) ; }


signature:
public class OSystemUserAuthenticator { /** * This will authenticate username using the system database . */
public String authenticate ( final String username , final String password ) { } }

implementation:
String principal = null ; try { if ( getServer ( ) != null ) { // dbName parameter is null because we don ' t need to filter any roles for this .
OUser user = getServer ( ) . getSecurity ( ) . getSystemUser ( username , null ) ; if ( user != null && user . getAccountStatus ( ) == OSecurityUser . STATUSES . ACTIVE ) { if ( user . checkPassword ( password ) ) principal = username ; } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , "authenticate()" , ex ) ; } return principal ;


signature:
public class OSystemUserAuthenticator { /** * Checks to see if a */
public boolean isAuthorized ( final String username , final String resource ) { } }

implementation: if ( username == null || resource == null ) return false ; try { if ( getServer ( ) != null ) { OUser user = getServer ( ) . getSecurity ( ) . getSystemUser ( username , null ) ; if ( user != null && user . getAccountStatus ( ) == OSecurityUser . STATUSES . ACTIVE ) { ORole role = null ; ORule . ResourceGeneric rg = ORule . mapLegacyResourceToGenericResource ( resource ) ; if ( rg != null ) { String specificResource = ORule . mapLegacyResourceToSpecificResource ( resource ) ; if ( specificResource == null || specificResource . equals ( "*" ) ) { specificResource = null ; } role = user . checkIfAllowed ( rg , specificResource , ORole . PERMISSION_EXECUTE ) ; } return role != null ; } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , "isAuthorized()" , ex ) ; } return false ;


signature:
public class OSystemUserAuthenticator { /** * OSecurityAuthenticator */
public OServerUserConfiguration getUser ( final String username ) { } }

implementation: OServerUserConfiguration userCfg = null ; try { if ( getServer ( ) != null ) { OUser user = getServer ( ) . getSecurity ( ) . getSystemUser ( username , null ) ; if ( user != null && user . getAccountStatus ( ) == OSecurityUser . STATUSES . ACTIVE ) { userCfg = new OServerUserConfiguration ( user . getName ( ) , "" , "" ) ; } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , "getUser()" , ex ) ; } return userCfg ;


signature:
public class OServerShutdownHook { /** * Catch the JVM exit and assure to shutdown the Orient Server . */
@ Override public void run ( ) { } }

implementation:
if ( server != null ) if ( ! server . shutdown ( ) ) { // ALREADY IN SHUTDOWN , WAIT FOR 5 SEC MORE
try { Thread . sleep ( 5000 ) ; } catch ( InterruptedException e ) { } }


signature:
public class JavaCharStream { /** * Reinitialise . */
public void ReInit ( java . io . Reader dstream , int startline , int startcolumn , int buffersize ) { } }

implementation: inputStream = dstream ; line = startline ; column = startcolumn - 1 ; if ( buffer == null || buffersize != buffer . length ) { available = bufsize = buffersize ; buffer = new char [ buffersize ] ; bufline = new int [ buffersize ] ; bufcolumn = new int [ buffersize ] ; nextCharBuf = new char [ 4096 ] ; } prevCharIsLF = prevCharIsCR = false ; tokenBegin = inBuf = maxNextCharInd = 0 ; nextCharInd = bufpos = - 1 ;


signature:
public class JavaCharStream { /** * Reinitialise . */
public void ReInit ( java . io . Reader dstream , int startline , int startcolumn ) { } }

implementation: ReInit ( dstream , startline , startcolumn , 4096 ) ;


signature:
public class JavaCharStream { /** * Reinitialise . */
public void ReInit ( java . io . InputStream dstream , String encoding , int startline , int startcolumn , int buffersize ) throws java . io . UnsupportedEncodingException { } }

implementation: ReInit ( encoding == null ? new java . io . InputStreamReader ( dstream ) : new java . io . InputStreamReader ( dstream , encoding ) , startline , startcolumn , buffersize ) ;


signature:
public class JavaCharStream { /** * Reinitialise . */
public void ReInit ( java . io . InputStream dstream , int startline , int startcolumn , int buffersize ) { } }

implementation: ReInit ( new java . io . InputStreamReader ( dstream ) , startline , startcolumn , buffersize ) ;


signature:
public class JavaCharStream { /** * Reinitialise . */
public void ReInit ( java . io . InputStream dstream , String encoding , int startline , int startcolumn ) throws java . io . UnsupportedEncodingException { } }

implementation: ReInit ( dstream , encoding , startline , startcolumn , 4096 ) ;


signature:
public class JavaCharStream { /** * Reinitialise . */
public void ReInit ( java . io . InputStream dstream , int startline , int startcolumn ) { } }


signature:
public class JavaCharStream { /** * Method to adjust line and column numbers for the start of a token . */
public void adjustBeginLineColumn ( int newLine , int newCol ) { } }

implementation: int start = tokenBegin ; int len ; if ( bufpos >= tokenBegin ) { len = bufpos - tokenBegin + inBuf + 1 ; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf ; } int i = 0 , j = 0 , k = 0 ; int nextColDiff = 0 , columnDiff = 0 ; while ( i < len && bufline [ j = start % bufsize ] == bufline [ k = ++ start % bufsize ] ) { bufline [ j ] = newLine ; nextColDiff = columnDiff + bufcolumn [ k ] - bufcolumn [ j ] ; bufcolumn [ j ] = newCol + columnDiff ; columnDiff = nextColDiff ; i ++ ; } if ( i < len ) { bufline [ j ] = newLine ++ ; bufcolumn [ j ] = newCol + columnDiff ; while ( i ++ < len ) { if ( bufline [ j = start % bufsize ] != bufline [ ++ start % bufsize ] ) bufline [ j ] = newLine ++ ; else bufline [ j ] = newLine ; } } line = bufline [ j ] ; column = bufcolumn [ j ] ;


signature:
public class OCompositeKeySerializer { /** * { @ inheritDoc } */
@ Override public void serializeInByteBufferObject ( OCompositeKey object , ByteBuffer buffer , Object ... hints ) { } }

implementation: final OType [ ] types = getKeyTypes ( hints ) ; final List < Object > keys = object . getKeys ( ) ; final int keysSize = keys . size ( ) ; final int oldStartOffset = buffer . position ( ) ; buffer . position ( oldStartOffset + OIntegerSerializer . INT_SIZE ) ; buffer . putInt ( keysSize ) ; final OBinarySerializerFactory factory = OBinarySerializerFactory . getInstance ( ) ; for ( int i = 0 ; i < keys . size ( ) ; i ++ ) { final Object key = keys . get ( i ) ; OBinarySerializer < Object > binarySerializer ; if ( key != null ) { final OType type ; if ( types . length > i ) type = types [ i ] ; else type = OType . getTypeByClass ( key . getClass ( ) ) ; binarySerializer = factory . getObjectSerializer ( type ) ; } else binarySerializer = ONullSerializer . INSTANCE ; buffer . put ( binarySerializer . getId ( ) ) ; binarySerializer . serializeInByteBufferObject ( key , buffer ) ; } final int finalPosition = buffer . position ( ) ; final int serializedSize = buffer . position ( ) - oldStartOffset ; buffer . position ( oldStartOffset ) ; buffer . putInt ( serializedSize ) ; buffer . position ( finalPosition ) ;


signature:
public class OCompositeKeySerializer { /** * { @ inheritDoc } */
@ Override public OCompositeKey deserializeFromByteBufferObject ( ByteBuffer buffer ) { } }

implementation: final OCompositeKey compositeKey = new OCompositeKey ( ) ; buffer . position ( buffer . position ( ) + OIntegerSerializer . INT_SIZE ) ; final int keysSize = buffer . getInt ( ) ; final OBinarySerializerFactory factory = OBinarySerializerFactory . getInstance ( ) ; for ( int i = 0 ; i < keysSize ; i ++ ) { final byte serializerId = buffer . get ( ) ; @ SuppressWarnings ( "unchecked" ) OBinarySerializer < Object > binarySerializer = ( OBinarySerializer < Object > ) factory . getObjectSerializer ( serializerId ) ; final Object key = binarySerializer . deserializeFromByteBufferObject ( buffer ) ; compositeKey . addKey ( key ) ; } return compositeKey ;


signature:
public class OCompositeKeySerializer { /** * { @ inheritDoc } */
@ Override public OCompositeKey deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { } }

implementation: final OCompositeKey compositeKey = new OCompositeKey ( ) ; offset += OIntegerSerializer . INT_SIZE ; final int keysSize = walChanges . getIntValue ( buffer , offset ) ; offset += OIntegerSerializer . INT_SIZE ; final OBinarySerializerFactory factory = OBinarySerializerFactory . getInstance ( ) ; for ( int i = 0 ; i < keysSize ; i ++ ) { final byte serializerId = walChanges . getByteValue ( buffer , offset ) ; offset += OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE ; @ SuppressWarnings ( "unchecked" ) OBinarySerializer < Object > binarySerializer = ( OBinarySerializer < Object > ) factory . getObjectSerializer ( serializerId ) ; final Object key = binarySerializer . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ; compositeKey . addKey ( key ) ; offset += binarySerializer . getObjectSize ( key ) ; } return compositeKey ;


signature:
public class OBonsaiBucketAbstract { /** * Write a bucket pointer to specific location .
 * @ param pageOffset
 * where to write
 * @ param value
 * - pointer to write
 * @ throws IOException */
protected void setBucketPointer ( int pageOffset , OBonsaiBucketPointer value ) throws IOException { } }

implementation: setLongValue ( pageOffset , value . getPageIndex ( ) ) ; setIntValue ( pageOffset + OLongSerializer . LONG_SIZE , value . getPageOffset ( ) ) ;


signature:
public class OBonsaiBucketAbstract { /** * Read bucket pointer from page .
 * @ param offset
 * where the pointer should be read from
 * @ return bucket pointer */
protected OBonsaiBucketPointer getBucketPointer ( int offset ) { } }

implementation: final long pageIndex = getLongValue ( offset ) ; final int pageOffset = getIntValue ( offset + OLongSerializer . LONG_SIZE ) ; return new OBonsaiBucketPointer ( pageIndex , pageOffset ) ;


signature:
public class OClassEmbedded { /** * { @ inheritDoc } */
@ Override public OClass truncateCluster ( String clusterName ) { } }

implementation: getDatabase ( ) . checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_DELETE , name ) ; acquireSchemaReadLock ( ) ; try { final ODatabaseDocumentInternal database = getDatabase ( ) ; truncateClusterInternal ( clusterName , database ) ; } finally { releaseSchemaReadLock ( ) ; } return this ;


signature:
public class OAtomicOperationsManager { /** * Starts atomic operation inside of current thread . If atomic operation has been already started , current atomic operation
 * instance will be returned . All durable components have to call this method at the beginning of any data modification
 * operation .
 * < p > In current implementation of atomic operation , each component which is participated in atomic operation is hold under
 * exclusive lock till atomic operation will not be completed ( committed or rolled back ) .
 * < p > If other thread is going to read data from component it has to acquire read lock inside of atomic operation manager { @ link
 * # acquireReadLock ( ODurableComponent ) } , otherwise data consistency will be compromised .
 * < p > Atomic operation may be delayed if start of atomic operations is prohibited by call of { @ link
 * # freezeAtomicOperations ( Class , String ) } method . If mentioned above method is called then execution of current method will be
 * stopped till call of { @ link # releaseAtomicOperations ( long ) } method or exception will be thrown . Concrete behaviour depends on
 * real values of parameters of { @ link # freezeAtomicOperations ( Class , String ) } method .
 * @ param trackNonTxOperations If this flag set to < code > true < / code > then special record { @ link ONonTxOperationPerformedWALRecord }
 * will be added to WAL in case of atomic operation is started outside of active storage transaction .
 * During storage restore procedure this record is monitored and if given record is present then
 * rebuild of all indexes is performed .
 * @ param lockName Name of lock ( usually name of component ) which is going participate in atomic operation .
 * @ return Instance of active atomic operation . */
public OAtomicOperation startAtomicOperation ( String lockName , boolean trackNonTxOperations ) throws IOException { } }

implementation: OAtomicOperation operation = currentOperation . get ( ) ; if ( operation != null ) { operation . incrementCounter ( ) ; if ( lockName != null ) { acquireExclusiveLockTillOperationComplete ( operation , lockName ) ; } return operation ; } atomicOperationsCount . increment ( ) ; while ( freezeRequests . get ( ) > 0 ) { assert freezeRequests . get ( ) >= 0 ; atomicOperationsCount . decrement ( ) ; throwFreezeExceptionIfNeeded ( ) ; final Thread thread = Thread . currentThread ( ) ; addThreadInWaitingList ( thread ) ; if ( freezeRequests . get ( ) > 0 ) { LockSupport . park ( this ) ; } atomicOperationsCount . increment ( ) ; } assert freezeRequests . get ( ) >= 0 ; final boolean useWal = useWal ( ) ; final OOperationUnitId unitId = OOperationUnitId . generateId ( ) ; final OLogSequenceNumber lsn = useWal ? writeAheadLog . logAtomicOperationStartRecord ( true , unitId ) : null ; operation = new OAtomicOperation ( lsn , unitId , readCache , writeCache , storage . getId ( ) ) ; currentOperation . set ( operation ) ; if ( trackAtomicOperations ) { final Thread thread = Thread . currentThread ( ) ; activeAtomicOperations . put ( unitId , new OPair < > ( thread . getName ( ) , thread . getStackTrace ( ) ) ) ; } if ( useWal && trackNonTxOperations && storage . getStorageTransaction ( ) == null ) { writeAheadLog . log ( new ONonTxOperationPerformedWALRecord ( ) ) ; } if ( lockName != null ) { acquireExclusiveLockTillOperationComplete ( operation , lockName ) ; } try { storage . checkReadOnlyConditions ( ) ; } catch ( RuntimeException | Error e ) { final Iterator < String > lockedObjectIterator = operation . lockedObjects ( ) . iterator ( ) ; while ( lockedObjectIterator . hasNext ( ) ) { final String lockedObject = lockedObjectIterator . next ( ) ; lockedObjectIterator . remove ( ) ; lockManager . releaseLock ( this , lockedObject , OOneEntryPerKeyLockManager . LOCK . EXCLUSIVE ) ; } throw e ; } return operation ;


signature:
public class OAtomicOperationsManager { /** * Ends the current atomic operation on this manager .
 * @ param rollback { @ code true } to indicate a rollback , { @ code false } for successful commit .
 * @ return the LSN produced by committing the current operation or { @ code null } if no commit was done . */
public OLogSequenceNumber endAtomicOperation ( boolean rollback ) throws IOException { } }

implementation: final OAtomicOperation operation = currentOperation . get ( ) ; if ( operation == null ) { OLogManager . instance ( ) . error ( this , "There is no atomic operation active" , null ) ; throw new ODatabaseException ( "There is no atomic operation active" ) ; } int counter = operation . getCounter ( ) ; operation . decrementCounter ( ) ; assert counter > 0 ; final OLogSequenceNumber lsn ; try { if ( rollback ) { operation . rollback ( ) ; } if ( counter == 1 ) { try { final boolean useWal = useWal ( ) ; if ( ! operation . isRollback ( ) ) { lsn = operation . commitChanges ( useWal ? writeAheadLog : null ) ; } else { lsn = null ; } if ( trackAtomicOperations ) { activeAtomicOperations . remove ( operation . getOperationUnitId ( ) ) ; } } finally { final Iterator < String > lockedObjectIterator = operation . lockedObjects ( ) . iterator ( ) ; while ( lockedObjectIterator . hasNext ( ) ) { final String lockedObject = lockedObjectIterator . next ( ) ; lockedObjectIterator . remove ( ) ; lockManager . releaseLock ( this , lockedObject , OOneEntryPerKeyLockManager . LOCK . EXCLUSIVE ) ; } currentOperation . set ( null ) ; } } else { lsn = null ; } } catch ( Error e ) { final OAbstractPaginatedStorage st = storage ; if ( st != null ) { st . handleJVMError ( e ) ; } counter = 1 ; throw e ; } finally { if ( counter == 1 ) { atomicOperationsCount . decrement ( ) ; } } return lsn ;


signature:
public class OAtomicOperationsManager { /** * Acquires exclusive lock with the given lock name in the given atomic operation .
 * @ param operation the atomic operation to acquire the lock in .
 * @ param lockName the lock name to acquire . */
public void acquireExclusiveLockTillOperationComplete ( OAtomicOperation operation , String lockName ) { } }

implementation: if ( operation . containsInLockedObjects ( lockName ) ) { return ; } lockManager . acquireLock ( lockName , OOneEntryPerKeyLockManager . LOCK . EXCLUSIVE ) ; operation . addLockedObject ( lockName ) ;


signature:
public class OAtomicOperationsManager { /** * Acquires exclusive lock in the active atomic operation running on the current thread for the { @ code durableComponent } . */
public void acquireExclusiveLockTillOperationComplete ( ODurableComponent durableComponent ) { } }

implementation: final OAtomicOperation operation = currentOperation . get ( ) ; assert operation != null ; acquireExclusiveLockTillOperationComplete ( operation , durableComponent . getLockName ( ) ) ;


signature:
public class O2QCache { /** * Changes amount of memory which may be used by given cache . This method may consume many resources if amount of memory provided
 * in parameter is much less than current amount of memory .
 * @ param readCacheMaxMemory New maximum size of cache in bytes .
 * @ throws IllegalStateException In case of new size of disk cache is too small to hold existing pinned pages . */
public void changeMaximumAmountOfMemory ( final long readCacheMaxMemory ) throws IllegalStateException { } }

implementation:
MemoryData memoryData ; MemoryData newMemoryData ; final int newMemorySize = normalizeMemory ( readCacheMaxMemory , pageSize ) ; do { memoryData = memoryDataContainer . get ( ) ; if ( memoryData . maxSize == newMemorySize ) { return ; } if ( ( 100 * memoryData . pinnedPages / newMemorySize ) > percentOfPinnedPages ) { throw new IllegalStateException ( "Cannot decrease amount of memory used by disk cache " + "because limit of pinned pages will be more than allowed limit " + percentOfPinnedPages ) ; } newMemoryData = new MemoryData ( newMemorySize , memoryData . pinnedPages ) ; } while ( ! memoryDataContainer . compareAndSet ( memoryData , newMemoryData ) ) ; // if ( newMemorySize < memoryData . maxSize )
// removeColdestPagesIfNeeded ( ) ;
OLogManager . instance ( ) . info ( this , "Disk cache size was changed from " + memoryData . maxSize + " pages to " + newMemorySize + " pages" ) ;


signature:
public class O2QCache { /** * Performs following steps :
 * < ol >
 * < li > If flag { @ link OGlobalConfiguration # STORAGE _ KEEP _ DISK _ CACHE _ STATE } is set to < code > true < / code > saves state of all queues of
 * 2Q cache into file { @ link # CACHE _ STATE _ FILE } . The only exception is pinned pages they need to pinned again . < / li >
 * < li > Closes all files and flushes all data associated to them . < / li >
 * < / ol >
 * @ param writeCache Write cache all files of which should be closed . In terms of cache write cache = storage . */
@ Override public final void closeStorage ( final OWriteCache writeCache ) throws IOException { } }

implementation: if ( writeCache == null ) { return ; } cacheLock . acquireWriteLock ( ) ; try { final long [ ] filesToClear = writeCache . close ( ) ; clearFiles ( writeCache , filesToClear ) ; } finally { cacheLock . releaseWriteLock ( ) ; }


signature:
public class O2QCache { /** * Stores state of queues of 2Q cache inside of { @ link # CACHE _ STATE _ FILE } file if flag
 * { @ link OGlobalConfiguration # STORAGE _ KEEP _ DISK _ CACHE _ STATE } is set to < code > true < / code > .
 * Following format is used to store queue state :
 * < ol >
 * < li > Max cache size , single item ( long ) < / li >
 * < li > File id or - 1 if end of queue is reached ( int ) < / li >
 * < li > Page index ( long ) , is absent if end of the queue is reached < / li >
 * < / ol >
 * @ param writeCache Write cache which manages files cache state of which is going to be stored . */
@ Override public final void storeCacheState ( final OWriteCache writeCache ) { } }

implementation: if ( ! OGlobalConfiguration . STORAGE_KEEP_DISK_CACHE_STATE . getValueAsBoolean ( ) ) { return ; } if ( writeCache == null ) { return ; } cacheLock . acquireWriteLock ( ) ; try { final Path rootDirectory = writeCache . getRootDirectory ( ) ; final Path stateFile = rootDirectory . resolve ( CACHE_STATE_FILE ) ; if ( Files . exists ( stateFile ) ) { Files . delete ( stateFile ) ; } final Set < Long > filesToStore = new HashSet < > ( writeCache . files ( ) . values ( ) ) ; try ( final FileChannel channel = FileChannel . open ( stateFile , StandardOpenOption . WRITE , StandardOpenOption . CREATE ) ) { final OutputStream channelStream = Channels . newOutputStream ( channel ) ; final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream ( channelStream , 64 * 1024 ) ; try ( final DataOutputStream dataOutputStream = new DataOutputStream ( bufferedOutputStream ) ) { dataOutputStream . writeLong ( memoryDataContainer . get ( ) . maxSize ) ; storeQueueState ( writeCache , filesToStore , dataOutputStream , am ) ; dataOutputStream . writeInt ( - 1 ) ; storeQueueState ( writeCache , filesToStore , dataOutputStream , a1in ) ; dataOutputStream . writeInt ( - 1 ) ; storeQueueState ( writeCache , filesToStore , dataOutputStream , a1out ) ; dataOutputStream . writeInt ( - 1 ) ; } } } catch ( final Exception e ) { OLogManager . instance ( ) . error ( this , "Cannot store state of cache for storage placed under %s" , e , writeCache . getRootDirectory ( ) ) ; } finally { cacheLock . releaseWriteLock ( ) ; }


signature:
public class O2QCache { /** * Stores state of single queue to the { @ link OutputStream } . Items are stored from least recently used to most recently used , so
 * in case of sequential read of data we will restore the same state of queue .
 * Not all queue items are stored , only ones which contains pages of selected files .
 * Following format is used to store queue state :
 * < ol >
 * < li > File id or - 1 if end of queue is reached ( int ) < / li >
 * < li > Page index ( long ) , is absent if end of the queue is reached < / li >
 * < / ol >
 * @ param writeCache Write cache is used to convert external file ids to internal ones .
 * @ param filesToStore List of files state of which should be stored .
 * @ param dataOutputStream Output stream for state file
 * @ param queue Queue state of which should be stored */
private static void storeQueueState ( final OWriteCache writeCache , final Set < Long > filesToStore , final DataOutputStream dataOutputStream , final LRUList queue ) throws IOException { } }

implementation: final Iterator < OCacheEntry > queueIterator = queue . reverseIterator ( ) ; while ( queueIterator . hasNext ( ) ) { final OCacheEntry cacheEntry = queueIterator . next ( ) ; final long fileId = cacheEntry . getFileId ( ) ; if ( filesToStore . contains ( fileId ) ) { final int internalId = writeCache . internalFileId ( fileId ) ; dataOutputStream . writeInt ( internalId ) ; dataOutputStream . writeLong ( cacheEntry . getPageIndex ( ) ) ; } }


signature:
public class OServerNetworkListener { /** * Initialize a server socket for communicating with the client .
 * @ param iHostPortRange
 * @ param iHostName */
private void listen ( final String iHostName , final String iHostPortRange , final String iProtocolName , Class < ? extends ONetworkProtocol > protocolClass ) { } }

implementation: for ( int port : getPorts ( iHostPortRange ) ) { inboundAddr = new InetSocketAddress ( iHostName , port ) ; try { serverSocket = socketFactory . createServerSocket ( port , 0 , InetAddress . getByName ( iHostName ) ) ; if ( serverSocket . isBound ( ) ) { OLogManager . instance ( ) . info ( this , "Listening $ANSI{green " + iProtocolName + "} connections on $ANSI{green " + inboundAddr . getAddress ( ) . getHostAddress ( ) + ":" + inboundAddr . getPort ( ) + "} (protocol v." + protocolVersion + ", socket=" + socketFactory . getName ( ) + ")" ) ; return ; } } catch ( BindException be ) { OLogManager . instance ( ) . warn ( this , "Port %s:%d busy, trying the next available..." , iHostName , port ) ; } catch ( SocketException se ) { OLogManager . instance ( ) . error ( this , "Unable to create socket" , se ) ; throw new RuntimeException ( se ) ; } catch ( IOException ioe ) { OLogManager . instance ( ) . error ( this , "Unable to read data from an open socket" , ioe ) ; System . err . println ( "Unable to read data from an open socket." ) ; throw new RuntimeException ( ioe ) ; } } OLogManager . instance ( ) . error ( this , "Unable to listen for connections using the configured ports '%s' on host '%s'" , null , iHostPortRange , iHostName ) ; throw new OSystemException ( "Unable to listen for connections using the configured ports '%s' on host '%s'" ) ;


signature:
public class OServerNetworkListener { /** * Initializes connection parameters by the reading XML configuration . If not specified , get the parameters defined as global
 * configuration .
 * @ param iServerConfig */
private void readParameters ( final OContextConfiguration iServerConfig , final OServerParameterConfiguration [ ] iParameters ) { } }

implementation:
configuration = new OContextConfiguration ( iServerConfig ) ; // SET PARAMETERS
if ( iParameters != null && iParameters . length > 0 ) { // CONVERT PARAMETERS IN MAP TO INTIALIZE THE CONTEXT - CONFIGURATION
for ( OServerParameterConfiguration param : iParameters ) configuration . setValue ( param . name , param . value ) ; } socketBufferSize = configuration . getValueAsInteger ( OGlobalConfiguration . NETWORK_SOCKET_BUFFER_SIZE ) ;


signature:
public class OLogManager { /** * Start filter out all messages which are logged using { @ link # errorStorage ( Object , String , Throwable , Object . . . ) } method . */
public void applyStorageFilter ( ) { } }

implementation: final StorageFilter filter = new StorageFilter ( ) ; if ( storageFilterHolder . compareAndSet ( null , filter ) ) { for ( Logger logger : loggersCache . values ( ) ) { logger . setFilter ( filter ) ; } }


signature:
public class OLogManager { /** * Shutdowns this log manager . */
public void shutdown ( ) { } }

implementation:
if ( shutdownFlag . compareAndSet ( false , true ) ) { try { if ( LogManager . getLogManager ( ) instanceof ShutdownLogManager ) ( ( ShutdownLogManager ) LogManager . getLogManager ( ) ) . shutdown ( ) ; } catch ( NoClassDefFoundError ignore ) { // Om nom nom . Some custom class loaders , like Tomcat ' s one , cannot load classes while in shutdown hooks , since their
// runtime is already shutdown . Ignoring the exception , if ShutdownLogManager is not loaded at this point there are no instances
// of it anyway and we have nothing to shutdown .
} }


signature:
public class OClosableLinkedContainer { /** * Adds item to the container .
 * Item should be in open state .
 * @ param key Key associated with given item .
 * @ param item Item associated with passed in key . */
public void add ( K key , V item ) throws InterruptedException { } }

implementation: if ( ! item . isOpen ( ) ) throw new IllegalArgumentException ( "All passed in items should be in open state" ) ; checkOpenFilesLimit ( ) ; final OClosableEntry < K , V > closableEntry = new OClosableEntry < K , V > ( item ) ; final OClosableEntry < K , V > oldEntry = data . putIfAbsent ( key , closableEntry ) ; if ( oldEntry != null ) { throw new IllegalStateException ( "Item with key " + key + " already exists" ) ; } logAdd ( closableEntry ) ;


signature:
public class OClosableLinkedContainer { /** * Removes item associated with passed in key .
 * @ param key Key associated with item to remove .
 * @ return Removed item . */
public V remove ( K key ) { } }

implementation: final OClosableEntry < K , V > removed = data . remove ( key ) ; if ( removed != null ) { long preStatus = removed . makeRetired ( ) ; if ( OClosableEntry . isOpen ( preStatus ) ) { countClosedFiles ( ) ; } logRemoved ( removed ) ; return removed . get ( ) ; } return null ;


signature:
public class OClosableLinkedContainer { /** * Acquires item associated with passed in key in container .
 * It is guarantied that item will not be closed if limit of open items will be exceeded and container will close rarely used
 * items .
 * @ param key Key associated with item
 * @ return Acquired item if key exists into container or < code > null < / code > if there is no item associated with given container */
public OClosableEntry < K , V > acquire ( K key ) throws InterruptedException { } }

implementation: checkOpenFilesLimit ( ) ; final OClosableEntry < K , V > entry = data . get ( key ) ; if ( entry == null ) return null ; boolean logOpen = false ; entry . acquireStateLock ( ) ; try { if ( entry . isRetired ( ) || entry . isDead ( ) ) { return null ; } else if ( entry . isClosed ( ) ) { entry . makeAcquiredFromClosed ( entry . get ( ) ) ; logOpen = true ; } else if ( entry . isOpen ( ) ) { entry . makeAcquiredFromOpen ( ) ; } else { entry . incrementAcquired ( ) ; } } finally { entry . releaseStateLock ( ) ; } if ( logOpen ) { logOpen ( entry ) ; } else { logAcquire ( entry ) ; } assert entry . get ( ) . isOpen ( ) ; return entry ;


signature:
public class OClosableLinkedContainer { /** * Checks if containers limit of open files is reached .
 * In such case execution of threads which add or acquire items is stopped and they wait till buffers will be emptied
 * and nubmer of open files will be inside limit . */
private void checkOpenFilesLimit ( ) throws InterruptedException { } }

implementation:
CountDownLatch ol = openLatch . get ( ) ; if ( ol != null ) ol . await ( ) ; while ( openFiles . get ( ) > openLimit ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; // make other threads to wait till we evict entries and close evicted open files
if ( openLatch . compareAndSet ( null , latch ) ) { while ( openFiles . get ( ) > openLimit ) { emptyBuffers ( ) ; } latch . countDown ( ) ; openLatch . set ( null ) ; } else { ol = openLatch . get ( ) ; if ( ol != null ) ol . await ( ) ; } }


signature:
public class OClosableLinkedContainer { /** * Returns item without acquiring it . State of item is not guarantied in such case .
 * @ param key Key associated with required item .
 * @ return Item associated with given key . */
public V get ( K key ) { } }

implementation: final OClosableEntry < K , V > entry = data . get ( key ) ; if ( entry != null ) return entry . get ( ) ; return null ;


signature:
public class OClosableLinkedContainer { /** * Clears all content . */
public void clear ( ) { } }

implementation: lruLock . lock ( ) ; try { data . clear ( ) ; openFiles . set ( 0 ) ; for ( int n = 0 ; n < NUMBER_OF_READ_BUFFERS ; n ++ ) { final AtomicReference < OClosableEntry < K , V > > [ ] buffer = readBuffers [ n ] ; for ( int i = 0 ; i < READ_BUFFER_SIZE ; i ++ ) { buffer [ i ] . set ( null ) ; } readBufferReadCount [ n ] = 0 ; readBufferWriteCount [ n ] . set ( 0 ) ; readBufferDrainAtWriteCount [ n ] . set ( 0 ) ; } stateBuffer . clear ( ) ; while ( lruList . poll ( ) != null ) ; } finally { lruLock . unlock ( ) ; }


signature:
public class OClosableLinkedContainer { /** * Closes item related to passed in key .
 * Item will be closed if it exists and is not acquired .
 * @ param key Key related to item that has going to be closed .
 * @ return < code > true < / code > if item was closed and < code > false < / code > otherwise . */
public boolean close ( K key ) { } }

implementation: emptyBuffers ( ) ; final OClosableEntry < K , V > entry = data . get ( key ) ; if ( entry == null ) return true ; if ( entry . makeClosed ( ) ) { countClosedFiles ( ) ; return true ; } return false ;


signature:
public class OClosableLinkedContainer { /** * Read content of write buffer and adds / removes LRU entries to update internal statistic .
 * Method has to be wrapped by LRU lock . */
private void emptyWriteBuffer ( ) { } }

implementation: Runnable task = stateBuffer . poll ( ) ; while ( task != null ) { task . run ( ) ; task = stateBuffer . poll ( ) ; }


signature:
public class OClosableLinkedContainer { /** * Read content of all read buffers and reorder elements inside of LRU list to update internal statistic .
 * Method has to be wrapped by LRU lock . */
private void emptyReadBuffers ( ) { } }

implementation: for ( int n = 0 ; n < NUMBER_OF_READ_BUFFERS ; n ++ ) { AtomicReference < OClosableEntry < K , V > > [ ] buffer = readBuffers [ n ] ; long writeCount = readBufferDrainAtWriteCount [ n ] . get ( ) ; long counter = readBufferReadCount [ n ] ; while ( true ) { final int bufferIndex = ( int ) ( counter & READ_BUFFER_INDEX_MASK ) ; final AtomicReference < OClosableEntry < K , V > > eref = buffer [ bufferIndex ] ; final OClosableEntry < K , V > entry = eref . get ( ) ; if ( entry == null ) break ; applyRead ( entry ) ; counter ++ ; eref . lazySet ( null ) ; } readBufferReadCount [ n ] = counter ; readBufferDrainAtWriteCount [ n ] . lazySet ( writeCount ) ; }


signature:
public class OClosableLinkedContainer { /** * Method is used to log operations which change content of the container .
 * Such changes should be flushed immediately to update content of LRU list .
 * @ param task Task which contains code is used to manipulate LRU list */
private void afterWrite ( Runnable task ) { } }

implementation: stateBuffer . add ( task ) ; drainStatus . lazySet ( DrainStatus . REQUIRED ) ; tryToDrainBuffers ( ) ;


signature:
public class OClosableLinkedContainer { /** * Method is used to log operations which do not change LRU list content but affect order of items inside of LRU list .
 * Such changes may be delayed till buffer will be full .
 * @ param entry Entry which was affected by operation . */
private void afterRead ( OClosableEntry < K , V > entry ) { } }

implementation: final int bufferIndex = readBufferIndex ( ) ; final long writeCount = putEntryInReadBuffer ( entry , bufferIndex ) ; drainReadBuffersIfNeeded ( bufferIndex , writeCount ) ;


signature:
public class OClosableLinkedContainer { /** * Adds entry to the read buffer with selected index and returns amount of writes to this buffer since creation of this container .
 * @ param entry LRU entry to add .
 * @ param bufferIndex Index of buffer
 * @ return Amount of writes to the buffer since creation of this container . */
private long putEntryInReadBuffer ( OClosableEntry < K , V > entry , int bufferIndex ) { } }

implementation:
// next index to write for this buffer
AtomicLong writeCounter = readBufferWriteCount [ bufferIndex ] ; final long counter = writeCounter . get ( ) ; // we do not use CAS operations to limit contention between threads
// it is normal that because of duplications of indexes some of items will be lost
writeCounter . lazySet ( counter + 1 ) ; final AtomicReference < OClosableEntry < K , V > > [ ] buffer = readBuffers [ bufferIndex ] ; AtomicReference < OClosableEntry < K , V > > bufferEntry = buffer [ ( int ) ( counter & READ_BUFFER_INDEX_MASK ) ] ; bufferEntry . lazySet ( entry ) ; return counter + 1 ;


signature:
public class OClosableLinkedContainer { /** * Finds closest power of two for given integer value . Idea is simple duplicate the most significant bit to the lowest bits for
 * the smallest number of iterations possible and then increment result value by 1.
 * @ param value Integer the most significant power of 2 should be found .
 * @ return The most significant power of 2. */
private static int closestPowerOfTwo ( int value ) { } }


signature:
public class OLongSerializer { /** * { @ inheritDoc } */
@ Override public void serializeInByteBufferObject ( Long object , ByteBuffer buffer , Object ... hints ) { } }

implementation: buffer . putLong ( object ) ;


signature:
public class OLongSerializer { /** * { @ inheritDoc } */
@ Override public Long deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { } }

implementation: return walChanges . getLongValue ( buffer , offset ) ;


signature:
public class OLiveQueryClientListener { /** * Return true if the push request require an unregister
 * @ param pushRequest
 * @ return */
public boolean onEvent ( OLiveQueryPushRequest pushRequest ) { } }

implementation: ODatabaseDocumentInternal old = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { database . activateOnCurrentThread ( ) ; if ( pushRequest . getStatus ( ) == OLiveQueryPushRequest . ERROR ) { onError ( pushRequest . getErrorCode ( ) . newException ( pushRequest . getErrorMessage ( ) , null ) ) ; return true ; } else { for ( OLiveQueryResult result : pushRequest . getEvents ( ) ) { switch ( result . getEventType ( ) ) { case OLiveQueryResult . CREATE_EVENT : listener . onCreate ( database , result . getCurrentValue ( ) ) ; break ; case OLiveQueryResult . UPDATE_EVENT : listener . onUpdate ( database , result . getOldValue ( ) , result . getCurrentValue ( ) ) ; break ; case OLiveQueryResult . DELETE_EVENT : listener . onDelete ( database , result . getCurrentValue ( ) ) ; break ; } } if ( pushRequest . getStatus ( ) == OLiveQueryPushRequest . END ) { onEnd ( ) ; return true ; } } return false ; } finally { ODatabaseRecordThreadLocal . instance ( ) . set ( old ) ; }


signature:
public class OStreamSerializerAnyStreamable { /** * Re - Create any object if the class has a public constructor that accepts a String as unique parameter . */
public OCommandRequestText fromStream ( final byte [ ] iStream , ORecordSerializer serializer ) throws IOException { } }

implementation:
if ( iStream == null || iStream . length == 0 ) // NULL VALUE
return null ; final int classNameSize = OBinaryProtocol . bytes2int ( iStream ) ; if ( classNameSize <= 0 ) { final String message = "Class signature not found in ANY element: " + Arrays . toString ( iStream ) ; OLogManager . instance ( ) . error ( this , message , null ) ; throw new OSerializationException ( message ) ; } final String className = new String ( iStream , 4 , classNameSize , "UTF-8" ) ; try { final OCommandRequestText stream ; // CHECK FOR ALIASES
if ( className . equalsIgnoreCase ( "q" ) ) // QUERY
stream = new OSQLSynchQuery < Object > ( ) ; else if ( className . equalsIgnoreCase ( "c" ) ) // SQL COMMAND
stream = new OCommandSQL ( ) ; else if ( className . equalsIgnoreCase ( "s" ) ) // SCRIPT COMMAND
stream = new OCommandScript ( ) ; else // CREATE THE OBJECT BY INVOKING THE EMPTY CONSTRUCTOR
stream = ( OCommandRequestText ) Class . forName ( className ) . newInstance ( ) ; return stream . fromStream ( OArrays . copyOfRange ( iStream , 4 + classNameSize , iStream . length ) , serializer ) ; } catch ( Exception e ) { final String message = "Error on unmarshalling content. Class: " + className ; OLogManager . instance ( ) . error ( this , message , e ) ; throw OException . wrapException ( new OSerializationException ( message ) , e ) ; }


signature:
public class OStreamSerializerAnyStreamable { /** * Serialize the class name size + class name + object content */
public byte [ ] toStream ( final OCommandRequestText iObject ) throws IOException { } }

implementation:
if ( iObject == null ) return null ; // SERIALIZE THE CLASS NAME
final byte [ ] className ; if ( iObject instanceof OLiveQuery < ? > ) className = iObject . getClass ( ) . getName ( ) . getBytes ( "UTF-8" ) ; else if ( iObject instanceof OSQLSynchQuery < ? > ) className = QUERY_COMMAND_CLASS_ASBYTES ; else if ( iObject instanceof OCommandSQL ) className = SQL_COMMAND_CLASS_ASBYTES ; else if ( iObject instanceof OCommandScript ) className = SCRIPT_COMMAND_CLASS_ASBYTES ; else { if ( iObject == null ) className = null ; else className = iObject . getClass ( ) . getName ( ) . getBytes ( "UTF-8" ) ; } // SERIALIZE THE OBJECT CONTENT
byte [ ] objectContent = iObject . toStream ( ) ; byte [ ] result = new byte [ 4 + className . length + objectContent . length ] ; // COPY THE CLASS NAME SIZE + CLASS NAME + OBJECT CONTENT
System . arraycopy ( OBinaryProtocol . int2bytes ( className . length ) , 0 , result , 0 , 4 ) ; System . arraycopy ( className , 0 , result , 4 , className . length ) ; System . arraycopy ( objectContent , 0 , result , 4 + className . length , objectContent . length ) ; return result ;


signature:
public class OStringSerializerEmbedded { /** * Re - Create any object if the class has a public constructor that accepts a String as unique parameter . */
public Object fromStream ( final String iStream ) { } }

implementation:
if ( iStream == null || iStream . length ( ) == 0 ) // NULL VALUE
return null ; final ODocument instance = new ODocument ( ) ; try { ORecordSerializerSchemaAware2CSV . INSTANCE . fromStream ( iStream . getBytes ( "UTF-8" ) , instance , null ) ; } catch ( UnsupportedEncodingException e ) { throw OException . wrapException ( new OSerializationException ( "Error decoding string" ) , e ) ; } final String className = instance . field ( ODocumentSerializable . CLASS_NAME ) ; if ( className == null ) return instance ; Class < ? > clazz = null ; try { clazz = Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { OLogManager . instance ( ) . debug ( this , "Class name provided in embedded document " + className + " does not exist." , e ) ; } if ( clazz == null ) return instance ; if ( ODocumentSerializable . class . isAssignableFrom ( clazz ) ) { try { final ODocumentSerializable documentSerializable = ( ODocumentSerializable ) clazz . newInstance ( ) ; final ODocument docClone = new ODocument ( ) ; instance . copyTo ( docClone ) ; docClone . removeField ( ODocumentSerializable . CLASS_NAME ) ; documentSerializable . fromDocument ( docClone ) ; return documentSerializable ; } catch ( InstantiationException e ) { throw OException . wrapException ( new OSerializationException ( "Cannot serialize the object" ) , e ) ; } catch ( IllegalAccessException e ) { throw OException . wrapException ( new OSerializationException ( "Cannot serialize the object" ) , e ) ; } } return instance ;


signature:
public class OStringSerializerEmbedded { /** * Serialize the class name size + class name + object content */
public StringBuilder toStream ( final StringBuilder iOutput , Object iValue ) { } }

implementation: if ( iValue != null ) { if ( iValue instanceof ODocumentSerializable ) iValue = ( ( ODocumentSerializable ) iValue ) . toDocument ( ) ; if ( ! ( iValue instanceof OSerializableStream ) ) throw new OSerializationException ( "Cannot serialize the object since it's not implements the OSerializableStream interface" ) ; OSerializableStream stream = ( OSerializableStream ) iValue ; iOutput . append ( iValue . getClass ( ) . getName ( ) ) ; iOutput . append ( SEPARATOR ) ; try { iOutput . append ( new String ( stream . toStream ( ) , "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { throw OException . wrapException ( new OSerializationException ( "Error serializing embedded object" ) , e ) ; } } return iOutput ;


signature:
public class OObjectEnumLazyMap { /** * Assure that the requested key is converted . */
private void convert ( final Object iKey ) { } }

implementation: if ( converted ) return ; if ( super . containsKey ( iKey ) ) return ; Object o = underlying . get ( String . valueOf ( iKey ) ) ; if ( o instanceof Number ) super . put ( iKey , enumClass . getEnumConstants ( ) [ ( ( Number ) o ) . intValue ( ) ] ) ; else super . put ( iKey , Enum . valueOf ( enumClass , o . toString ( ) ) ) ;


signature:
public class OObjectEnumLazyMap { /** * Converts all the items */
protected void convertAll ( ) { } }

implementation: if ( converted ) return ; for ( java . util . Map . Entry < Object , Object > e : underlying . entrySet ( ) ) { if ( e . getValue ( ) instanceof Number ) super . put ( e . getKey ( ) , enumClass . getEnumConstants ( ) [ ( ( Number ) e . getValue ( ) ) . intValue ( ) ] ) ; else super . put ( e . getKey ( ) , Enum . valueOf ( enumClass , e . getValue ( ) . toString ( ) ) ) ; } converted = true ;


signature:
public class OBinarySerializerFactory { /** * Obtain OBinarySerializer realization for the OType
 * @ param type is the OType to obtain serializer algorithm for
 * @ return OBinarySerializer instance */
@ SuppressWarnings ( "unchecked" ) public < T > OBinarySerializer < T > getObjectSerializer ( final OType type ) { } }

implementation: return ( OBinarySerializer < T > ) serializerTypeMap . get ( type ) ;


signature:
public class ODistributedDatabaseImpl { /** * Distributed requests against the available workers by using one queue per worker . This guarantee the sequence of the operations
 * against the same record cluster . */
public void processRequest ( final ODistributedRequest request , final boolean waitForAcceptingRequests ) { } }

implementation:
if ( ! running ) { throw new ODistributedException ( "Server is going down or is removing the database:'" + getDatabaseName ( ) + "' discarding" ) ; } final ORemoteTask task = request . getTask ( ) ; if ( waitForAcceptingRequests ) { waitIsReady ( task ) ; if ( ! running ) { throw new ODistributedException ( "Server is going down or is removing the database:'" + getDatabaseName ( ) + "' discarding" ) ; } } totalReceivedRequests . incrementAndGet ( ) ; // final ODistributedMomentum lastMomentum = filterByMomentum . get ( ) ;
// if ( lastMomentum ! = null & & task instanceof OAbstractReplicatedTask ) {
// final OLogSequenceNumber taskLastLSN = ( ( OAbstractReplicatedTask ) task ) . getLastLSN ( ) ;
// final String sourceServer = manager . getNodeNameById ( request . getId ( ) . getNodeId ( ) ) ;
// final OLogSequenceNumber lastLSNFromMomentum = lastMomentum . getLSN ( sourceServer ) ;
// if ( taskLastLSN ! = null & & lastLSNFromMomentum ! = null & & taskLastLSN . compareTo ( lastLSNFromMomentum ) < 0 ) {
// / / SKIP REQUEST BECAUSE CONTAINS AN OLD LSN
// final String msg = String . format ( " Skipped request % s on database ' % s ' because % s < current % s " , request , databaseName ,
// taskLastLSN , lastLSNFromMomentum ) ;
// ODistributedServerLog . info ( this , localNodeName , null , DIRECTION . NONE , msg ) ;
// ODistributedWorker . sendResponseBack ( this , manager , request , new ODistributedException ( msg ) ) ;
// return ;
final int [ ] partitionKeys = task . getPartitionKey ( ) ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , localNodeName , task . getNodeSource ( ) , DIRECTION . IN , "Request %s on database '%s' partitionKeys=%s task=%s" , request , databaseName , Arrays . toString ( partitionKeys ) , task ) ; if ( partitionKeys . length > 1 || partitionKeys [ 0 ] == - 1 ) { final Set < Integer > involvedWorkerQueues ; if ( partitionKeys . length > 1 ) involvedWorkerQueues = getInvolvedQueuesByPartitionKeys ( partitionKeys ) ; else // LOCK ALL THE QUEUES
involvedWorkerQueues = ALL_QUEUES ; // if ( ODistributedServerLog . isDebugEnabled ( ) )
ODistributedServerLog . debug ( this , localNodeName , null , DIRECTION . NONE , "Request %s on database '%s' involvedQueues=%s" , request , databaseName , involvedWorkerQueues ) ; if ( involvedWorkerQueues . size ( ) == 1 ) // JUST ONE QUEUE INVOLVED : PROCESS IT IMMEDIATELY
processRequest ( involvedWorkerQueues . iterator ( ) . next ( ) , request ) ; else { // INVOLVING MULTIPLE QUEUES
// if ( ODistributedServerLog . isDebugEnabled ( ) )
ODistributedServerLog . debug ( this , localNodeName , null , DIRECTION . NONE , "Request %s on database '%s' waiting for all the previous requests to be completed" , request , databaseName ) ; // WAIT ALL THE INVOLVED QUEUES ARE FREE AND SYNCHRONIZED
final CountDownLatch syncLatch = new CountDownLatch ( involvedWorkerQueues . size ( ) ) ; final ODistributedRequest syncRequest = new ODistributedRequest ( null , request . getId ( ) . getNodeId ( ) , - 1 , databaseName , new OSynchronizedTaskWrapper ( syncLatch ) ) ; for ( int queue : involvedWorkerQueues ) { ODistributedWorker worker = workerThreads . get ( queue ) ; worker . processRequest ( syncRequest ) ; } // Make infinite timeout everytime
long taskTimeout = 0 ; try { if ( taskTimeout <= 0 ) syncLatch . await ( ) ; else { // WAIT FOR COMPLETION . THE TIMEOUT IS MANAGED IN SMALLER CYCLES TO PROPERLY RECOGNIZE WHEN THE DB IS REMOVED
final long start = System . currentTimeMillis ( ) ; final long cycleTimeout = Math . min ( taskTimeout , 2000 ) ; boolean locked = false ; do { if ( syncLatch . await ( cycleTimeout , TimeUnit . MILLISECONDS ) ) { // DONE
locked = true ; break ; } if ( this . workerThreads . size ( ) == 0 ) // DATABASE WAS SHUTDOWN
break ; } while ( System . currentTimeMillis ( ) - start < taskTimeout ) ; if ( ! locked ) { final String msg = String . format ( "Cannot execute distributed request (%s) because all worker threads (%d) are busy (pending=%d timeout=%d)" , request , workerThreads . size ( ) , syncLatch . getCount ( ) , taskTimeout ) ; ODistributedWorker . sendResponseBack ( this , manager , request , new ODistributedOperationException ( msg ) ) ; return ; } } } catch ( InterruptedException e ) { // IGNORE
Thread . currentThread ( ) . interrupt ( ) ; final String msg = String . format ( "Cannot execute distributed request (%s) because all worker threads (%d) are busy" , request , workerThreads . size ( ) ) ; ODistributedWorker . sendResponseBack ( this , manager , request , new ODistributedOperationException ( msg ) ) ; return ; } // PUT THE TASK TO EXECUTE ONLY IN THE FIRST QUEUE AND PUT WAIT - FOR TASKS IN THE OTHERS . WHEN THE REAL TASK IS EXECUTED ,
// ALL THE OTHER TASKS WILL RETURN , SO THE QUEUES WILL BE BUSY DURING THE EXECUTION OF THE TASK . THIS AVOID CONCURRENT
// EXECUTION FOR THE SAME PARTITION
final CountDownLatch queueLatch = new CountDownLatch ( 1 ) ; int i = 0 ; for ( int queue : involvedWorkerQueues ) { final ODistributedRequest req ; if ( i ++ == 0 ) { // USE THE FIRST QUEUE TO PROCESS THE REQUEST
final String senderNodeName = manager . getNodeNameById ( request . getId ( ) . getNodeId ( ) ) ; request . setTask ( new OSynchronizedTaskWrapper ( queueLatch , senderNodeName , task ) ) ; req = request ; } else req = new ODistributedRequest ( manager , request . getId ( ) . getNodeId ( ) , - 1 , databaseName , new OWaitForTask ( queueLatch ) ) ; workerThreads . get ( queue ) . processRequest ( req ) ; } } } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 2 ) { // ANY PARTITION : USE THE FIRST EMPTY IF ANY , OTHERWISE THE FIRST IN THE LIST
boolean found = false ; for ( ODistributedWorker q : workerThreads ) { if ( q . isWaitingForNextRequest ( ) && q . localQueue . isEmpty ( ) ) { q . processRequest ( request ) ; found = true ; break ; } } if ( ! found ) // ALL THE THREADS ARE BUSY , SELECT THE FIRST EMPTY ONE
for ( ODistributedWorker q : workerThreads ) { if ( q . localQueue . isEmpty ( ) ) { q . processRequest ( request ) ; found = true ; break ; } } if ( ! found ) // EXEC ON THE FIRST QUEUE
workerThreads . get ( 0 ) . processRequest ( request ) ; } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 3 ) { // SERVICE - LOCK
ODistributedServerLog . debug ( this , localNodeName , request . getTask ( ) . getNodeSource ( ) , DIRECTION . IN , "Request %s on database '%s' dispatched to the lock worker" , request , databaseName ) ; lockThread . processRequest ( request ) ; } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 4 ) { // SERVICE - FAST _ NOLOCK
ODistributedServerLog . debug ( this , localNodeName , request . getTask ( ) . getNodeSource ( ) , DIRECTION . IN , "Request %s on database '%s' dispatched to the nowait worker" , request , databaseName ) ; nowaitThread . processRequest ( request ) ; } else { processRequest ( partitionKeys [ 0 ] , request ) ; }


signature:
public class Orient { /** * Add handler which will be executed during { @ link # shutdown ( ) } call .
 * @ param shutdownHandler Shutdown handler instance . */
public void addShutdownHandler ( OShutdownHandler shutdownHandler ) { } }

implementation: engineLock . writeLock ( ) . lock ( ) ; try { shutdownHandlers . add ( shutdownHandler ) ; } finally { engineLock . writeLock ( ) . unlock ( ) ; }


signature:
public class Orient { /** * Adds shutdown handlers in order which will be used during execution of shutdown . */
private void initShutdownQueue ( ) { } }

implementation: addShutdownHandler ( new OShutdownWorkersHandler ( ) ) ; addShutdownHandler ( new OShutdownOrientDBInstancesHandler ( ) ) ; addShutdownHandler ( new OShutdownPendingThreadsHandler ( ) ) ; addShutdownHandler ( new OShutdownProfilerHandler ( ) ) ; addShutdownHandler ( new OShutdownCallListenersHandler ( ) ) ;


signature:
public class Orient { /** * Shutdown whole OrientDB ecosystem . Usually is called during JVM shutdown by JVM shutdown handler . During shutdown all handlers
 * which were registered by the call of { @ link # addShutdownHandler ( OShutdownHandler ) } are called together with pre - registered
 * system shoutdown handlers according to their priority .
 * @ see OShutdownWorkersHandler
 * @ see */
private void registerEngines ( ) { } }

implementation: ClassLoader classLoader = Orient . class . getClassLoader ( ) ; Iterator < OEngine > engines = OClassLoaderHelper . lookupProviderWithOrientClassLoader ( OEngine . class , classLoader ) ; OEngine engine = null ; while ( engines . hasNext ( ) ) { try { engine = engines . next ( ) ; registerEngine ( engine ) ; } catch ( IllegalArgumentException e ) { if ( engine != null ) OLogManager . instance ( ) . debug ( this , "Failed to replace engine " + engine . getName ( ) , e ) ; } }


signature:
public class Orient { /** * Returns the engine by its name .
 * @ param engineName Engine name to retrieve
 * @ return OEngine instance of found , otherwise null */
public OEngine getEngine ( final String engineName ) { } }

implementation: engineLock . readLock ( ) . lock ( ) ; try { return engines . get ( engineName ) ; } finally { engineLock . readLock ( ) . unlock ( ) ; }


signature:
public class Orient { /** * Obtains an { @ link OEngine engine } instance with the given { @ code engineName } , if it is { @ link OEngine # isRunning ( ) running } .
 * @ param engineName the name of the engine to obtain .
 * @ return the obtained engine instance or { @ code null } if no such engine known or the engine is not running . */
public OEngine getEngineIfRunning ( final String engineName ) { } }

implementation: engineLock . readLock ( ) . lock ( ) ; try { final OEngine engine = engines . get ( engineName ) ; return engine == null || ! engine . isRunning ( ) ? null : engine ; } finally { engineLock . readLock ( ) . unlock ( ) ; }


signature:
public class Orient { /** * Obtains a { @ link OEngine # isRunning ( ) running } { @ link OEngine engine } instance with the given { @ code engineName } . If engine is
 * not running , starts it .
 * @ param engineName the name of the engine to obtain .
 * @ return the obtained running engine instance , never { @ code null } .
 * @ throws IllegalStateException if an engine with the given is not found or failed to start . */
public OEngine getRunningEngine ( final String engineName ) { } }

implementation: engineLock . readLock ( ) . lock ( ) ; try { OEngine engine = engines . get ( engineName ) ; if ( engine == null ) throw new IllegalStateException ( "Engine '" + engineName + "' is not found." ) ; if ( ! engine . isRunning ( ) && ! startEngine ( engine ) ) throw new IllegalStateException ( "Engine '" + engineName + "' is failed to start." ) ; return engine ; } finally { engineLock . readLock ( ) . unlock ( ) ; }


signature:
public class OProfileStorageStatement { /** * new execution logic */
@ Override public OResultSet executeSimple ( OCommandContext ctx ) { } }

implementation:
OResultInternal result = new OResultInternal ( ) ; result . setProperty ( "operation" , "optimize database" ) ; OStorage storage = ( ( ODatabaseInternal ) ctx . getDatabase ( ) ) . getStorage ( ) ; if ( on ) { // activate the profiler
( ( OAbstractPaginatedStorage ) storage ) . startGatheringPerformanceStatisticForCurrentThread ( ) ; result . setProperty ( "value" , "on" ) ; } else { // stop the profiler and return the stats
final OSessionStoragePerformanceStatistic performanceStatistic = ( ( OAbstractPaginatedStorage ) storage ) . completeGatheringPerformanceStatisticForCurrentThread ( ) ; result . setProperty ( "value" , "off" ) ; if ( performanceStatistic != null ) { result . setProperty ( "result" , performanceStatistic . toDocument ( ) ) ; } else { result . setProperty ( "result" , "error" ) ; result . setProperty ( "errorMessage" , "profiling of storage was not started" ) ; } } OInternalResultSet rs = new OInternalResultSet ( ) ; rs . add ( result ) ; return rs ;


signature:
public class OProfileStorageStatement { /** * old execution logic */
@ Override public Object execute ( OSQLAsynchQuery < ODocument > request , OCommandContext context , OProgressListener progressListener ) { } }

implementation:
try { ODatabaseDocumentInternal db = getDatabase ( ) ; final OStorage storage = db . getStorage ( ) ; if ( on ) { // activate the profiler
( ( OAbstractPaginatedStorage ) storage ) . startGatheringPerformanceStatisticForCurrentThread ( ) ; ODocument result = new ODocument ( ) ; result . field ( "result" , "OK" ) ; request . getResultListener ( ) . result ( result ) ; } else { // stop the profiler and return the stats
final OSessionStoragePerformanceStatistic performanceStatistic = ( ( OAbstractPaginatedStorage ) storage ) . completeGatheringPerformanceStatisticForCurrentThread ( ) ; if ( performanceStatistic != null ) request . getResultListener ( ) . result ( performanceStatistic . toDocument ( ) ) ; else { ODocument result = new ODocument ( ) ; result . field ( "result" , "Error: profiling of storage was not started." ) ; request . getResultListener ( ) . result ( result ) ; } } return getResult ( request ) ; } finally { if ( request . getResultListener ( ) != null ) { request . getResultListener ( ) . end ( ) ; } }


signature:
public class ScalableRWLock { /** * This function should be called only from ReadersEntry . finalize ( )
 * @ param state The reader ' s state that we wish to remove from the ConcurrentLinkedQueue */
protected void removeState ( AtomicInteger state ) { } }

implementation:
readersStateList . remove ( state ) ; readersStateArrayRef . set ( null ) ; // Paranoia : just in case someone forgot to call sharedUnlock ( )
// and there is a Writer waiting on that state
state . set ( SRWL_STATE_NOT_READING ) ;


signature:
public class ScalableRWLock { /** * Creates a new ReadersEntry instance for the current thread and
 * its associated AtomicInteger to store the state of the Reader
 * @ return Returns a reference to the newly created instance of
 * { @ code ReadersEntry } */
private ReadersEntry addState ( ) { } }

implementation: final AtomicInteger state = new AtomicInteger ( SRWL_STATE_NOT_READING ) ; final ReadersEntry newEntry = new ReadersEntry ( state ) ; entry . set ( newEntry ) ; readersStateList . add ( state ) ; readersStateArrayRef . set ( null ) ; return newEntry ;


signature:
public class ScalableRWLock { /** * Acquires the read lock .
 * < p > Acquires the read lock if the write lock is not held by
 * another thread and returns immediately .
 * < p > If the write lock is held by another thread then
 * the current thread yields until the write lock is released . */
public void sharedLock ( ) { } }

implementation:
ReadersEntry localEntry = entry . get ( ) ; // Initialize a new Reader - state for this thread if needed
if ( localEntry == null ) { localEntry = addState ( ) ; } final AtomicInteger currentReadersState = localEntry . state ; // The " optimistic " code path takes only two synchronized calls :
// a set ( ) on a cache line that should be held in exclusive mode
// by the current thread , and a get ( ) on a cache line that is shared .
while ( true ) { currentReadersState . set ( SRWL_STATE_READING ) ; if ( ! stampedLock . isWriteLocked ( ) ) { // Acquired lock in read - only mode
return ; } else { // Go back to SRWL _ STATE _ NOT _ READING to avoid blocking a Writer
currentReadersState . set ( SRWL_STATE_NOT_READING ) ; // Some ( other ) thread is holding the write - lock , we must wait
while ( stampedLock . isWriteLocked ( ) ) { Thread . yield ( ) ; } } }


signature:
public class ScalableRWLock { /** * Attempts to release the read lock .
 * < p > If the current thread is the holder of this lock then
 * the { @ code reentrantReaderCount } is decremented . If the
 * { @ code reentrantReaderCount } is now zero then the lock is released .
 * If the current thread is not the holder of this lock then { @ link
 * IllegalMonitorStateException } is thrown .
 * @ throws IllegalMonitorStateException if the current thread does not
 * hold this lock . */
public void sharedUnlock ( ) { } }

implementation:
final ReadersEntry localEntry = entry . get ( ) ; if ( localEntry == null ) { // ERROR : Tried to unlock a non read - locked lock
throw new IllegalMonitorStateException ( ) ; } else { localEntry . state . set ( SRWL_STATE_NOT_READING ) ; return ; }


signature:
public class ScalableRWLock { /** * Acquires the write lock .
 * < p > Acquires the write lock if neither the read nor write lock
 * are held by another thread and returns immediately , setting
 * the write lock { @ code reentrantWriterCount } to one .
 * < p > If the current thread already holds the write lock then the
 * { @ code reentrantWriterCount } is incremented by one and the method
 * returns immediately .
 * < p > If the lock is held by another thread , then the current
 * thread yields and lies dormant until the write lock has been acquired ,
 * at which time the { @ code reentrantWriterCount } is set to one . */
public void exclusiveLock ( ) { } }

implementation:
// Try to acquire the lock in write - mode
stampedLock . writeLock ( ) ; // We can only do this after writerOwner has been set to the current thread
AtomicInteger [ ] localReadersStateArray = readersStateArrayRef . get ( ) ; if ( localReadersStateArray == null ) { // Set to dummyArray before scanning the readersStateList to impose
// a linearizability condition
readersStateArrayRef . set ( dummyArray ) ; // Copy readersStateList to an array
localReadersStateArray = readersStateList . toArray ( new AtomicInteger [ readersStateList . size ( ) ] ) ; readersStateArrayRef . compareAndSet ( dummyArray , localReadersStateArray ) ; } // Scan the array of Reader states
for ( AtomicInteger readerState : localReadersStateArray ) { while ( readerState != null && readerState . get ( ) == SRWL_STATE_READING ) { Thread . yield ( ) ; } }


signature:
public class ScalableRWLock { /** * Acquires the read lock only if the write lock is not held by
 * another thread at the time of invocation .
 * < p > Acquires the read lock if the write lock is not held by
 * another thread and returns immediately with the value
 * { @ code true } .
 * < p > If the write lock is held by another thread then
 * this method will return immediately with the value
 * { @ code false } .
 * @ return { @ code true } if the read lock was acquired */
public boolean sharedTryLock ( ) { } }

implementation:
ReadersEntry localEntry = entry . get ( ) ; // Initialize a new Reader - state for this thread if needed
if ( localEntry == null ) { localEntry = addState ( ) ; } final AtomicInteger currentReadersState = localEntry . state ; currentReadersState . set ( SRWL_STATE_READING ) ; if ( ! stampedLock . isWriteLocked ( ) ) { // Acquired lock in read - only mode
return true ; } else { // Go back to SRWL _ STATE _ NOT _ READING and quit
currentReadersState . set ( SRWL_STATE_NOT_READING ) ; return false ; }


signature:
public class ScalableRWLock { /** * Acquires the read lock if the write lock is not held by
 * another thread within the given waiting time .
 * < p > Acquires the read lock if the write lock is not held by
 * another thread and returns immediately with the value
 * { @ code true } .
 * < p > If the write lock is held by another thread then the
 * current thread yields execution until one of two things happens :
 * < ul >
 * < li > The read lock is acquired by the current thread ; or
 * < li > The specified waiting time elapses .
 * < / ul >
 * < p > If the read lock is acquired then the value { @ code true } is
 * returned .
 * @ param nanosTimeout the time to wait for the read lock in nanoseconds
 * @ return { @ code true } if the read lock was acquired */
public boolean sharedTryLockNanos ( long nanosTimeout ) { } }

implementation:
final long lastTime = System . nanoTime ( ) ; ReadersEntry localEntry = entry . get ( ) ; // Initialize a new Reader - state for this thread if needed
if ( localEntry == null ) { localEntry = addState ( ) ; } final AtomicInteger currentReadersState = localEntry . state ; while ( true ) { currentReadersState . set ( SRWL_STATE_READING ) ; if ( ! stampedLock . isWriteLocked ( ) ) { // Acquired lock in read - only mode
return true ; } else { // Go back to SRWL _ STATE _ NOT _ READING to avoid blocking a Writer
// and then check if this is a downgrade .
currentReadersState . set ( SRWL_STATE_NOT_READING ) ; if ( nanosTimeout <= 0 ) return false ; if ( System . nanoTime ( ) - lastTime < nanosTimeout ) { Thread . yield ( ) ; } else { return false ; } } }


signature:
public class ScalableRWLock { /** * Acquires the write lock only if it is not held by another thread
 * at the time of invocation .
 * < p > Acquires the write lock if the write lock is not
 * held by another thread and returns immediately with
 * the value { @ code true } if and only if no other thread is attempting a
 * read lock , setting the write lock { @ code writerLoop }
 * count to one .
 * < p > If the current thread already holds this lock then the
 * { @ code reentrantWriterCount } count is incremented by one and the method returns
 * { @ code true } .
 * < p > If the write lock is held by another thread then this method
 * will return immediately with the value { @ code false } .
 * @ return { @ code true } if the write lock was free and was acquired
 * by the current thread , or the write lock was already held
 * by the current thread ; and { @ code false } otherwise . */
public boolean exclusiveTryLock ( ) { } }

implementation:
// Try to acquire the lock in write - mode
if ( stampedLock . tryWriteLock ( ) == 0 ) { return false ; } // We can only do this after writerOwner has been set to the current thread
AtomicInteger [ ] localReadersStateArray = readersStateArrayRef . get ( ) ; if ( localReadersStateArray == null ) { // Set to dummyArray before scanning the readersStateList to impose
// a linearizability condition
readersStateArrayRef . set ( dummyArray ) ; // Copy readersStateList to an array
localReadersStateArray = readersStateList . toArray ( new AtomicInteger [ readersStateList . size ( ) ] ) ; readersStateArrayRef . compareAndSet ( dummyArray , localReadersStateArray ) ; } // Scan the array of Reader states
for ( AtomicInteger readerState : localReadersStateArray ) { if ( readerState != null && readerState . get ( ) == SRWL_STATE_READING ) { // There is at least one ongoing Reader so give up
stampedLock . asWriteLock ( ) . unlock ( ) ; return false ; } } return true ;


signature:
public class ScalableRWLock { /** * Acquires the write lock if it is not held by another thread
 * within the given waiting time .
 * < p > Acquires the write lock if the write lock is not
 * held by another thread and returns immediately with
 * the value { @ code true } if and only if no other thread is attempting a
 * read lock , setting the write lock { @ code reentrantWriterCount }
 * to one . If another thread is attempting a read lock , this
 * function < b > may yield until the read lock is released < / b > .
 * < p > If the current thread already holds this lock then the
 * { @ code reentrantWriterCount } is incremented by one and the method returns
 * { @ code true } .
 * < p > If the write lock is held by another thread then the current
 * thread yields and lies dormant until one of two things happens :
 * < ul >
 * < li > The write lock is acquired by the current thread ; or
 * < li > The specified waiting time elapses
 * < / ul >
 * < p > If the write lock is acquired then the value { @ code true } is
 * returned and the write lock { @ code reentrantWriterCount } is set to one .
 * @ param nanosTimeout the time to wait for the write lock in nanoseconds
 * @ return { @ code true } if the lock was free and was acquired
 * by the current thread , or the write lock was already held by the
 * current thread ; and { @ code false } if the waiting time
 * elapsed before the lock could be acquired . */
public boolean exclusiveTryLockNanos ( long nanosTimeout ) throws InterruptedException { } }

implementation:
final long lastTime = System . nanoTime ( ) ; // Try to acquire the lock in write - mode
if ( stampedLock . tryWriteLock ( nanosTimeout , TimeUnit . NANOSECONDS ) == 0 ) { return false ; } // We can only do this after writerOwner has been set to the current thread
AtomicInteger [ ] localReadersStateArray = readersStateArrayRef . get ( ) ; if ( localReadersStateArray == null ) { // Set to dummyArray before scanning the readersStateList to impose
// a linearizability condition
readersStateArrayRef . set ( dummyArray ) ; // Copy readersStateList to an array
localReadersStateArray = readersStateList . toArray ( new AtomicInteger [ readersStateList . size ( ) ] ) ; readersStateArrayRef . compareAndSet ( dummyArray , localReadersStateArray ) ; } // Scan the array of Reader states
for ( AtomicInteger readerState : localReadersStateArray ) { while ( readerState != null && readerState . get ( ) == SRWL_STATE_READING ) { if ( System . nanoTime ( ) - lastTime < nanosTimeout ) { Thread . yield ( ) ; } else { // Time has expired and there is at least one ongoing Reader so give up
stampedLock . asWriteLock ( ) . unlock ( ) ; return false ; } } } return true ;


signature:
public class OSecurityShared { /** * Token MUST be validated before being passed to this method . */
public OUser authenticate ( final OToken authToken ) { } }

implementation:
final String dbName = getDatabase ( ) . getName ( ) ; if ( authToken . getIsValid ( ) != true ) { throw new OSecurityAccessException ( dbName , "Token not valid" ) ; } OUser user = authToken . getUser ( getDatabase ( ) ) ; if ( user == null && authToken . getUserName ( ) != null ) { // Token handler may not support returning an OUser so let ' s get username ( subject ) and query :
user = getUser ( authToken . getUserName ( ) ) ; } if ( user == null ) { throw new OSecurityAccessException ( dbName , "Authentication failed, could not load user from token" ) ; } if ( user . getAccountStatus ( ) != STATUSES . ACTIVE ) throw new OSecurityAccessException ( dbName , "User '" + user . getName ( ) + "' is not active" ) ; return user ;


signature:
public class OSecurityShared { /** * Repairs the security structure if broken by creating the ADMIN role and user with default password .
 * @ return */
public OUser createMetadata ( ) { } }

implementation:
final ODatabaseDocument database = getDatabase ( ) ; OClass identityClass = database . getMetadata ( ) . getSchema ( ) . getClass ( OIdentity . CLASS_NAME ) ; // SINCE 1.2.0
if ( identityClass == null ) identityClass = database . getMetadata ( ) . getSchema ( ) . createAbstractClass ( OIdentity . CLASS_NAME ) ; OClass roleClass = createOrUpdateORoleClass ( database , identityClass ) ; createOrUpdateOUserClass ( database , identityClass , roleClass ) ; // CREATE ROLES AND USERS
ORole adminRole = getRole ( ORole . ADMIN ) ; if ( adminRole == null ) { adminRole = createRole ( ORole . ADMIN , ORole . ALLOW_MODES . ALLOW_ALL_BUT ) ; adminRole . addRule ( ORule . ResourceGeneric . BYPASS_RESTRICTED , null , ORole . PERMISSION_ALL ) . save ( ) ; } OUser adminUser = getUser ( OUser . ADMIN ) ; if ( adminUser == null ) { // This will return the global value if a local storage context configuration value does not exist .
boolean createDefUsers = getDatabase ( ) . getStorage ( ) . getConfiguration ( ) . getContextConfiguration ( ) . getValueAsBoolean ( OGlobalConfiguration . CREATE_DEFAULT_USERS ) ; if ( createDefUsers ) { adminUser = createUser ( OUser . ADMIN , OUser . ADMIN , adminRole ) ; } } // SINCE 1.2.0
createOrUpdateORestrictedClass ( database ) ; return adminUser ;


signature:
public class OTraverse { /** * Executes a traverse collecting all the result in the returning List < OIdentifiable > . This could be memory expensive because for
 * large results the list could be huge . it ' s always better to use it as an Iterable and lazy fetch each result on next ( ) call .
 * @ see com . orientechnologies . orient . core . command . OCommand # execute ( ) */
public List < OIdentifiable > execute ( ) { } }

implementation: final List < OIdentifiable > result = new ArrayList < OIdentifiable > ( ) ; while ( hasNext ( ) ) result . add ( next ( ) ) ; return result ;


signature:
public class HeapDumper { /** * Invoke { @ code dumpHeap } operation on { @ code com . sun . management : type = HotSpotDiagnostic } mbean . */
public static void dumpHeap ( String fileName , boolean live ) { } }

implementation: try { MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; server . invoke ( new ObjectName ( HOTSPOT_BEAN_NAME ) , "dumpHeap" , new Object [ ] { fileName , live } , new String [ ] { String . class . getName ( ) , Boolean . TYPE . getName ( ) } ) ; } catch ( RuntimeException re ) { throw re ; } catch ( Exception exp ) { throw new RuntimeException ( exp ) ; }


signature:
public class OReadersWriterSpinLock { /** * Tries to acquire lock during provided interval of time and returns either if provided time interval was passed or
 * if lock was acquired .
 * @ param timeout Timeout during of which we should wait for read lock .
 * @ return < code > true < / code > if read lock was acquired . */
public boolean tryAcquireReadLock ( long timeout ) { } }

implementation:
final OModifiableInteger lHolds = lockHolds . get ( ) ; final int holds = lHolds . intValue ( ) ; if ( holds > 0 ) { // we have already acquire read lock
lHolds . increment ( ) ; return true ; } else if ( holds < 0 ) { // write lock is acquired before , do nothing
return true ; } distributedCounter . increment ( ) ; WNode wNode = tail . get ( ) ; final long start = System . nanoTime ( ) ; while ( wNode . locked ) { distributedCounter . decrement ( ) ; while ( wNode . locked && wNode == tail . get ( ) ) { wNode . waitingReaders . put ( Thread . currentThread ( ) , Boolean . TRUE ) ; if ( wNode . locked && wNode == tail . get ( ) ) { final long parkTimeout = timeout - ( System . nanoTime ( ) - start ) ; if ( parkTimeout > 0 ) { LockSupport . parkNanos ( this , parkTimeout ) ; } else { return false ; } } wNode = tail . get ( ) ; if ( System . nanoTime ( ) - start > timeout ) { return false ; } } distributedCounter . increment ( ) ; wNode = tail . get ( ) ; if ( System . nanoTime ( ) - start > timeout ) { distributedCounter . decrement ( ) ; return false ; } } lHolds . increment ( ) ; assert lHolds . intValue ( ) == 1 ; return true ;


signature:
public class OrientEdge { /** * ( Blueprints Extension ) Returns true if the edge is labeled with any of the passed strings .
 * @ param iEdgeLabel Label of current edge
 * @ param iLabels Labels as array of Strings
 * @ return true if the edge is labeled with any of the passed strings */
public static boolean isLabeled ( final String iEdgeLabel , final String [ ] iLabels ) { } }

implementation:
if ( iLabels != null && iLabels . length > 0 ) { // FILTER LABEL
if ( iEdgeLabel != null ) for ( String l : iLabels ) if ( l . equals ( iEdgeLabel ) ) // FOUND
return true ; // NOT FOUND
return false ; } // NO LABELS
return true ;


signature:
public class OrientEdge { /** * ( Blueprints Extension ) Returns the record label if any , otherwise NULL .
 * @ param iEdge Edge instance */
public static String getRecordLabel ( final OIdentifiable iEdge ) { } }

implementation: if ( iEdge == null ) return null ; final ODocument edge = iEdge . getRecord ( ) ; if ( edge == null ) return null ; return edge . field ( OrientElement . LABEL_FIELD_NAME ) ;


signature:
public class OrientEdge { /** * ( Blueprints Extension ) This method does not remove connection from opposite side .
 * @ param iVertex vertex that holds connection
 * @ param iFieldName name of field that holds connection
 * @ param iVertexToRemove target of connection */
private static void removeLightweightConnection ( final ODocument iVertex , final String iFieldName , final OIdentifiable iVertexToRemove ) { } }

implementation: if ( iVertex == null || iVertexToRemove == null ) return ; final Object fieldValue = iVertex . field ( iFieldName ) ; if ( fieldValue instanceof OIdentifiable ) { if ( fieldValue . equals ( iVertexToRemove ) ) { iVertex . removeField ( iFieldName ) ; } } else if ( fieldValue instanceof ORidBag ) { ( ( ORidBag ) fieldValue ) . remove ( iVertexToRemove ) ; }