signature:
public class OrientEdge { /** * Returns the connected incoming or outgoing vertex .
 * @ param direction Direction between IN or OUT */
@ Override public OrientVertex getVertex ( final Direction direction ) { } }

implementation: final OrientBaseGraph graph = setCurrentGraphInThreadLocal ( ) ; if ( direction . equals ( Direction . OUT ) ) return graph . getVertex ( getOutVertex ( ) ) ; else if ( direction . equals ( Direction . IN ) ) return graph . getVertex ( getInVertex ( ) ) ; else throw ExceptionFactory . bothIsNotSupported ( ) ;


signature:
public class OrientEdge { /** * ( Blueprints Extension ) Returns the outgoing vertex in form of record . */
public OIdentifiable getOutVertex ( ) { } }

implementation:
if ( vOut != null ) // LIGHTWEIGHT EDGE
return vOut ; setCurrentGraphInThreadLocal ( ) ; final ODocument doc = getRecord ( ) ; if ( doc == null ) return null ; if ( settings != null && settings . isKeepInMemoryReferences ( ) ) // AVOID LAZY RESOLVING + SETTING OF RECORD
return doc . rawField ( OrientBaseGraph . CONNECTION_OUT ) ; else return doc . field ( OrientBaseGraph . CONNECTION_OUT ) ;


signature:
public class OrientEdge { /** * ( Blueprints Extension ) Returns the incoming vertex in form of record . */
public OIdentifiable getInVertex ( ) { } }

implementation:
if ( vIn != null ) // LIGHTWEIGHT EDGE
return vIn ; setCurrentGraphInThreadLocal ( ) ; final ODocument doc = getRecord ( ) ; if ( doc == null ) return null ; if ( settings != null && settings . isKeepInMemoryReferences ( ) ) // AVOID LAZY RESOLVING + SETTING OF RECORD
return doc . rawField ( OrientBaseGraph . CONNECTION_IN ) ; else return doc . field ( OrientBaseGraph . CONNECTION_IN ) ;


signature:
public class OrientEdge { /** * Returns the Edge ' s label . By default OrientDB binds the Blueprints Label concept to Edge Class . To disable this feature execute
 * this at database level < code > alter database custom useClassForEdgeLabel = false
 * < / code > */
@ Override public String getLabel ( ) { } }

implementation:
if ( label != null ) // LIGHTWEIGHT EDGE
return label ; else if ( rawElement != null ) { if ( settings != null && settings . isUseClassForEdgeLabel ( ) ) { final String clsName = getRecord ( ) . getClassName ( ) ; if ( ! OrientEdgeType . CLASS_NAME . equals ( clsName ) ) // RETURN THE CLASS NAME
return OrientBaseGraph . decodeClassName ( clsName ) ; } setCurrentGraphInThreadLocal ( ) ; final ODocument doc = rawElement . getRecord ( ) ; if ( doc == null ) return null ; final String label = doc . field ( OrientElement . LABEL_FIELD_NAME ) ; if ( label != null ) return OrientBaseGraph . decodeClassName ( label ) ; } return null ;


signature:
public class OrientEdge { /** * Returns the Edge Id assuring to save it if it ' s transient yet . */
@ Override public Object getId ( ) { } }

implementation:
if ( rawElement == null ) // CREATE A TEMPORARY ID
return vOut . getIdentity ( ) + "->" + vIn . getIdentity ( ) ; setCurrentGraphInThreadLocal ( ) ; return super . getId ( ) ;


signature:
public class OrientEdge { /** * Returns a Property value .
 * @ param key Property name
 * @ return Property value if any , otherwise NULL . */
@ Override public < T > T getProperty ( final String key ) { } }

implementation:
setCurrentGraphInThreadLocal ( ) ; if ( rawElement == null ) // LIGHTWEIGHT EDGE
return null ; return super . getProperty ( key ) ;


signature:
public class OrientEdge { /** * Returns all the Property names as Set of String . out , in and label are not returned as properties even if are part of the
 * underlying document because are considered internal properties . */
@ Override public Set < String > getPropertyKeys ( ) { } }

implementation:
if ( rawElement == null ) // LIGHTWEIGHT EDGE
return Collections . emptySet ( ) ; setCurrentGraphInThreadLocal ( ) ; final Set < String > result = new HashSet < String > ( ) ; for ( String field : getRecord ( ) . fieldNames ( ) ) if ( ! field . equals ( OrientBaseGraph . CONNECTION_OUT ) && ! field . equals ( OrientBaseGraph . CONNECTION_IN ) && ( settings . isUseClassForEdgeLabel ( ) || ! field . equals ( OrientElement . LABEL_FIELD_NAME ) ) ) result . add ( field ) ; return result ;


signature:
public class OrientEdge { /** * Set a Property value . If the edge is lightweight , it ' s transparently transformed into a regular edge .
 * @ param key Property name
 * @ param value Property value */
@ Override public void setProperty ( final String key , final Object value ) { } }

implementation:
setCurrentGraphInThreadLocal ( ) ; if ( rawElement == null ) // LIGHTWEIGHT EDGE
convertToDocument ( ) ; super . setProperty ( key , value ) ;


signature:
public class OrientEdge { /** * Removed a Property .
 * @ param key Property name
 * @ return Old value if any */
@ Override public < T > T removeProperty ( String key ) { } }

implementation:
setCurrentGraphInThreadLocal ( ) ; if ( rawElement != null ) // NON LIGHTWEIGHT EDGE
return super . removeProperty ( key ) ; return null ;


signature:
public class OrientEdge { /** * Removes the Edge from the Graph . Connected vertices aren ' t removed . */
@ Override public void remove ( ) { } }

implementation:
final OrientBaseGraph graph = getGraph ( ) ; if ( ! isLightweight ( ) ) checkClass ( ) ; graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; for ( final Index < ? extends Element > index : graph . getIndices ( ) ) { if ( Edge . class . isAssignableFrom ( index . getIndexClass ( ) ) ) { OrientIndex < OrientEdge > idx = ( OrientIndex < OrientEdge > ) index ; idx . removeElement ( this ) ; } } if ( graph != null ) graph . removeEdgeInternal ( this ) ; else // IN MEMORY CHANGES ONLY : USE NOTX CLASS
OrientGraphNoTx . removeEdgeInternal ( null , this ) ;


signature:
public class OrientEdge { /** * ( Blueprints Extension ) Returns the underlying record if it ' s a regular edge , otherwise it created a document with no identity
 * with the edge properties . */
@ Override public ODocument getRecord ( ) { } }

implementation:
if ( rawElement == null ) { // CREATE AT THE FLY
final ODocument tmp = new ODocument ( getClassName ( label ) ) . setTrackingChanges ( false ) ; tmp . field ( OrientBaseGraph . CONNECTION_IN , vIn . getIdentity ( ) ) ; tmp . field ( OrientBaseGraph . CONNECTION_OUT , vOut . getIdentity ( ) ) ; if ( label != null && settings != null && ! settings . isUseClassForEdgeLabel ( ) ) tmp . field ( OrientEdge . LABEL_FIELD_NAME , label ) ; return tmp ; } return super . getRecord ( ) ;


signature:
public class OrientEdge { /** * ( Blueprints Extension ) Converts the lightweight edge to a regular edge creating the underlying document to store edge ' s
 * properties . */
public void convertToDocument ( ) { } }

implementation:
final OrientBaseGraph graph = checkIfAttached ( ) ; if ( rawElement != null ) // ALREADY CONVERTED
return ; graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; final ODocument vOutRecord = vOut . getRecord ( ) ; final ODocument vInRecord = vIn . getRecord ( ) ; final ODocument doc = createDocument ( label ) ; doc . field ( OrientBaseGraph . CONNECTION_OUT , settings . isKeepInMemoryReferences ( ) ? vOutRecord . getIdentity ( ) : vOutRecord ) ; doc . field ( OrientBaseGraph . CONNECTION_IN , settings . isKeepInMemoryReferences ( ) ? vInRecord . getIdentity ( ) : vInRecord ) ; rawElement = doc ; final boolean useVertexFieldsForEdgeLabels = settings . isUseVertexFieldsForEdgeLabels ( ) ; final String outFieldName = OrientVertex . getConnectionFieldName ( Direction . OUT , label , useVertexFieldsForEdgeLabels ) ; removeLightweightConnection ( vOutRecord , outFieldName , vInRecord ) ; // OUT - VERTEX - - - > IN - VERTEX / EDGE
OrientVertex . createLink ( graph , vOutRecord , doc , outFieldName ) ; vOutRecord . save ( ) ; final String inFieldName = OrientVertex . getConnectionFieldName ( Direction . IN , label , useVertexFieldsForEdgeLabels ) ; removeLightweightConnection ( vInRecord , inFieldName , vOutRecord ) ; // IN - VERTEX - - - > OUT - VERTEX / EDGE
OrientVertex . createLink ( graph , vInRecord , doc , inFieldName ) ; vInRecord . save ( ) ; vOut = null ; vIn = null ; label = null ;


signature:
public class OrientEdge { /** * ( Blueprints Extension ) Returns the class name based on graph settings . */
public String getClassName ( final String iLabel ) { } }

implementation:
if ( iLabel != null && ( settings == null || settings . isUseClassForEdgeLabel ( ) ) ) // USE THE LABEL AS DOCUMENT CLASS
return checkForClassInSchema ( iLabel ) ; return OrientEdgeType . CLASS_NAME ;


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

implementation: if ( attribute == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . DATABASE , ORole . PERMISSION_UPDATE ) ; database . setInternal ( attribute , value ) ; return null ;


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

implementation: final Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( object ) ; buffer . putLong ( calendar . getTimeInMillis ( ) ) ;


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

implementation: final Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeInMillis ( buffer . getLong ( ) ) ; return calendar . getTime ( ) ;


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

implementation: final Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeInMillis ( walChanges . getLongValue ( buffer , offset ) ) ; return calendar . getTime ( ) ;


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

implementation:
final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . SERVER , "remove" , ORole . PERMISSION_EXECUTE ) ; if ( ! ( database instanceof ODatabaseDocumentDistributed ) ) { throw new OCommandExecutionException ( "OrientDB is not started in distributed mode" ) ; } final OHazelcastPlugin dManager = ( OHazelcastPlugin ) ( ( ODatabaseDocumentDistributed ) database ) . getDistributedManager ( ) ; if ( dManager == null || ! dManager . isEnabled ( ) ) throw new OCommandExecutionException ( "OrientDB is not started in distributed mode" ) ; final String databaseName = database . getName ( ) ; // The last parameter ( true ) indicates to set the node ' s database status to OFFLINE .
// If this is changed to false , the node will be set to NOT _ AVAILABLE , and then the auto - repairer will
// re - synchronize the database on the node , and then set it to ONLINE .
return dManager . removeNodeFromConfiguration ( parsedStatement . serverName . getStringValue ( ) , databaseName , false , true ) ;


signature:
public class OSBTreeBonsaiLocal { /** * Removes all entries from bonsai tree . Put all but the root page to free list for further reuse . */
@ Override public void clear ( ) throws IOException { } }

implementation: boolean rollback = false ; final OAtomicOperation atomicOperation = startAtomicOperation ( true ) ; try { final Lock lock = FILE_LOCK_MANAGER . acquireExclusiveLock ( fileId ) ; try { final Queue < OBonsaiBucketPointer > subTreesToDelete = new LinkedList < > ( ) ; final OCacheEntry cacheEntry = loadPageForWrite ( atomicOperation , fileId , rootBucketPointer . getPageIndex ( ) , false , true ) ; try { OSBTreeBonsaiBucket < K , V > rootBucket = new OSBTreeBonsaiBucket < > ( cacheEntry , rootBucketPointer . getPageOffset ( ) , keySerializer , valueSerializer , this ) ; addChildrenToQueue ( subTreesToDelete , rootBucket ) ; rootBucket . shrink ( 0 ) ; rootBucket = new OSBTreeBonsaiBucket < > ( cacheEntry , rootBucketPointer . getPageOffset ( ) , true , keySerializer , valueSerializer , this ) ; rootBucket . setTreeSize ( 0 ) ; } finally { releasePageFromWrite ( atomicOperation , cacheEntry ) ; } recycleSubTrees ( subTreesToDelete , atomicOperation ) ; } finally { lock . unlock ( ) ; } } catch ( final Exception e ) { rollback = true ; throw e ; } finally { endAtomicOperation ( rollback ) ; }


signature:
public class OSBTreeBonsaiLocal { /** * Deletes a whole tree . Puts all its pages to free list for further reusage . */
@ Override public void delete ( ) throws IOException { } }

implementation: boolean rollback = false ; final OAtomicOperation atomicOperation = startAtomicOperation ( false ) ; try { final Lock lock = FILE_LOCK_MANAGER . acquireExclusiveLock ( fileId ) ; try { final Queue < OBonsaiBucketPointer > subTreesToDelete = new LinkedList < > ( ) ; subTreesToDelete . add ( rootBucketPointer ) ; recycleSubTrees ( subTreesToDelete , atomicOperation ) ; } finally { lock . unlock ( ) ; } } catch ( final Exception e ) { rollback = true ; throw e ; } finally { endAtomicOperation ( rollback ) ; }


signature:
public class OGraphBatchInsertBasic { /** * Creates the database ( if it does not exist ) and initializes batch operations . Call this once , before starting to create
 * vertices and edges . */
public void begin ( ) { } }

implementation: walActive = OGlobalConfiguration . USE_WAL . getValueAsBoolean ( ) ; if ( walActive ) OGlobalConfiguration . USE_WAL . setValue ( false ) ; if ( averageEdgeNumberPerNode > 0 ) { OGlobalConfiguration . RID_BAG_EMBEDDED_DEFAULT_SIZE . setValue ( averageEdgeNumberPerNode ) ; OGlobalConfiguration . RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD . setValue ( bonsaiThreshold ) ; } db = new ODatabaseDocumentTx ( dbUrl ) ; if ( db . exists ( ) ) { db . open ( userName , password ) ; } else { db . create ( ) ; } createBaseSchema ( ) ; out = estimatedEntries > 0 ? new HashMap < Long , List < Long > > ( estimatedEntries ) : new HashMap < Long , List < Long > > ( ) ; in = estimatedEntries > 0 ? new HashMap < Long , List < Long > > ( estimatedEntries ) : new HashMap < Long , List < Long > > ( ) ; OClass vClass = db . getMetadata ( ) . getSchema ( ) . getClass ( this . vertexClass ) ; int [ ] existingClusters = vClass . getClusterIds ( ) ; for ( int c = existingClusters . length ; c <= parallel ; c ++ ) { vClass . addCluster ( vClass . getName ( ) + "_" + c ) ; } clusterIds = vClass . getClusterIds ( ) ; lastClusterPositions = new long [ clusterIds . length ] ; for ( int i = 0 ; i < clusterIds . length ; i ++ ) { int clusterId = clusterIds [ i ] ; try { lastClusterPositions [ i ] = db . getStorage ( ) . getClusterById ( clusterId ) . getLastPosition ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }


signature:
public class OGraphBatchInsertBasic { /** * Flushes data to db and closes the db . Call this once , after vertices and edges creation . */
public void end ( ) { } }

implementation: final OClass vClass = db . getMetadata ( ) . getSchema ( ) . getClass ( vertexClass ) ; try { runningThreads = new AtomicInteger ( parallel ) ; for ( int i = 0 ; i < parallel - 1 ; i ++ ) { Thread t = new BatchImporterJob ( i , vClass ) ; t . start ( ) ; } Thread t = new BatchImporterJob ( parallel - 1 , vClass ) ; t . run ( ) ; if ( runningThreads . get ( ) > 0 ) { synchronized ( runningThreads ) { while ( runningThreads . get ( ) > 0 ) { try { runningThreads . wait ( ) ; } catch ( InterruptedException e ) { } } } } } finally { db . activateOnCurrentThread ( ) ; db . declareIntent ( null ) ; db . close ( ) ; if ( walActive ) OGlobalConfiguration . USE_WAL . setValue ( true ) ; }


signature:
public class OGraphBatchInsertBasic { /** * Creates a new vertex
 * @ param v
 * the vertex ID */
public void createVertex ( final Long v ) { } }

implementation: last = last < v ? v : last ; final List < Long > outList = out . get ( v ) ; if ( outList == null ) { out . put ( v , new ArrayList < Long > ( averageEdgeNumberPerNode <= 0 ? 4 : averageEdgeNumberPerNode ) ) ; }


signature:
public class OGraphBatchInsertBasic { /** * Creates a new edge between two vertices . If vertices do not exist , they will be created
 * @ param from
 * id of the vertex that is starting point of the edge
 * @ param to
 * id of the vertex that is end point of the edge */
public void createEdge ( final Long from , final Long to ) { } }

implementation: if ( from < 0 ) { throw new IllegalArgumentException ( " Invalid vertex id: " + from ) ; } if ( to < 0 ) { throw new IllegalArgumentException ( " Invalid vertex id: " + to ) ; } last = last < from ? from : last ; last = last < to ? to : last ; putInList ( from , out , to ) ; putInList ( to , in , from ) ;


signature:
public class OCommandExecutorSQLDeleteVertex { /** * Execute the command and return the ODocument object created . */
public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation:
if ( rid == null && query == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; if ( ! returning . equalsIgnoreCase ( "COUNT" ) ) allDeletedRecords = new ArrayList < ORecord > ( ) ; txAlreadyBegun = getDatabase ( ) . getTransaction ( ) . isActive ( ) ; ODatabaseDocumentInternal db = getDatabase ( ) ; if ( rid != null ) { // REMOVE PUNCTUAL RID
db . begin ( ) ; final OVertex v = toVertex ( rid ) ; if ( v != null ) { v . delete ( ) ; removed = 1 ; } db . commit ( ) ; } else if ( query != null ) { // TARGET IS A CLASS + OPTIONAL CONDITION
db . begin ( ) ; // TARGET IS A CLASS + OPTIONAL CONDITION
query . setContext ( getContext ( ) ) ; query . execute ( iArgs ) ; db . commit ( ) ; } else throw new OCommandExecutionException ( "Invalid target" ) ; if ( returning . equalsIgnoreCase ( "COUNT" ) ) // RETURNS ONLY THE COUNT
return removed ; else // RETURNS ALL THE DELETED RECORDS
return allDeletedRecords ;


signature:
public class OCommandExecutorSQLDeleteVertex { /** * Delete the current vertex . */
public boolean result ( final Object iRecord ) { } }

implementation: final OIdentifiable id = ( OIdentifiable ) iRecord ; if ( id . getIdentity ( ) . isValid ( ) ) { final ODocument record = id . getRecord ( ) ; ODatabaseDocumentInternal db = getDatabase ( ) ; final OVertex v = toVertex ( record ) ; if ( v != null ) { v . delete ( ) ; if ( ! txAlreadyBegun && batch > 0 && removed % batch == 0 ) { db . commit ( ) ; db . begin ( ) ; } if ( returning . equalsIgnoreCase ( "BEFORE" ) ) allDeletedRecords . add ( record ) ; removed ++ ; } } return true ;


signature:
public class OCommandExecutorSQLTraverse { /** * Compile the filter conditions only the first time . */
public OCommandExecutorSQLTraverse parse ( final OCommandRequest iRequest ) { } }

implementation:
final OCommandRequestText textRequest = ( OCommandRequestText ) iRequest ; String queryText = textRequest . getText ( ) ; String originalQuery = queryText ; try { // System . out . println ( " NEW PARSER FROM : " + queryText ) ;
queryText = preParse ( queryText , iRequest ) ; // System . out . println ( " NEW PARSER TO : " + queryText ) ;
textRequest . setText ( queryText ) ; super . parse ( iRequest ) ; final int pos = parseFields ( ) ; if ( pos == - 1 ) throw new OCommandSQLParsingException ( "Traverse must have the field list. Use " + getSyntax ( ) ) ; parserSetCurrentPosition ( pos ) ; int endPosition = parserText . length ( ) ; parsedTarget = OSQLEngine . getInstance ( ) . parseTarget ( parserText . substring ( pos , endPosition ) , getContext ( ) ) ; if ( parsedTarget . parserIsEnded ( ) ) parserSetCurrentPosition ( endPosition ) ; else parserMoveCurrentPosition ( parsedTarget . parserGetCurrentPosition ( ) ) ; if ( ! parserIsEnded ( ) ) { parserNextWord ( true ) ; if ( parserGetLastWord ( ) . equalsIgnoreCase ( KEYWORD_WHERE ) ) // / / TODO Remove the additional management of WHERE for TRAVERSE after a while
warnDeprecatedWhere ( ) ; if ( parserGetLastWord ( ) . equalsIgnoreCase ( KEYWORD_WHERE ) || parserGetLastWord ( ) . equalsIgnoreCase ( KEYWORD_WHILE ) ) { compiledFilter = OSQLEngine . getInstance ( ) . parseCondition ( parserText . substring ( parserGetCurrentPosition ( ) , endPosition ) , getContext ( ) , KEYWORD_WHILE ) ; traverse . predicate ( compiledFilter ) ; optimize ( ) ; parserSetCurrentPosition ( compiledFilter . parserIsEnded ( ) ? endPosition : compiledFilter . parserGetCurrentPosition ( ) + parserGetCurrentPosition ( ) ) ; } else parserGoBack ( ) ; } parserSkipWhiteSpaces ( ) ; while ( ! parserIsEnded ( ) ) { if ( parserOptionalKeyword ( KEYWORD_LIMIT , KEYWORD_SKIP , KEYWORD_OFFSET , KEYWORD_TIMEOUT , KEYWORD_MAXDEPTH , KEYWORD_STRATEGY ) ) { final String w = parserGetLastWord ( ) ; if ( w . equals ( KEYWORD_LIMIT ) ) parseLimit ( w ) ; else if ( w . equals ( KEYWORD_SKIP ) || w . equals ( KEYWORD_OFFSET ) ) parseSkip ( w ) ; else if ( w . equals ( KEYWORD_TIMEOUT ) ) parseTimeout ( w ) ; else if ( w . equals ( KEYWORD_MAXDEPTH ) ) parseMaxDepth ( w ) ; else if ( w . equals ( KEYWORD_STRATEGY ) ) parseStrategy ( w ) ; } } if ( limit == 0 || limit < - 1 ) throw new IllegalArgumentException ( "Limit must be > 0 or = -1 (no limit)" ) ; else traverse . limit ( limit ) ; traverse . getContext ( ) . setParent ( iRequest . getContext ( ) ) ; } finally { textRequest . setText ( originalQuery ) ; } return this ;


signature:
public class OCommandExecutorSQLTraverse { /** * Parses the strategy keyword if found . */
protected boolean parseStrategy ( final String w ) throws OCommandSQLParsingException { } }

implementation: if ( ! w . equals ( KEYWORD_STRATEGY ) ) return false ; final String strategyWord = parserNextWord ( true ) ; try { traverse . setStrategy ( OTraverse . STRATEGY . valueOf ( strategyWord . toUpperCase ( Locale . ENGLISH ) ) ) ; } catch ( IllegalArgumentException ignore ) { throwParsingException ( "Invalid " + KEYWORD_STRATEGY + ". Use one between " + Arrays . toString ( OTraverse . STRATEGY . values ( ) ) ) ; } return true ;


signature:
public class OBinaryTypeSerializer { /** * { @ inheritDoc } */
@ Override public void serializeInByteBufferObject ( byte [ ] object , ByteBuffer buffer , Object ... hints ) { } }

implementation: final int len = object . length ; buffer . putInt ( len ) ; buffer . put ( object ) ;


signature:
public class OBinaryTypeSerializer { /** * { @ inheritDoc } */
@ Override public byte [ ] deserializeFromByteBufferObject ( ByteBuffer buffer ) { } }

implementation: final int len = buffer . getInt ( ) ; final byte [ ] result = new byte [ len ] ; buffer . get ( result ) ; return result ;


signature:
public class OBinaryTypeSerializer { /** * { @ inheritDoc } */
@ Override public byte [ ] deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { } }

implementation: final int len = walChanges . getIntValue ( buffer , offset ) ; offset += OIntegerSerializer . INT_SIZE ; return walChanges . getBinaryValue ( buffer , offset , len ) ;


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

implementation: return walChanges . getIntValue ( buffer , offset ) + OIntegerSerializer . INT_SIZE ;


signature:
public class ORecordSerializerBinaryV0 { /** * returns begin position and length for each value in embedded collection */
private List < RecordInfo > getPositionsFromEmbeddedCollection ( final BytesContainer bytes , int serializerVersion ) { } }

implementation:
List < RecordInfo > retList = new ArrayList < > ( ) ; int numberOfElements = OVarIntSerializer . readAsInteger ( bytes ) ; // read collection type
readByte ( bytes ) ; for ( int i = 0 ; i < numberOfElements ; i ++ ) { // read element
// read data type
OType dataType = readOType ( bytes , false ) ; int fieldStart = bytes . offset ; RecordInfo fieldInfo = new RecordInfo ( ) ; fieldInfo . fieldStartOffset = fieldStart ; fieldInfo . fieldType = dataType ; // TODO find better way to skip data bytes ;
deserializeValue ( bytes , dataType , null , true , - 1 , serializerVersion , true ) ; fieldInfo . fieldLength = bytes . offset - fieldStart ; retList . add ( fieldInfo ) ; } return retList ;


signature:
public class OCommandExecutorSQLInsert { /** * Execute the INSERT and return the ODocument object created . */
public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation:
if ( newRecords == null && content == null && subQuery == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final OCommandParameters commandParameters = new OCommandParameters ( iArgs ) ; if ( indexName != null ) { if ( newRecords == null ) throw new OCommandExecutionException ( "No key/value found" ) ; final OIndex < ? > index = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . getIndex ( indexName ) ; if ( index == null ) throw new OCommandExecutionException ( "Target index '" + indexName + "' not found" ) ; // BIND VALUES
Map < String , Object > result = new HashMap < String , Object > ( ) ; for ( Map < String , Object > candidate : newRecords ) { Object indexKey = getIndexKeyValue ( commandParameters , candidate ) ; OIdentifiable indexValue = getIndexValue ( commandParameters , candidate ) ; if ( index instanceof OIndexMultiValues ) { final Collection < ORID > rids = ( ( OIndexMultiValues ) index ) . get ( indexKey ) ; if ( ! rids . contains ( indexValue . getIdentity ( ) ) ) { index . put ( indexKey , indexValue ) ; } } else { index . put ( indexKey , indexValue ) ; } result . put ( KEYWORD_KEY , indexKey ) ; result . put ( KEYWORD_RID , indexValue ) ; } // RETURN LAST ENTRY
return prepareReturnItem ( new ODocument ( result ) ) ; } else { // CREATE NEW DOCUMENTS
final List < ODocument > docs = new ArrayList < ODocument > ( ) ; if ( newRecords != null ) { for ( Map < String , Object > candidate : newRecords ) { final ODocument doc = className != null ? new ODocument ( className ) : new ODocument ( ) ; OSQLHelper . bindParameters ( doc , candidate , commandParameters , context ) ; saveRecord ( doc ) ; docs . add ( doc ) ; } if ( docs . size ( ) == 1 ) return prepareReturnItem ( docs . get ( 0 ) ) ; else return prepareReturnResult ( docs ) ; } else if ( content != null ) { final ODocument doc = className != null ? new ODocument ( className ) : new ODocument ( ) ; doc . merge ( content , true , false ) ; saveRecord ( doc ) ; return prepareReturnItem ( doc ) ; } else if ( subQuery != null ) { subQuery . execute ( ) ; if ( queryResult != null ) return prepareReturnResult ( queryResult ) ; return saved . longValue ( ) ; } } return null ;


signature:
public class ODatabaseRepair { /** * Checks if the link must be fixed .
 * @ param fieldValue
 * Field containing the OIdentifiable ( RID or Record )
 * @ return true to fix it , otherwise false */
protected boolean fixLink ( final Object fieldValue ) { } }

implementation: if ( fieldValue instanceof OIdentifiable ) { final ORID id = ( ( OIdentifiable ) fieldValue ) . getIdentity ( ) ; if ( id . getClusterId ( ) == 0 && id . getClusterPosition ( ) == 0 ) return true ; if ( id . isValid ( ) ) if ( id . isPersistent ( ) ) { final ORecord connected = ( ( OIdentifiable ) fieldValue ) . getRecord ( ) ; if ( connected == null ) return true ; } else return true ; } return false ;


signature:
public class OJPAPersistenceUnitInfo { /** * TODO : init default value In a Java EE environment , if this element is not specified , the default is JTA . In a Java SE
 * environment , if this element is not specified , a default of RESOURCE _ LOCAL may be assumed .
 * @ param elementContent
 * @ return */
public static PersistenceUnitTransactionType initTransactionType ( String elementContent ) { } }

implementation: if ( elementContent == null || elementContent . isEmpty ( ) ) { return null ; } try { return PersistenceUnitTransactionType . valueOf ( elementContent . toUpperCase ( Locale . ENGLISH ) ) ; } catch ( IllegalArgumentException ex ) { throw new PersistenceException ( "Unknown TransactionType: " + elementContent , ex ) ; }


signature:
public class OCommandExecutorSQLRebuildIndex { /** * Execute the REMOVE INDEX . */
public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation: if ( name == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseDocument database = getDatabase ( ) ; if ( name . equals ( "*" ) ) { long totalIndexed = 0 ; for ( OIndex < ? > idx : database . getMetadata ( ) . getIndexManager ( ) . getIndexes ( ) ) { if ( idx . isAutomatic ( ) ) totalIndexed += idx . rebuild ( ) ; } return totalIndexed ; } else { final OIndex < ? > idx = database . getMetadata ( ) . getIndexManager ( ) . getIndex ( name ) ; if ( idx == null ) throw new OCommandExecutionException ( "Index '" + name + "' not found" ) ; if ( ! idx . isAutomatic ( ) ) throw new OCommandExecutionException ( "Cannot rebuild index '" + name + "' because it's manual and there aren't indications of what to index" ) ; return idx . rebuild ( ) ; }


signature:
public class OSymmetricKeyCI { /** * The usual password field should be a JSON representation . */
public void intercept ( final String url , final String username , final String password ) throws OSecurityException { } }

implementation:
if ( username == null || username . isEmpty ( ) ) throw new OSecurityException ( "OSymmetricKeyCI username is not valid!" ) ; if ( password == null || password . isEmpty ( ) ) throw new OSecurityException ( "OSymmetricKeyCI password is not valid!" ) ; this . username = username ; // These are all used as defaults if the JSON document is missing any fields .
// Defaults to " AES " .
String algorithm = OGlobalConfiguration . CLIENT_CI_KEYALGORITHM . getValueAsString ( ) ; // Defaults to " AES / CBC / PKCS5Padding " .
String transform = OGlobalConfiguration . CLIENT_CI_CIPHERTRANSFORM . getValueAsString ( ) ; String keystoreFile = OGlobalConfiguration . CLIENT_CI_KEYSTORE_FILE . getValueAsString ( ) ; String keystorePassword = OGlobalConfiguration . CLIENT_CI_KEYSTORE_PASSWORD . getValueAsString ( ) ; ODocument jsonDoc = null ; try { jsonDoc = new ODocument ( ) . fromJSON ( password , "noMap" ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKeyCI.intercept() Exception: " + ex . getMessage ( ) ) , ex ) ; } // Override algorithm and transform , if they exist in the JSON document .
if ( jsonDoc . containsField ( "algorithm" ) ) algorithm = jsonDoc . field ( "algorithm" ) ; if ( jsonDoc . containsField ( "transform" ) ) transform = jsonDoc . field ( "transform" ) ; // Just in case the default configuration gets changed , check it .
if ( transform == null || transform . isEmpty ( ) ) throw new OSecurityException ( "OSymmetricKeyCI.intercept() cipher transformation is required" ) ; // If the algorithm is not set , either as a default in the global configuration or in the JSON document ,
// then determine the algorithm from the cipher transformation .
if ( algorithm == null ) algorithm = OSymmetricKey . separateAlgorithm ( transform ) ; OSymmetricKey key = null ; // " key " has priority over " keyFile " and " keyStore " .
if ( jsonDoc . containsField ( "key" ) ) { final String base64Key = jsonDoc . field ( "key" ) ; key = OSymmetricKey . fromString ( algorithm , base64Key ) ; key . setDefaultCipherTransform ( transform ) ; } else // " keyFile " has priority over " keyStore " .
if ( jsonDoc . containsField ( "keyFile" ) ) { key = OSymmetricKey . fromFile ( algorithm , ( String ) jsonDoc . field ( "keyFile" ) ) ; key . setDefaultCipherTransform ( transform ) ; } else if ( jsonDoc . containsField ( "keyStore" ) ) { ODocument ksDoc = jsonDoc . field ( "keyStore" ) ; if ( ksDoc . containsField ( "file" ) ) keystoreFile = ksDoc . field ( "file" ) ; if ( keystoreFile == null || keystoreFile . isEmpty ( ) ) throw new OSecurityException ( "OSymmetricKeyCI.intercept() keystore file is required" ) ; // Specific to Keystore , but override if present in the JSON document .
if ( ksDoc . containsField ( "password" ) ) keystorePassword = ksDoc . field ( "password" ) ; String keyAlias = ksDoc . field ( "keyAlias" ) ; if ( keyAlias == null || keyAlias . isEmpty ( ) ) throw new OSecurityException ( "OSymmetricKeyCI.intercept() keystore key alias is required" ) ; // keyPassword may be null .
String keyPassword = ksDoc . field ( "keyPassword" ) ; // keystorePassword may be null .
key = OSymmetricKey . fromKeystore ( keystoreFile , keystorePassword , keyAlias , keyPassword ) ; key . setDefaultCipherTransform ( transform ) ; } else { throw new OSecurityException ( "OSymmetricKeyCI.intercept() No suitable symmetric key property exists" ) ; } // This should never happen , but . . .
if ( key == null ) throw new OSecurityException ( "OSymmetricKeyCI.intercept() OSymmetricKey is null" ) ; encodedJSON = key . encrypt ( transform , username ) ;


signature:
public class ORecordInternal { /** * Internal only . Fills in one shot the record . */
public static ORecordAbstract fill ( final ORecord record , final ORID iRid , final int iVersion , final byte [ ] iBuffer , final boolean iDirty ) { } }

implementation: final ORecordAbstract rec = ( ORecordAbstract ) record ; rec . fill ( iRid , iVersion , iBuffer , iDirty ) ; return rec ;


signature:
public class ORecordInternal { /** * Internal only . Changes the identity of the record . */
public static ORecordAbstract setIdentity ( final ORecord record , final int iClusterId , final long iClusterPosition ) { } }

implementation: final ORecordAbstract rec = ( ORecordAbstract ) record ; rec . setIdentity ( iClusterId , iClusterPosition ) ; return rec ;


signature:
public class ORecordInternal { /** * Internal only . Changes the identity of the record . */
public static ORecordAbstract setIdentity ( final ORecord record , final ORecordId iIdentity ) { } }

implementation: final ORecordAbstract rec = ( ORecordAbstract ) record ; rec . setIdentity ( iIdentity ) ; return rec ;


signature:
public class ORecordInternal { /** * Internal only . Sets the version . */
public static void setVersion ( final ORecord record , final int iVersion ) { } }

implementation: final ORecordAbstract rec = ( ORecordAbstract ) record ; rec . setVersion ( iVersion ) ;


signature:
public class ORecordInternal { /** * Internal only . Return the record type . */
public static byte getRecordType ( final ORecord record ) { } }

implementation: if ( record instanceof ORecordAbstract ) { return ( ( ORecordAbstract ) record ) . getRecordType ( ) ; } final ORecordAbstract rec = ( ORecordAbstract ) record . getRecord ( ) ; return rec . getRecordType ( ) ;


signature:
public class ODistributedWorker { /** * Opens the database . */
public void initDatabaseInstance ( ) { } }

implementation:
if ( database == null ) { for ( int retry = 0 ; retry < 100 ; ++ retry ) { try { database = distributed . getDatabaseInstance ( ) ; // OK
break ; } catch ( OStorageException e ) { // WAIT FOR A WHILE , THEN RETRY
if ( ! dbNotAvailable ( retry ) ) return ; } catch ( OConfigurationException e ) { // WAIT FOR A WHILE , THEN RETRY
if ( ! dbNotAvailable ( retry ) ) return ; } } if ( database == null ) { ODistributedServerLog . info ( this , manager . getLocalNodeName ( ) , null , DIRECTION . NONE , "Database '%s' not present, shutting down database manager" , databaseName ) ; distributed . shutdown ( ) ; throw new ODistributedException ( "Cannot open database '" + databaseName + "'" ) ; } } else if ( database . isClosed ( ) ) { // DATABASE CLOSED , REOPEN IT
database . activateOnCurrentThread ( ) ; database . close ( ) ; database = distributed . getDatabaseInstance ( ) ; }


signature:
public class ODistributedWorker { /** * Executes the remote call on the local node and send back the result */
protected void onMessage ( final ODistributedRequest iRequest ) { } }

implementation:
String senderNodeName = null ; for ( int retry = 0 ; retry < 10 ; retry ++ ) { senderNodeName = manager . getNodeNameById ( iRequest . getId ( ) . getNodeId ( ) ) ; if ( senderNodeName != null ) break ; try { Thread . sleep ( 200 ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw OException . wrapException ( new ODistributedException ( "Execution has been interrupted" ) , e ) ; } } if ( senderNodeName == null ) { ODistributedServerLog . warn ( this , localNodeName , senderNodeName , DIRECTION . IN , "Sender server id %d is not registered in the cluster configuration, discard the request: (%s) (worker=%d)" , iRequest . getId ( ) . getNodeId ( ) , iRequest , id ) ; sendResponseBack ( iRequest , new ODistributedException ( "Sender server id " + iRequest . getId ( ) . getNodeId ( ) + " is not registered in the cluster configuration, discard the request" ) ) ; return ; } final ORemoteTask task = iRequest . getTask ( ) ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , localNodeName , senderNodeName , DIRECTION . IN , "Received request: (%s) (worker=%d)" , iRequest , id ) ; // EXECUTE IT LOCALLY
Object responsePayload = null ; OSecurityUser origin = null ; try { waitNodeIsOnline ( ) ; distributed . waitIsReady ( task ) ; // EXECUTE THE TASK
for ( int retry = 1 ; running ; ++ retry ) { if ( task . isUsingDatabase ( ) ) { initDatabaseInstance ( ) ; if ( database == null ) throw new ODistributedOperationException ( "Error on executing remote request because the database '" + databaseName + "' is not available" ) ; // keep original user in database , check the username passed in request and set new user in DB , after document saved ,
// reset to original user
if ( database != null ) { database . activateOnCurrentThread ( ) ; origin = database . getUser ( ) ; try { if ( iRequest . getUserRID ( ) != null && iRequest . getUserRID ( ) . isValid ( ) && ( lastUser == null || ! ( lastUser . getIdentity ( ) ) . equals ( iRequest . getUserRID ( ) ) ) ) { lastUser = database . getMetadata ( ) . getSecurity ( ) . getUser ( iRequest . getUserRID ( ) ) ; database . setUser ( lastUser ) ; // set to new user
} else origin = null ; } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , "Failed on user switching database. " , ex ) ; } } } responsePayload = manager . executeOnLocalNode ( iRequest . getId ( ) , iRequest . getTask ( ) , database ) ; if ( responsePayload instanceof OModificationOperationProhibitedException ) { // RETRY
try { ODistributedServerLog . info ( this , localNodeName , senderNodeName , DIRECTION . IN , "Database is frozen, waiting and retrying. Request %s (retry=%d, worker=%d)" , iRequest , retry , id ) ; Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { } } else { // OPERATION EXECUTED ( OK OR ERROR ) , NO RETRY NEEDED
if ( retry > 1 ) ODistributedServerLog . info ( this , localNodeName , senderNodeName , DIRECTION . IN , "Request %s succeed after retry=%d" , iRequest , retry ) ; break ; } } } catch ( RuntimeException e ) { if ( task . hasResponse ( ) ) sendResponseBack ( iRequest , e ) ; throw e ; } finally { if ( database != null && ! database . isClosed ( ) ) { database . activateOnCurrentThread ( ) ; if ( ! database . isClosed ( ) ) { database . rollback ( ) ; database . getLocalCache ( ) . clear ( ) ; if ( origin != null ) database . setUser ( origin ) ; } } } if ( task . hasResponse ( ) ) { if ( ! sendResponseBack ( iRequest , responsePayload ) ) { handleError ( iRequest , responsePayload ) ; } }


signature:
public class OETLContext { /** * Prints the error message for a caught exception according to a level passed as argument . It ' s composed of :
 * - defined error message
 * - exception message
 * @ param e
 * @ param message
 * @ param level
 * @ return printedMessage */
public String printExceptionMessage ( Exception e , String message , String level ) { } }

implementation: if ( e . getMessage ( ) != null ) message += "\n" + e . getClass ( ) . getName ( ) + " - " + e . getMessage ( ) ; else message += "\n" + e . getClass ( ) . getName ( ) ; switch ( level ) { case "debug" : this . messageHandler . debug ( this , message ) ; break ; case "info" : this . messageHandler . info ( this , message ) ; break ; case "warn" : this . messageHandler . warn ( this , message ) ; break ; case "error" : this . messageHandler . error ( this , message ) ; break ; } return message ;


signature:
public class OETLContext { /** * Builds the exception stack trace and prints it according to a level passed as argument .
 * @ param e
 * @ param level
 * @ return printedMessage */
public String printExceptionStackTrace ( Exception e , String level ) { } }

implementation:
// copying the exception stack trace in the string
Writer writer = new StringWriter ( ) ; e . printStackTrace ( new PrintWriter ( writer ) ) ; String s = writer . toString ( ) ; switch ( level ) { case "debug" : this . messageHandler . debug ( this , "\n" + s + "\n" ) ; break ; case "info" : this . messageHandler . info ( this , "\n" + s + "\n" ) ; break ; case "warn" : this . messageHandler . warn ( this , "\n" + s + "\n" ) ; break ; case "error" : this . messageHandler . error ( this , "\n" + s + "\n" ) ; break ; } return s ;


signature:
public class OQueryOperator { /** * Performs index query and returns index cursor which presents subset of index data which corresponds to result of execution of
 * given operator .
 * Query that should be executed can be presented like : [ [ property0 = keyParam0 ] and [ property1 = keyParam1 ] and ] propertyN
 * operator keyParamN .
 * It is supped that index which passed in as parameter is used to index properties listed above and responsibility of given
 * method execute query using given parameters .
 * Multiple parameters are passed in to implement composite indexes support .
 * @ param iContext
 * @ param index
 * Instance of index that will be used to calculate result of operator execution .
 * @ param keyParams
 * Parameters of query is used to calculate query result .
 * @ param ascSortOrder
 * Data returned by cursors should be sorted in ascending or descending order .
 * @ return Cursor instance if index can be used to evaluate result of execution of given operator and < code > null < / code > otherwise . */
public OIndexCursor executeIndexQuery ( OCommandContext iContext , OIndex < ? > index , final List < Object > keyParams , boolean ascSortOrder ) { } }

implementation: return null ;


signature:
public class ORecordLazyMap { /** * Convert the item with the received key to a record .
 * @ param iKey
 * Key of the item to convert */
private void convertLink2Record ( final Object iKey ) { } }

implementation:
if ( status == MULTIVALUE_CONTENT_TYPE . ALL_RECORDS ) return ; final Object value ; if ( iKey instanceof ORID ) value = iKey ; else value = super . get ( iKey ) ; if ( value != null && value instanceof ORID ) { final ORID rid = ( ORID ) value ; marshalling = true ; try { try { // OVERWRITE IT
ORecord record = rid . getRecord ( ) ; if ( record != null ) { ORecordInternal . unTrack ( sourceRecord , rid ) ; ORecordInternal . track ( sourceRecord , record ) ; } super . put ( iKey , record ) ; } catch ( ORecordNotFoundException ignore ) { // IGNORE THIS
} } finally { marshalling = false ; } }


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

implementation: buffer . put ( object . booleanValue ( ) ? ( byte ) 1 : ( byte ) 0 ) ;


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

implementation: return walChanges . getByteValue ( buffer , offset ) > 0 ;


signature:
public class OHttpNetworkCommandManager { /** * Register all the names for the same instance .
 * @ param iServerCommandInstance */
public void registerCommand ( final OServerCommand iServerCommandInstance ) { } }

implementation: for ( String name : iServerCommandInstance . getNames ( ) ) if ( OStringSerializerHelper . contains ( name , '{' ) ) { restCommands . put ( name , iServerCommandInstance ) ; } else if ( OStringSerializerHelper . contains ( name , '*' ) ) wildcardCommands . put ( name , iServerCommandInstance ) ; else exactCommands . put ( name , iServerCommandInstance ) ; iServerCommandInstance . configure ( server ) ;


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

implementation: super . config ( oServer , serverCfg , jsonConfig ) ; try { if ( jsonConfig . containsField ( "users" ) ) { List < ODocument > usersList = jsonConfig . field ( "users" ) ; for ( ODocument userDoc : usersList ) { OServerUserConfiguration userCfg = createServerUser ( userDoc ) ; if ( userCfg != null ) { String checkName = userCfg . name ; if ( ! isCaseSensitive ( ) ) checkName = checkName . toLowerCase ( Locale . ENGLISH ) ; usersMap . put ( checkName , userCfg ) ; } } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , "config()" , ex ) ; }


signature:
public class ODefaultPasswordAuthenticator { /** * Derived implementations can override this method to provide new server user implementations . */
protected OServerUserConfiguration createServerUser ( final ODocument userDoc ) { } }

implementation: OServerUserConfiguration userCfg = null ; if ( userDoc . containsField ( "username" ) && userDoc . containsField ( "resources" ) ) { final String user = userDoc . field ( "username" ) ; final String resources = userDoc . field ( "resources" ) ; String password = userDoc . field ( "password" ) ; if ( password == null ) password = "" ; userCfg = new OServerUserConfiguration ( user , password , resources ) ; } return userCfg ;


signature:
public class ODefaultPasswordAuthenticator { /** * Returns the actual username if successful , null otherwise . */
public String authenticate ( final String username , final String password ) { } }

implementation: String principal = null ; try { OServerUserConfiguration user = getUser ( username ) ; if ( isPasswordValid ( user ) ) { if ( OSecurityManager . instance ( ) . checkPassword ( password , user . password ) ) { principal = user . name ; } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , "ODefaultPasswordAuthenticator.authenticate()" , ex ) ; } return principal ;


signature:
public class ODefaultPasswordAuthenticator { /** * If not supported by the authenticator , return false . */
public boolean isAuthorized ( final String username , final String resource ) { } }

implementation:
if ( username == null || resource == null ) return false ; OServerUserConfiguration userCfg = getUser ( username ) ; if ( userCfg != null ) { // Total Access
if ( userCfg . resources . equals ( "*" ) ) return true ; String [ ] resourceParts = userCfg . resources . split ( "," ) ; for ( String r : resourceParts ) { if ( r . equalsIgnoreCase ( resource ) ) return true ; } } return false ;


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

implementation: OServerUserConfiguration userCfg = null ; synchronized ( usersMap ) { if ( username != null ) { String checkName = username ; if ( ! isCaseSensitive ( ) ) checkName = username . toLowerCase ( Locale . ENGLISH ) ; if ( usersMap . containsKey ( checkName ) ) { userCfg = usersMap . get ( checkName ) ; } } } return userCfg ;


signature:
public class OFilterAnalyzer { /** * Analyzes a query filter for a possible indexation options . The results are sorted by amount of fields . So the most specific
 * items go first .
 * @ param condition to analyze
 * @ param schemaClass the class that is scanned by query
 * @ param context of the query
 * @ return list of OIndexSearchResult items */
public List < OIndexSearchResult > analyzeCondition ( OSQLFilterCondition condition , final OClass schemaClass , OCommandContext context ) { } }

implementation: final List < OIndexSearchResult > indexSearchResults = new ArrayList < OIndexSearchResult > ( ) ; OIndexSearchResult lastCondition = analyzeFilterBranch ( schemaClass , condition , indexSearchResults , context ) ; if ( indexSearchResults . isEmpty ( ) && lastCondition != null ) { indexSearchResults . add ( lastCondition ) ; } Collections . sort ( indexSearchResults , new Comparator < OIndexSearchResult > ( ) { public int compare ( final OIndexSearchResult searchResultOne , final OIndexSearchResult searchResultTwo ) { return searchResultTwo . getFieldCount ( ) - searchResultOne . getFieldCount ( ) ; } } ) ; return indexSearchResults ;


signature:
public class OFilterAnalyzer { /** * Add SQL filter field to the search candidate list .
 * @ param iCondition Condition item
 * @ param iItem Value to search
 * @ return true if the property was indexed and found , otherwise false */
private OIndexSearchResult createIndexedProperty ( final OSQLFilterCondition iCondition , final Object iItem , OCommandContext ctx ) { } }

implementation: if ( iItem == null || ! ( iItem instanceof OSQLFilterItemField ) ) { return null ; } if ( iCondition . getLeft ( ) instanceof OSQLFilterItemField && iCondition . getRight ( ) instanceof OSQLFilterItemField ) { return null ; } final OSQLFilterItemField item = ( OSQLFilterItemField ) iItem ; if ( item . hasChainOperators ( ) && ! item . isFieldChain ( ) ) { return null ; } boolean inverted = iCondition . getRight ( ) == iItem ; final Object origValue = inverted ? iCondition . getLeft ( ) : iCondition . getRight ( ) ; OQueryOperator operator = iCondition . getOperator ( ) ; if ( inverted ) { if ( operator instanceof OQueryOperatorIn ) { operator = new OQueryOperatorContains ( ) ; } else if ( operator instanceof OQueryOperatorContains ) { operator = new OQueryOperatorIn ( ) ; } else if ( operator instanceof OQueryOperatorMajor ) { operator = new OQueryOperatorMinor ( ) ; } else if ( operator instanceof OQueryOperatorMinor ) { operator = new OQueryOperatorMajor ( ) ; } else if ( operator instanceof OQueryOperatorMajorEquals ) { operator = new OQueryOperatorMinorEquals ( ) ; } else if ( operator instanceof OQueryOperatorMinorEquals ) { operator = new OQueryOperatorMajorEquals ( ) ; } } if ( iCondition . getOperator ( ) instanceof OQueryOperatorBetween || operator instanceof OQueryOperatorIn ) { return new OIndexSearchResult ( operator , item . getFieldChain ( ) , origValue ) ; } final Object value = OSQLHelper . getValue ( origValue , null , ctx ) ; return new OIndexSearchResult ( operator , item . getFieldChain ( ) , value ) ;


signature:
public class OObjectProxyMethodHandler { /** * Method that detaches all fields contained in the document to the given object
 * @ param self : - The object containing this handler instance
 * @ throws InvocationTargetException
 * @ throws IllegalAccessException
 * @ throws NoSuchMethodException */
public void detach ( final Object self , final boolean nonProxiedInstance ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { } }

implementation: final Class < ? > selfClass = self . getClass ( ) ; for ( String fieldName : doc . fieldNames ( ) ) { Object value = getValue ( self , fieldName , false , null , true ) ; if ( value instanceof OObjectLazyMultivalueElement ) { ( ( OObjectLazyMultivalueElement < ? > ) value ) . detach ( nonProxiedInstance ) ; if ( nonProxiedInstance ) value = ( ( OObjectLazyMultivalueElement < ? > ) value ) . getNonOrientInstance ( ) ; } OObjectEntitySerializer . setFieldValue ( OObjectEntitySerializer . getField ( fieldName , selfClass ) , self , value ) ; } OObjectEntitySerializer . setIdField ( selfClass , self , doc . getIdentity ( ) ) ; OObjectEntitySerializer . setVersionField ( selfClass , self , doc . getVersion ( ) ) ;


signature:
public class OObjectProxyMethodHandler { /** * Method that detaches all fields contained in the document to the given object
 * @ param self : - The object containing this handler instance
 * @ throws InvocationTargetException
 * @ throws IllegalAccessException
 * @ throws NoSuchMethodException */
public void detachAll ( final Object self , final boolean nonProxiedInstance , final Map < Object , Object > alreadyDetached , final Map < Object , Object > lazyObjects ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { } }

implementation:
final Class < ? > selfClass = self . getClass ( ) ; for ( String fieldName : doc . fieldNames ( ) ) { final Field field = OObjectEntitySerializer . getField ( fieldName , selfClass ) ; if ( field != null ) { Object value = getValue ( self , fieldName , false , null , true ) ; if ( value instanceof OObjectLazyMultivalueElement ) { ( ( OObjectLazyMultivalueElement < ? > ) value ) . detachAll ( nonProxiedInstance , alreadyDetached , lazyObjects ) ; if ( nonProxiedInstance ) value = ( ( OObjectLazyMultivalueElement < ? > ) value ) . getNonOrientInstance ( ) ; } else if ( value instanceof Proxy ) { OObjectProxyMethodHandler handler = ( OObjectProxyMethodHandler ) ( ( ProxyObject ) value ) . getHandler ( ) ; if ( nonProxiedInstance ) { value = OObjectEntitySerializer . getNonProxiedInstance ( value ) ; } if ( OObjectEntitySerializer . isFetchLazyField ( self . getClass ( ) , fieldName ) ) { // just make a placeholder with only the id , so it can be fetched later ( but not by orient
// internally )
// do not use the already detached map for this , that might mix up lazy and non - lazy objects
Object lazyValue = lazyObjects . get ( handler . doc . getIdentity ( ) ) ; if ( lazyValue != null ) { value = lazyValue ; } else { OObjectEntitySerializer . setIdField ( field . getType ( ) , value , handler . doc . getIdentity ( ) ) ; lazyObjects . put ( handler . doc . getIdentity ( ) , value ) ; } } else { Object detachedValue = alreadyDetached . get ( handler . doc . getIdentity ( ) ) ; if ( detachedValue != null ) { value = detachedValue ; } else { ORID identity = handler . doc . getIdentity ( ) ; if ( identity . isValid ( ) ) alreadyDetached . put ( identity , value ) ; handler . detachAll ( value , nonProxiedInstance , alreadyDetached , lazyObjects ) ; } } } else if ( value instanceof OTrackedMap && nonProxiedInstance ) { Map newValue = new LinkedHashMap < > ( ) ; newValue . putAll ( ( Map ) value ) ; value = newValue ; } else if ( value instanceof OTrackedList && nonProxiedInstance ) { List newValue = new ArrayList ( ) ; newValue . addAll ( ( Collection ) value ) ; value = newValue ; } else if ( value instanceof OTrackedSet && nonProxiedInstance ) { Set newValue = new LinkedHashSet ( ) ; newValue . addAll ( ( Collection ) value ) ; value = newValue ; } OObjectEntitySerializer . setFieldValue ( field , self , value ) ; } } OObjectEntitySerializer . setIdField ( selfClass , self , doc . getIdentity ( ) ) ; OObjectEntitySerializer . setVersionField ( selfClass , self , doc . getVersion ( ) ) ;


signature:
public class OObjectProxyMethodHandler { /** * Method that attaches all data contained in the object to the associated document
 * @ param self : - The object containing this handler instance
 * @ throws IllegalAccessException
 * @ throws IllegalArgumentException
 * @ throws InvocationTargetException
 * @ throws NoSuchMethodException */
public void attach ( final Object self ) throws IllegalArgumentException , IllegalAccessException , NoSuchMethodException , InvocationTargetException { } }

implementation:
for ( Class < ? > currentClass = self . getClass ( ) ; currentClass != Object . class ; ) { if ( Proxy . class . isAssignableFrom ( currentClass ) ) { currentClass = currentClass . getSuperclass ( ) ; continue ; } for ( Field f : currentClass . getDeclaredFields ( ) ) { final String fieldName = f . getName ( ) ; final Class < ? > declaringClass = f . getDeclaringClass ( ) ; if ( OObjectEntitySerializer . isTransientField ( declaringClass , fieldName ) || OObjectEntitySerializer . isVersionField ( declaringClass , fieldName ) || OObjectEntitySerializer . isIdField ( declaringClass , fieldName ) ) continue ; Object value = OObjectEntitySerializer . getFieldValue ( f , self ) ; value = setValue ( self , fieldName , value ) ; OObjectEntitySerializer . setFieldValue ( f , self , value ) ; } currentClass = currentClass . getSuperclass ( ) ; if ( currentClass == null || currentClass . equals ( ODocument . class ) ) // POJO EXTENDS ODOCUMENT : SPECIAL CASE : AVOID TO CONSIDER
// ODOCUMENT FIELDS
currentClass = Object . class ; }


signature:
public class OCreateIndexStatement { /** * returns the list of property names to be indexed
 * @ param ctx
 * @ return */
private String [ ] calculateProperties ( OCommandContext ctx ) { } }

implementation: if ( propertyList == null ) { return null ; } return propertyList . stream ( ) . map ( x -> x . getCompleteKey ( ) ) . collect ( Collectors . toList ( ) ) . toArray ( new String [ ] { } ) ;


signature:
public class OCreateIndexStatement { /** * calculates the indexed class based on the class name */
private OClass getIndexClass ( OCommandContext ctx ) { } }

implementation: if ( className == null ) { return null ; } OClass result = ctx . getDatabase ( ) . getMetadata ( ) . getSchema ( ) . getClass ( className . getStringValue ( ) ) ; if ( result == null ) { throw new OCommandExecutionException ( "Cannot find class " + className ) ; } return result ;


signature:
public class OCreateIndexStatement { /** * returns index metadata as an ODocuemnt ( as expected by Index API ) */
private ODocument calculateMetadata ( OCommandContext ctx ) { } }

implementation: if ( metadata == null ) { return null ; } return metadata . toDocument ( null , ctx ) ;


signature:
public class OSequenceCached { /** * first set new current value then call next */
protected long nextWithNewCurrentValue ( long currentValue , boolean executeViaDistributed ) throws OSequenceLimitReachedException , ODatabaseException { } }

implementation:
if ( ! executeViaDistributed ) { // we don ' t want synchronization on whole method , because called with executeViaDistributed = = true
// will later call nextWithNewCurrentValue with parameter executeViaDistributed = = false
// and that will cause deadlock
synchronized ( this ) { cacheStart = currentValue ; return nextWork ( ) ; } } else { try { return sendSequenceActionSetAndNext ( currentValue ) ; } catch ( InterruptedException | ExecutionException exc ) { OLogManager . instance ( ) . error ( this , exc . getMessage ( ) , exc , ( Object [ ] ) null ) ; throw new ODatabaseException ( exc . getMessage ( ) ) ; } }


signature:
public class OTransactionIndexChangesPerKey { /** * Interprets this key changes using the given { @ link Interpretation interpretation } .
 * @ param interpretation the interpretation to use .
 * @ return the interpreted changes . */
public Iterable < OTransactionIndexEntry > interpret ( Interpretation interpretation ) { } }

implementation: synchronized ( this ) { switch ( interpretation ) { case Unique : return interpretAsUnique ( ) ; case Dictionary : return interpretAsDictionary ( ) ; case NonUnique : return interpretAsNonUnique ( ) ; default : throw new IllegalStateException ( "Unexpected interpretation '" + interpretation + "'" ) ; } }


signature:
public class OCommandExecutorSQLDeleteEdge { /** * Execute the command and return the ODocument object created . */
public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation:
if ( fromExpr == null && toExpr == null && rids == null && query == null && compiledFilter == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; ODatabaseDocumentInternal db = getDatabase ( ) ; txAlreadyBegun = db . getTransaction ( ) . isActive ( ) ; if ( rids != null ) { // REMOVE PUNCTUAL RID
db . begin ( ) ; for ( ORecordId rid : rids ) { final OEdge e = toEdge ( rid ) ; if ( e != null ) { e . delete ( ) ; removed ++ ; } } db . commit ( ) ; return removed ; } else { // MULTIPLE EDGES
final Set < OEdge > edges = new HashSet < OEdge > ( ) ; if ( query == null ) { db . begin ( ) ; Set < OIdentifiable > fromIds = null ; if ( fromExpr != null ) fromIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , fromExpr , context , iArgs ) ; Set < OIdentifiable > toIds = null ; if ( toExpr != null ) toIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , toExpr , context , iArgs ) ; if ( label == null ) label = "E" ; if ( fromIds != null && toIds != null ) { int fromCount = 0 ; int toCount = 0 ; for ( OIdentifiable fromId : fromIds ) { final OVertex v = toVertex ( fromId ) ; if ( v != null ) fromCount += count ( v . getEdges ( ODirection . OUT , label ) ) ; } for ( OIdentifiable toId : toIds ) { final OVertex v = toVertex ( toId ) ; if ( v != null ) toCount += count ( v . getEdges ( ODirection . IN , label ) ) ; } if ( fromCount <= toCount ) { // REMOVE ALL THE EDGES BETWEEN VERTICES
for ( OIdentifiable fromId : fromIds ) { final OVertex v = toVertex ( fromId ) ; if ( v != null ) for ( OEdge e : v . getEdges ( ODirection . OUT , label ) ) { final OIdentifiable inV = ( ( OEdge ) e ) . getTo ( ) ; if ( inV != null && toIds . contains ( inV . getIdentity ( ) ) ) edges . add ( e ) ; } } } else { for ( OIdentifiable toId : toIds ) { final OVertex v = toVertex ( toId ) ; if ( v != null ) for ( OEdge e : v . getEdges ( ODirection . IN , label ) ) { final OIdentifiable outV = ( ( OEdge ) e ) . getFrom ( ) ; if ( outV != null && fromIds . contains ( outV . getIdentity ( ) ) ) edges . add ( e ) ; } } } } else if ( fromIds != null ) { // REMOVE ALL THE EDGES THAT START FROM A VERTEXES
for ( OIdentifiable fromId : fromIds ) { final OVertex v = toVertex ( fromId ) ; if ( v != null ) { for ( OEdge e : v . getEdges ( ODirection . OUT , label ) ) { edges . add ( e ) ; } } } } else if ( toIds != null ) { // REMOVE ALL THE EDGES THAT ARRIVE TO A VERTEXES
for ( OIdentifiable toId : toIds ) { final OVertex v = toVertex ( toId ) ; if ( v != null ) { for ( OEdge e : v . getEdges ( ODirection . IN , label ) ) { edges . add ( e ) ; } } } } else throw new OCommandExecutionException ( "Invalid target: " + toIds ) ; if ( compiledFilter != null ) { // ADDITIONAL FILTERING
for ( Iterator < OEdge > it = edges . iterator ( ) ; it . hasNext ( ) ; ) { final OEdge edge = it . next ( ) ; if ( ! ( Boolean ) compiledFilter . evaluate ( edge . getRecord ( ) , null , context ) ) it . remove ( ) ; } } // DELETE THE FOUND EDGES
removed = edges . size ( ) ; for ( OEdge edge : edges ) edge . delete ( ) ; db . commit ( ) ; return removed ; } else { db . begin ( ) ; // TARGET IS A CLASS + OPTIONAL CONDITION
query . setContext ( getContext ( ) ) ; query . execute ( iArgs ) ; db . commit ( ) ; return removed ; } }


signature:
public class OCommandExecutorSQLDeleteEdge { /** * Delete the current edge . */
public boolean result ( final Object iRecord ) { } }

implementation:
final OIdentifiable id = ( OIdentifiable ) iRecord ; if ( compiledFilter != null ) { // ADDITIONAL FILTERING
if ( ! ( Boolean ) compiledFilter . evaluate ( id . getRecord ( ) , null , context ) ) return true ; } if ( id . getIdentity ( ) . isValid ( ) ) { final OEdge e = toEdge ( id ) ; if ( e != null ) { e . delete ( ) ; if ( ! txAlreadyBegun && batch > 0 && ( removed + 1 ) % batch == 0 ) { getDatabase ( ) . commit ( ) ; getDatabase ( ) . begin ( ) ; } removed ++ ; } } return true ;


signature:
public class OClassImpl { /** * Truncates all the clusters the class uses . */
public void truncate ( ) throws IOException { } }

implementation: ODatabaseDocumentInternal db = getDatabase ( ) ; db . checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_UPDATE ) ; if ( isSubClassOf ( OSecurityShared . RESTRICTED_CLASSNAME ) ) { throw new OSecurityException ( "Class '" + getName ( ) + "' cannot be truncated because has record level security enabled (extends '" + OSecurityShared . RESTRICTED_CLASSNAME + "')" ) ; } final OStorage storage = db . getStorage ( ) ; acquireSchemaReadLock ( ) ; try { for ( int id : clusterIds ) { OCluster cl = storage . getClusterById ( id ) ; db . checkForClusterPermissions ( cl . getName ( ) ) ; cl . truncate ( ) ; } for ( OIndex < ? > index : getClassIndexes ( ) ) index . clear ( ) ; Set < OIndex < ? > > superclassIndexes = new HashSet < OIndex < ? > > ( ) ; superclassIndexes . addAll ( getIndexes ( ) ) ; superclassIndexes . removeAll ( getClassIndexes ( ) ) ; for ( OIndex index : superclassIndexes ) { index . rebuild ( ) ; } } finally { releaseSchemaReadLock ( ) ; }


signature:
public class OClassImpl { /** * Check if the current instance extends specified schema class .
 * @ param iClassName of class that should be checked
 * @ return Returns true if the current instance extends the passed schema class ( iClass )
 * @ see # isSuperClassOf ( OClass ) */
public boolean isSubClassOf ( final String iClassName ) { } }

implementation: acquireSchemaReadLock ( ) ; try { if ( iClassName == null ) return false ; if ( iClassName . equalsIgnoreCase ( getName ( ) ) || iClassName . equalsIgnoreCase ( getShortName ( ) ) ) return true ; for ( OClassImpl superClass : superClasses ) { if ( superClass . isSubClassOf ( iClassName ) ) return true ; } return false ; } finally { releaseSchemaReadLock ( ) ; }


signature:
public class OClassImpl { /** * Check if the current instance extends specified schema class .
 * @ param clazz to check
 * @ return true if the current instance extends the passed schema class ( iClass )
 * @ see # isSuperClassOf ( OClass ) */
public boolean isSubClassOf ( final OClass clazz ) { } }

implementation: acquireSchemaReadLock ( ) ; try { if ( clazz == null ) return false ; if ( equals ( clazz ) ) return true ; for ( OClassImpl superClass : superClasses ) { if ( superClass . isSubClassOf ( clazz ) ) return true ; } return false ; } finally { releaseSchemaReadLock ( ) ; }


signature:
public class OClassImpl { /** * Adds a base class to the current one . It adds also the base class cluster ids to the polymorphic cluster ids array .
 * @ param iBaseClass The base class to add . */
protected OClass addBaseClass ( final OClassImpl iBaseClass ) { } }

implementation: checkRecursion ( iBaseClass ) ; if ( subclasses == null ) subclasses = new ArrayList < OClass > ( ) ; if ( subclasses . contains ( iBaseClass ) ) return this ; subclasses . add ( iBaseClass ) ; addPolymorphicClusterIdsWithInheritance ( iBaseClass ) ; return this ;


signature:
public class OClassImpl { /** * Add different cluster id to the " polymorphic cluster ids " array . */
protected void addPolymorphicClusterIds ( final OClassImpl iBaseClass ) { } }

implementation: Set < Integer > clusters = new TreeSet < Integer > ( ) ; for ( int clusterId : polymorphicClusterIds ) { clusters . add ( clusterId ) ; } for ( int clusterId : iBaseClass . polymorphicClusterIds ) { if ( clusters . add ( clusterId ) ) { try { addClusterIdToIndexes ( clusterId ) ; } catch ( RuntimeException e ) { OLogManager . instance ( ) . warn ( this , "Error adding clusterId '%d' to index of class '%s'" , e , clusterId , getName ( ) ) ; clusters . remove ( clusterId ) ; } } } polymorphicClusterIds = new int [ clusters . size ( ) ] ; int i = 0 ; for ( Integer cluster : clusters ) { polymorphicClusterIds [ i ] = cluster ; i ++ ; }


signature:
public class OLuceneSpatialOperator { /** * TODO HANDLE EVALUATE RECORD */
@ Override public Object evaluateRecord ( OIdentifiable iRecord , ODocument iCurrentResult , OSQLFilterCondition iCondition , Object iLeft , Object iRight , OCommandContext iContext , final ODocumentSerializer serializer ) { } }

implementation: OSQLFunction function = OSQLEngine . getInstance ( ) . getFunction ( keyword ) ; return function . execute ( this , iRecord , iCurrentResult , new Object [ ] { iLeft , iCondition . getRight ( ) } , iContext ) ;


signature:
public class ORecordSerializerCSVAbstract { /** * Serialize the link .
 * @ param buffer
 * @ param iParentRecord
 * @ param iLinked Can be an instance of ORID or a Record < ? >
 * @ return */
private static OIdentifiable linkToStream ( final StringBuilder buffer , final ODocument iParentRecord , Object iLinked ) { } }

implementation:
if ( iLinked == null ) // NULL REFERENCE
return null ; OIdentifiable resultRid = null ; ORID rid ; if ( iLinked instanceof ORID ) { // JUST THE REFERENCE
rid = ( ORID ) iLinked ; assert rid . getIdentity ( ) . isValid ( ) || ( ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getStorage ( ) instanceof OStorageProxy ) : "Impossible to serialize invalid link " + rid . getIdentity ( ) ; resultRid = rid ; } else { if ( iLinked instanceof String ) iLinked = new ORecordId ( ( String ) iLinked ) ; if ( ! ( iLinked instanceof OIdentifiable ) ) throw new IllegalArgumentException ( "Invalid object received. Expected a OIdentifiable but received type=" + iLinked . getClass ( ) . getName ( ) + " and value=" + iLinked ) ; // RECORD
ORecord iLinkedRecord = ( ( OIdentifiable ) iLinked ) . getRecord ( ) ; rid = iLinkedRecord . getIdentity ( ) ; assert rid . getIdentity ( ) . isValid ( ) || ( ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getStorage ( ) instanceof OStorageProxy ) : "Impossible to serialize invalid link " + rid . getIdentity ( ) ; final ODatabaseDocument database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; if ( iParentRecord != null ) { if ( ! database . isRetainRecords ( ) ) // REPLACE CURRENT RECORD WITH ITS ID : THIS SAVES A LOT OF MEMORY
resultRid = iLinkedRecord . getIdentity ( ) ; } } if ( rid . isValid ( ) ) rid . toString ( buffer ) ; return resultRid ;


signature:
public class OLuceneIndexEngineUtils { /** * Builds a { @ link SortField } from a configuration map . The map can contains up to three fields : field ( name ) , reverse
 * ( true / false ) and type { @ link SortField . Type } .
 * @ param conf
 * @ return */
public static SortField buildSortField ( Map < String , Object > conf ) { } }

implementation: final String field = Optional . ofNullable ( ( String ) conf . get ( "field" ) ) . orElse ( null ) ; final String type = Optional . ofNullable ( ( ( String ) conf . get ( "type" ) ) . toUpperCase ( ) ) . orElse ( SortField . Type . STRING . name ( ) ) ; final Boolean reverse = Optional . ofNullable ( ( Boolean ) conf . get ( "reverse" ) ) . orElse ( false ) ; SortField sortField = new SortField ( field , SortField . Type . valueOf ( type ) , reverse ) ; return sortField ;


signature:
public class ORecordBytes { /** * Reads the input stream in memory . This is less efficient than { @ link # fromInputStream ( InputStream , int ) } because allocation is
 * made multiple times . If you already know the input size use { @ link # fromInputStream ( InputStream , int ) } .
 * @ param in
 * Input Stream , use buffered input stream wrapper to speed up reading
 * @ return Buffer read from the stream . It ' s also the internal buffer size in bytes
 * @ throws IOException */
public int fromInputStream ( final InputStream in ) throws IOException { } }

implementation: final OMemoryStream out = new OMemoryStream ( ) ; try { final byte [ ] buffer = new byte [ OMemoryStream . DEF_SIZE ] ; int readBytesCount ; while ( true ) { readBytesCount = in . read ( buffer , 0 , buffer . length ) ; if ( readBytesCount == - 1 ) { break ; } out . write ( buffer , 0 , readBytesCount ) ; } out . flush ( ) ; _source = out . toByteArray ( ) ; } finally { out . close ( ) ; } _size = _source . length ; return _size ;


signature:
public class ORecordBytes { /** * Reads the input stream in memory specifying the maximum bytes to read . This is more efficient than
 * { @ link # fromInputStream ( InputStream ) } because allocation is made only once .
 * @ param in
 * Input Stream , use buffered input stream wrapper to speed up reading
 * @ param maxSize
 * Maximum size to read
 * @ return Buffer count of bytes that are read from the stream . It ' s also the internal buffer size in bytes
 * @ throws IOException
 * if an I / O error occurs . */
public int fromInputStream ( final InputStream in , final int maxSize ) throws IOException { } }

implementation: final byte [ ] buffer = new byte [ maxSize ] ; int totalBytesCount = 0 ; int readBytesCount ; while ( totalBytesCount < maxSize ) { readBytesCount = in . read ( buffer , totalBytesCount , buffer . length - totalBytesCount ) ; if ( readBytesCount == - 1 ) { break ; } totalBytesCount += readBytesCount ; } if ( totalBytesCount == 0 ) { _source = EMPTY_SOURCE ; _size = 0 ; } else if ( totalBytesCount == maxSize ) { _source = buffer ; _size = maxSize ; } else { _source = Arrays . copyOf ( buffer , totalBytesCount ) ; _size = totalBytesCount ; } return _size ;


signature:
public class OByteBufferPool { /** * Acquires direct memory buffer with native byte order .
 * If there is free ( already released ) direct memory page we reuse it , otherwise new
 * memory chunk is allocated from direct memory .
 * @ param clear Whether returned buffer should be filled with zeros before return .
 * @ return Direct memory buffer instance . */
public final OPointer acquireDirect ( boolean clear ) { } }

implementation: OPointer pointer ; pointer = pointersPool . poll ( ) ; if ( pointer != null ) { pointersPoolSize . decrementAndGet ( ) ; } else { pointer = allocator . allocate ( pageSize , - 1 ) ; } if ( clear ) { pointer . clear ( ) ; } final ByteBuffer buffer = pointer . getNativeByteBuffer ( ) ; buffer . position ( 0 ) ; if ( TRACK ) { pointerMapping . put ( pointer , generatePointer ( ) ) ; } return pointer ;


signature:
public class OByteBufferPool { /** * Put buffer which is not used any more back to the pool or frees direct memory if pool is full .
 * @ param pointer Not used instance of buffer .
 * @ see OGlobalConfiguration # DIRECT _ MEMORY _ POOL _ LIMIT */
public final void release ( OPointer pointer ) { } }

implementation: if ( TRACK ) { pointerMapping . remove ( pointer ) ; } long poolSize = pointersPoolSize . incrementAndGet ( ) ; if ( poolSize > this . poolSize ) { pointersPoolSize . decrementAndGet ( ) ; allocator . deallocate ( pointer ) ; } else { pointersPool . add ( pointer ) ; }


signature:
public class OByteBufferPool { /** * Checks whether there are not released buffers in the pool */
public void checkMemoryLeaks ( ) { } }

implementation: boolean detected = false ; if ( TRACK ) { for ( Map . Entry < OPointer , PointerTracker > entry : pointerMapping . entrySet ( ) ) { OLogManager . instance ( ) . errorNoDb ( this , "DIRECT-TRACK: unreleased direct memory pointer `%X` detected." , entry . getValue ( ) . allocation , System . identityHashCode ( entry . getKey ( ) ) ) ; detected = true ; } } assert ! detected ;


signature:
public class OByteBufferPool { /** * Clears pool and dealocates memory . */
public void clear ( ) { } }

implementation: for ( OPointer pointer : pointersPool ) { allocator . deallocate ( pointer ) ; } pointersPool . clear ( ) ; pointersPoolSize . set ( 0 ) ; for ( OPointer pointer : pointerMapping . keySet ( ) ) { allocator . deallocate ( pointer ) ; } pointerMapping . clear ( ) ;


signature:
public class OBinaryProtocol { /** * Convert the byte array to an int starting from the given offset .
 * @ param b The byte array
 * @ param offset The array offset
 * @ return The integer */
public static int bytes2int ( final byte [ ] b , final int offset ) { } }


signature:
public class PersistenceXmlUtil { /** * Parse the persistence . xml files referenced by the URLs in the collection
 * @ param persistenceXml
 * @ return A collection of parsed persistence units , or null if nothing has been found */
public static PersistenceUnitInfo findPersistenceUnit ( String unitName , Collection < ? extends PersistenceUnitInfo > units ) { } }

implementation: if ( units == null || unitName == null ) { return null ; } for ( PersistenceUnitInfo unit : units ) { if ( unitName . equals ( unit . getPersistenceUnitName ( ) ) ) { return unit ; } } return null ;


signature:
public class PersistenceXmlUtil { /** * Parse the persistence . xml files referenced by the URLs in the collection
 * @ param persistenceXml
 * @ return A collection of parsed persistence units .
 * @ throws IOException
 * @ throws SAXException
 * @ throws ParserConfigurationException */
public static Collection < ? extends PersistenceUnitInfo > parse ( URL persistenceXml ) { } }

implementation:
InputStream is = null ; try { // Buffer the InputStream so we can mark it , though we ' ll be in
// trouble if we have to read more than 8192 characters before finding
// the schema !
is = new BufferedInputStream ( persistenceXml . openStream ( ) ) ; JPAVersion jpaVersion = getSchemaVersion ( is ) ; Schema schema = getSchema ( jpaVersion ) ; if ( schema == null ) { throw new PersistenceException ( "Schema is unknown" ) ; } // Get back to the beginning of the stream
is = new BufferedInputStream ( persistenceXml . openStream ( ) ) ; parserFactory . setNamespaceAware ( true ) ; int endIndex = persistenceXml . getPath ( ) . length ( ) - PERSISTENCE_XML_BASE_NAME . length ( ) ; URL persistenceXmlRoot = new URL ( "file://" + persistenceXml . getFile ( ) . substring ( 0 , endIndex ) ) ; return getPersistenceUnits ( is , persistenceXmlRoot , jpaVersion ) ; } catch ( Exception e ) { throw new PersistenceException ( "Something goes wrong while parsing persistence.xml" , e ) ; } finally { if ( is != null ) try { is . close ( ) ; } catch ( IOException e ) { // No logging necessary , just consume
} }


signature:
public class SchemaLocatingHandler { /** * Fist tag of ' persistence . xml ' ( < persistence > ) have to have ' version ' attribute
 * @ see org . xml . sax . helpers . DefaultHandler # startElement ( java . lang . String , java . lang . String , java . lang . String ,
 * org . xml . sax . Attributes ) */
@ Override public void startElement ( String uri , String localName , String name , Attributes attributes ) throws SAXException { } }

implementation:
PersistenceXml element = PersistenceXml . parse ( ( localName == null || localName . isEmpty ( ) ) ? name : localName ) ; schemaVersion = PersistenceXmlUtil . parseSchemaVersion ( uri , element , attributes ) ; // found , stop parsing
if ( schemaVersion != null ) { throw new StopSAXParser ( ) ; } // This should never occurs , however check if contain known tag other than TAG _ PERSISTENCE
if ( TAG_PERSISTENCE != element && EnumSet . allOf ( PersistenceXml . class ) . contains ( element ) ) { throw new PersistenceException ( "Cannot find schema version attribute in <persistence> tag" ) ; }


signature:
public class OVarIntSerializer { /** * Encodes a value using the variable - length encoding from < a
 * href = " http : / / code . google . com / apis / protocolbuffers / docs / encoding . html " > Google Protocol Buffers < / a > . Zig - zag is not used , so
 * input must not be negative .
 * @ param value value to encode
 * @ return the number of bytes written */
public static void writeUnsignedVarLong ( long value , final BytesContainer bos ) { } }

implementation:
int pos ; while ( ( value & 0xFFFFFFFFFFFFFF80L ) != 0L ) { // out . writeByte ( ( ( int ) value & 0x7F ) | 0x80 ) ;
pos = bos . alloc ( ( short ) 1 ) ; bos . bytes [ pos ] = ( byte ) ( value & 0x7F | 0x80 ) ; value >>>= 7 ; } // out . writeByte ( ( int ) value & 0x7F ) ;
pos = bos . alloc ( ( short ) 1 ) ; bos . bytes [ pos ] = ( byte ) ( value & 0x7F ) ;


signature:
public class OVarIntSerializer { /** * @ param bytes to read bytes from
 * @ return decode value
 * @ throws IllegalArgumentException if variable - length value does not terminate after 9 bytes have been read */
public static long readSignedVarLong ( final BytesContainer bytes ) { } }

implementation:
final long raw = readUnsignedVarLong ( bytes ) ; // This undoes the trick in writeSignedVarLong ( )
final long temp = ( ( ( raw << 63 ) >> 63 ) ^ raw ) >> 1 ; // This extra step lets us deal with the largest signed values by
// treating
// negative results from read unsigned methods as like unsigned values
// Must re - flip the top bit if the original read value had it set .
return temp ^ ( raw & ( 1L << 63 ) ) ;


signature:
public class OVarIntSerializer { /** * @ param bytes to read bytes from
 * @ return decode value
 * @ throws IllegalArgumentException if variable - length value does not terminate after 9 bytes have been read */
public static long readUnsignedVarLong ( final BytesContainer bytes ) { } }

implementation: long value = 0L ; int i = 0 ; long b ; while ( ( ( b = bytes . bytes [ bytes . offset ++ ] ) & 0x80L ) != 0 ) { value |= ( b & 0x7F ) << i ; i += 7 ; if ( i > 63 ) throw new IllegalArgumentException ( "Variable length quantity is too long (must be <= 63)" ) ; } return value | ( b << i ) ;


signature:
public class ODistributedAbstractPlugin { /** * Auto register myself as hook . */
@ Override public void onOpen ( final ODatabaseInternal iDatabase ) { } }

implementation:
if ( ! isRelatedToLocalServer ( iDatabase ) ) return ; if ( isOffline ( ) && status != NODE_STATUS . STARTING ) return ; final ODatabaseDocumentInternal currDb = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { final String dbName = iDatabase . getName ( ) ; final ODistributedConfiguration cfg = getDatabaseConfiguration ( dbName ) ; if ( cfg == null ) return ; } catch ( HazelcastException e ) { throw OException . wrapException ( new OOfflineNodeException ( "Hazelcast instance is not available" ) , e ) ; } catch ( HazelcastInstanceNotActiveException e ) { throw OException . wrapException ( new OOfflineNodeException ( "Hazelcast instance is not available" ) , e ) ; } finally { // RESTORE ORIGINAL DATABASE INSTANCE IN TL
ODatabaseRecordThreadLocal . instance ( ) . set ( currDb ) ; }


signature:
public class ODistributedAbstractPlugin { /** * Installs a database from the network . */
protected void installDatabaseFromNetwork ( final String dbPath , final String databaseName , final ODistributedDatabaseImpl distrDatabase , final String iNode , final ODistributedDatabaseChunk firstChunk , final boolean delta , final File uniqueClustersBackupDirectory , final OModifiableDistributedConfiguration cfg ) { } }

implementation:
final String localNodeName = nodeName ; final AtomicReference < ODistributedMomentum > momentum = new AtomicReference < ODistributedMomentum > ( ) ; OSyncReceiver receiver = new OSyncReceiver ( this , databaseName , firstChunk , momentum , iNode , dbPath ) ; try { Thread t = new Thread ( receiver ) ; t . setUncaughtExceptionHandler ( new OUncaughtExceptionHandler ( ) ) ; t . start ( ) ; } catch ( Exception e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , "Error on transferring database '%s' " , e , databaseName ) ; throw OException . wrapException ( new ODistributedException ( "Error on transferring database" ) , e ) ; } final ODatabaseDocumentInternal db = installDatabaseOnLocalNode ( databaseName , dbPath , iNode , delta , uniqueClustersBackupDirectory , cfg , firstChunk . incremental , receiver ) ; if ( db == null ) return ; // OVERWRITE THE MOMENTUM FROM THE ORIGINAL SERVER AND ADD LAST LOCAL LSN
try { distrDatabase . getSyncConfiguration ( ) . load ( ) ; distrDatabase . getSyncConfiguration ( ) . setLastLSN ( localNodeName , ( ( OLocalPaginatedStorage ) db . getStorage ( ) . getUnderlying ( ) ) . getLSN ( ) , false ) ; } catch ( IOException e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , "Error on loading %s file for database '%s'" , e , DISTRIBUTED_SYNC_JSON_FILENAME , databaseName ) ; } try { distrDatabase . setOnline ( ) ; } finally { db . activateOnCurrentThread ( ) ; db . close ( ) ; } // ASK FOR INDIVIDUAL CLUSTERS IN CASE OF SHARDING AND NO LOCAL COPY
final Set < String > localManagedClusters = cfg . getClustersOnServer ( localNodeName ) ; final Set < String > sourceNodeClusters = cfg . getClustersOnServer ( iNode ) ; localManagedClusters . removeAll ( sourceNodeClusters ) ; final HashSet < String > toSynchClusters = new HashSet < String > ( ) ; for ( String cl : localManagedClusters ) { // FILTER CLUSTER CHECKING IF ANY NODE IS ACTIVE
final List < String > servers = cfg . getServers ( cl , localNodeName ) ; getAvailableNodes ( servers , databaseName ) ; if ( ! servers . isEmpty ( ) ) toSynchClusters . add ( cl ) ; } // SYNC ALL THE CLUSTERS
for ( String cl : toSynchClusters ) { // FILTER CLUSTER CHECKING IF ANY NODE IS ACTIVE
OCommandExecutorSQLHASyncCluster . replaceCluster ( this , serverInstance , databaseName , cl ) ; } try { rebalanceClusterOwnership ( nodeName , db , cfg , false ) ; } catch ( Exception e ) { // HANDLE IT AS WARNING
ODistributedServerLog . warn ( this , nodeName , null , DIRECTION . NONE , "Error on re-balancing the cluster for database '%s'" , e , databaseName ) ; // NOT CRITICAL , CONTINUE
}


signature:
public class ODistributedAbstractPlugin { /** * Guarantees that each class has own master cluster . */
public boolean installClustersOfClass ( final ODatabaseInternal iDatabase , final OClass iClass , OModifiableDistributedConfiguration cfg ) { } }

implementation:
final String databaseName = iDatabase . getName ( ) ; if ( iClass . isAbstract ( ) ) return false ; // INIT THE DATABASE IF NEEDED
getMessageService ( ) . registerDatabase ( databaseName , cfg ) ; return executeInDistributedDatabaseLock ( databaseName , 20000 , cfg , new OCallable < Boolean , OModifiableDistributedConfiguration > ( ) { @ Override public Boolean call ( final OModifiableDistributedConfiguration lastCfg ) { final Set < String > availableNodes = getAvailableNodeNames ( iDatabase . getName ( ) ) ; final List < String > cluster2Create = clusterAssignmentStrategy . assignClusterOwnershipOfClass ( iDatabase , lastCfg , iClass , availableNodes , true ) ; final Map < OClass , List < String > > cluster2CreateMap = new HashMap < OClass , List < String > > ( 1 ) ; cluster2CreateMap . put ( iClass , cluster2Create ) ; createClusters ( iDatabase , cluster2CreateMap , lastCfg ) ; return true ; } } ) ;


signature:
public class ODistributedAbstractPlugin { /** * Executes an operation protected by a distributed lock ( one per database ) .
 * @ param < T > Return type
 * @ param databaseName Database name
 * @ param iCallback Operation @ return The operation ' s result of type T */
public < T > T executeInDistributedDatabaseLock ( final String databaseName , final long timeoutLocking , OModifiableDistributedConfiguration lastCfg , final OCallable < T , OModifiableDistributedConfiguration > iCallback ) { } }

implementation:
boolean updated ; T result ; lockManagerRequester . acquireExclusiveLock ( databaseName , nodeName , timeoutLocking ) ; try { if ( lastCfg == null ) // ACQUIRE CFG INSIDE THE LOCK
lastCfg = getDatabaseConfiguration ( databaseName ) . modify ( ) ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , nodeName , null , DIRECTION . NONE , "Current distributed configuration for database '%s': %s" , databaseName , lastCfg . getDocument ( ) . toJSON ( ) ) ; try { result = iCallback . call ( lastCfg ) ; } finally { if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , nodeName , null , DIRECTION . NONE , "New distributed configuration for database '%s': %s" , databaseName , lastCfg . getDocument ( ) . toJSON ( ) ) ; // CONFIGURATION CHANGED , UPDATE IT ON THE CLUSTER AND DISK
updated = updateCachedDatabaseConfiguration ( databaseName , lastCfg , true ) ; } } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { lockManagerRequester . releaseExclusiveLock ( databaseName , nodeName ) ; } if ( updated ) { // SEND NEW CFG TO ALL THE CONNECTED CLIENTS
notifyClients ( databaseName ) ; serverInstance . getClientConnectionManager ( ) . pushDistribCfg2Clients ( getClusterConfiguration ( ) ) ; } return result ;


signature:
public class ODistributedAbstractPlugin { /** * Avoids to dump the same configuration twice if it ' s unchanged since the last time . */
protected void dumpServersStatus ( ) { } }

implementation: final ODocument cfg = getClusterConfiguration ( ) ; final String compactStatus = ODistributedOutput . getCompactServerStatus ( this , cfg ) ; if ( ! lastServerDump . equals ( compactStatus ) ) { lastServerDump = compactStatus ; ODistributedServerLog . info ( this , getLocalNodeName ( ) , null , DIRECTION . NONE , "Distributed servers status (*=current @=lockmgr[%s]):\n%s" , getLockManagerServer ( ) , ODistributedOutput . formatServerStatus ( this , cfg ) ) ; }


signature:
public class OCollections { /** * This method is used to find item in collection using passed in comparator . Only 0 value ( requested object is found ) returned by
 * comparator is taken into account the rest is ignored .
 * @ param list
 * List in which value should be found .
 * @ param object
 * Object to find .
 * @ param comparator
 * Comparator is sued for search .
 * @ param < T >
 * Type of collection elements .
 * @ return Index of found item or < code > - 1 < / code > otherwise . */
public static < T > int indexOf ( final List < T > list , final T object , final Comparator < T > comparator ) { } }

implementation: int i = 0 ; for ( final T item : list ) { if ( comparator . compare ( item , object ) == 0 ) return i ; i ++ ; } return - 1 ;


signature:
public class OCollections { /** * This method is used to find an item in an array .
 * @ param array Array in which value should be found .
 * @ param object Object to find .
 * @ return Index of found item or < code > - 1 < / code > otherwise . */
public static int indexOf ( final Object [ ] array , final Comparable object ) { } }

implementation:
for ( int i = 0 ; i < array . length ; ++ i ) { if ( object . compareTo ( array [ i ] ) == 0 ) // FOUND
return i ; } return - 1 ;


signature:
public class OCollections { /** * This method is used to find a number in an array .
 * @ param array Array of integers in which value should be found .
 * @ param object number to find .
 * @ return Index of found item or < code > - 1 < / code > otherwise . */
public static int indexOf ( final int [ ] array , final int object ) { } }

implementation:
for ( int i = 0 ; i < array . length ; ++ i ) { if ( array [ i ] == object ) // FOUND
return i ; } return - 1 ;


signature:
public class OCommandExecutorSQLSelect { /** * Compile the filter conditions only the first time . */
public OCommandExecutorSQLSelect parse ( final OCommandRequest iRequest ) { } }

implementation:
final OCommandRequestText textRequest = ( OCommandRequestText ) iRequest ; String queryText = textRequest . getText ( ) ; String originalQuery = queryText ; try { // System . out . println ( " NEW PARSER FROM : " + queryText ) ;
queryText = preParse ( queryText , iRequest ) ; // System . out . println ( " NEW PARSER TO : " + queryText ) ;
textRequest . setText ( queryText ) ; super . parse ( iRequest ) ; initContext ( ) ; final int pos = parseProjections ( ) ; if ( pos == - 1 ) { return this ; } final int endPosition = parserText . length ( ) ; parserNextWord ( true ) ; if ( parserGetLastWord ( ) . equalsIgnoreCase ( KEYWORD_FROM ) ) { // FROM
parsedTarget = OSQLEngine . getInstance ( ) . parseTarget ( parserText . substring ( parserGetCurrentPosition ( ) , endPosition ) , getContext ( ) ) ; parserSetCurrentPosition ( parsedTarget . parserIsEnded ( ) ? endPosition : parsedTarget . parserGetCurrentPosition ( ) + parserGetCurrentPosition ( ) ) ; } else { parserGoBack ( ) ; } if ( ! parserIsEnded ( ) ) { parserSkipWhiteSpaces ( ) ; while ( ! parserIsEnded ( ) ) { final String w = parserNextWord ( true ) ; if ( ! w . isEmpty ( ) ) { if ( w . equals ( KEYWORD_WHERE ) ) { compiledFilter = OSQLEngine . getInstance ( ) . parseCondition ( parserText . substring ( parserGetCurrentPosition ( ) , endPosition ) , getContext ( ) , KEYWORD_WHERE ) ; optimize ( ) ; parserSetCurrentPosition ( compiledFilter . parserIsEnded ( ) ? endPosition : compiledFilter . parserGetCurrentPosition ( ) + parserGetCurrentPosition ( ) ) ; } else if ( w . equals ( KEYWORD_LET ) ) { parseLet ( ) ; } else if ( w . equals ( KEYWORD_GROUP ) ) { parseGroupBy ( ) ; } else if ( w . equals ( KEYWORD_ORDER ) ) { parseOrderBy ( ) ; } else if ( w . equals ( KEYWORD_UNWIND ) ) { parseUnwind ( ) ; } else if ( w . equals ( KEYWORD_LIMIT ) ) { parseLimit ( w ) ; } else if ( w . equals ( KEYWORD_SKIP ) || w . equals ( KEYWORD_OFFSET ) ) { parseSkip ( w ) ; } else if ( w . equals ( KEYWORD_FETCHPLAN ) ) { parseFetchplan ( w ) ; } else if ( w . equals ( KEYWORD_NOCACHE ) ) { parseNoCache ( w ) ; } else if ( w . equals ( KEYWORD_TIMEOUT ) ) { parseTimeout ( w ) ; } else if ( w . equals ( KEYWORD_LOCK ) ) { final String lock = parseLock ( ) ; if ( lock . equalsIgnoreCase ( "DEFAULT" ) ) { lockingStrategy = LOCKING_STRATEGY . DEFAULT ; } else if ( lock . equals ( "NONE" ) ) { lockingStrategy = LOCKING_STRATEGY . NONE ; } else if ( lock . equals ( "RECORD" ) ) { lockingStrategy = LOCKING_STRATEGY . EXCLUSIVE_LOCK ; } else if ( lock . equals ( "SHARED" ) ) { lockingStrategy = LOCKING_STRATEGY . SHARED_LOCK ; } } else if ( w . equals ( KEYWORD_PARALLEL ) ) { parallel = parseParallel ( w ) ; } else { if ( preParsedStatement == null ) { throwParsingException ( "Invalid keyword '" + w + "'" ) ; } // if the pre - parsed statement is OK , then you can go on with the rest , the SQL is valid and this is probably a space in a backtick
} } } } if ( limit == 0 || limit < - 1 ) { throw new IllegalArgumentException ( "Limit must be > 0 or = -1 (no limit)" ) ; } validateQuery ( ) ; } finally { textRequest . setText ( originalQuery ) ; } return this ;


signature:
public class OCommandExecutorSQLSelect { /** * Determine clusters that are used in select operation
 * @ return set of involved cluster names */
@ Override public Set < String > getInvolvedClusters ( ) { } }

implementation:
final Set < String > clusters = new HashSet < String > ( ) ; if ( parsedTarget != null ) { final ODatabaseDocument db = getDatabase ( ) ; if ( parsedTarget . getTargetQuery ( ) != null && parsedTarget . getTargetRecords ( ) instanceof OCommandExecutorSQLResultsetDelegate ) { // SUB - QUERY : EXECUTE IT LOCALLY
// SUB QUERY , PROPAGATE THE CALL
final Set < String > clIds = ( ( OCommandExecutorSQLResultsetDelegate ) parsedTarget . getTargetRecords ( ) ) . getInvolvedClusters ( ) ; for ( String c : clIds ) { // FILTER THE CLUSTER WHERE THE USER HAS THE RIGHT ACCESS
if ( checkClusterAccess ( db , c ) ) { clusters . add ( c ) ; } } } else if ( parsedTarget . getTargetRecords ( ) != null ) { // SINGLE RECORDS : BROWSE ALL ( COULD BE EXPENSIVE ) .
for ( OIdentifiable identifiable : parsedTarget . getTargetRecords ( ) ) { final String c = db . getClusterNameById ( identifiable . getIdentity ( ) . getClusterId ( ) ) . toLowerCase ( Locale . ENGLISH ) ; // FILTER THE CLUSTER WHERE THE USER HAS THE RIGHT ACCESS
if ( checkClusterAccess ( db , c ) ) { clusters . add ( c ) ; } } } if ( parsedTarget . getTargetClasses ( ) != null ) { return getInvolvedClustersOfClasses ( parsedTarget . getTargetClasses ( ) . values ( ) ) ; } if ( parsedTarget . getTargetClusters ( ) != null ) { return getInvolvedClustersOfClusters ( parsedTarget . getTargetClusters ( ) . keySet ( ) ) ; } if ( parsedTarget . getTargetIndex ( ) != null ) { // EXTRACT THE CLASS NAME - > CLUSTERS FROM THE INDEX DEFINITION
return getInvolvedClustersOfIndex ( parsedTarget . getTargetIndex ( ) ) ; } } return clusters ;


signature:
public class OCommandExecutorSQLSelect { /** * Handles the record in result .
 * @ param iRecord Record to handle
 * @ return false if limit has been reached , otherwise true */
@ Override protected boolean handleResult ( final OIdentifiable iRecord , final OCommandContext iContext ) { } }

implementation: lastRecord = iRecord ; if ( ( orderedFields . isEmpty ( ) || fullySortedByIndex || isRidOnlySort ( ) ) && skip > 0 && this . unwindFields == null && this . expandTarget == null ) { lastRecord = null ; skip -- ; return true ; } if ( ! addResult ( lastRecord , iContext ) ) { return false ; } return continueSearching ( ) ;


signature:
public class OCommandExecutorSQLSelect { /** * Returns the temporary RID counter assuring it ' s unique per query tree .
 * @ return Serial as integer */
public int getTemporaryRIDCounter ( final OCommandContext iContext ) { } }

implementation: final OTemporaryRidGenerator parentQuery = ( OTemporaryRidGenerator ) iContext . getVariable ( "parentQuery" ) ; return parentQuery != null && parentQuery != this ? parentQuery . getTemporaryRIDCounter ( iContext ) : serialTempRID . getAndIncrement ( ) ;


signature:
public class OCommandExecutorSQLSelect { /** * in case of ORDER BY + SKIP + LIMIT , this method applies ORDER BY operation on partial result and discards overflowing results
 * ( results > skip + limit ) */
private void applyPartialOrderBy ( ) { } }

implementation: if ( expandTarget != null || ( unwindFields != null && unwindFields . size ( ) > 0 ) || orderedFields . isEmpty ( ) || fullySortedByIndex || isRidOnlySort ( ) ) { return ; } if ( limit > 0 ) { int sortBufferSize = limit + 1 ; if ( skip > 0 ) { sortBufferSize += skip ; } if ( tempResult instanceof List && ( ( List ) tempResult ) . size ( ) >= sortBufferSize + PARTIAL_SORT_BUFFER_THRESHOLD ) { applyOrderBy ( false ) ; tempResult = new ArrayList ( ( ( List ) tempResult ) . subList ( 0 , sortBufferSize ) ) ; } }


signature:
public class OCommandExecutorSQLSelect { /** * Report the tip to the profiler and collect it in context to be reported by tools like Studio */
protected void reportTip ( final String iMessage ) { } }

implementation: Orient . instance ( ) . getProfiler ( ) . reportTip ( iMessage ) ; List < String > tips = ( List < String > ) context . getVariable ( "tips" ) ; if ( tips == null ) { tips = new ArrayList < String > ( 3 ) ; context . setVariable ( "tips" , tips ) ; } tips . add ( iMessage ) ;


signature:
public class OCommandExecutorSQLSelect { /** * Parses the fetchplan keyword if found . */
protected boolean parseFetchplan ( final String w ) throws OCommandSQLParsingException { } }

implementation: if ( ! w . equals ( KEYWORD_FETCHPLAN ) ) { return false ; } parserSkipWhiteSpaces ( ) ; int start = parserGetCurrentPosition ( ) ; parserNextWord ( true ) ; int end = parserGetCurrentPosition ( ) ; parserSkipWhiteSpaces ( ) ; int position = parserGetCurrentPosition ( ) ; while ( ! parserIsEnded ( ) ) { final String word = OIOUtils . getStringContent ( parserNextWord ( true ) ) ; if ( ! OPatternConst . PATTERN_FETCH_PLAN . matcher ( word ) . matches ( ) ) { break ; } end = parserGetCurrentPosition ( ) ; parserSkipWhiteSpaces ( ) ; position = parserGetCurrentPosition ( ) ; } parserSetCurrentPosition ( position ) ; if ( end < 0 ) { fetchPlan = OIOUtils . getStringContent ( parserText . substring ( start ) ) ; } else { fetchPlan = OIOUtils . getStringContent ( parserText . substring ( start , end ) ) ; } request . setFetchPlan ( fetchPlan ) ; return true ;


signature:
public class OCommandExecutorSQLSelect { /** * Parses the NOCACHE keyword if found . */
protected boolean parseNoCache ( final String w ) throws OCommandSQLParsingException { } }

implementation: if ( ! w . equals ( KEYWORD_NOCACHE ) ) return false ; noCache = true ; return true ;