signature:
public class OrientBaseGraph { /** * ( Internal only ) */
protected static void removeEdges ( final OrientBaseGraph graph , final ODocument iVertex , final String iFieldName , final OIdentifiable iVertexToRemove , final boolean iAlsoInverse , final boolean useVertexFieldsForEdgeLabels , final boolean autoScaleEdgeType , final boolean forceReload ) { } }

implementation:
if ( iVertex == null ) return ; final Object fieldValue = iVertexToRemove != null ? iVertex . field ( iFieldName ) : iVertex . removeField ( iFieldName ) ; if ( fieldValue == null ) return ; if ( fieldValue instanceof OIdentifiable ) { // SINGLE RECORD
if ( iVertexToRemove != null ) { if ( ! fieldValue . equals ( iVertexToRemove ) ) // NOT FOUND
return ; iVertex . removeField ( iFieldName ) ; deleteEdgeIfAny ( iVertexToRemove , forceReload ) ; } if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , ( OIdentifiable ) fieldValue , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; } else if ( fieldValue instanceof ORidBag ) { // COLLECTION OF RECORDS : REMOVE THE ENTRY
final ORidBag bag = ( ORidBag ) fieldValue ; if ( iVertexToRemove != null ) { // SEARCH SEQUENTIALLY ( SLOWER )
for ( Iterator < OIdentifiable > it = bag . rawIterator ( ) ; it . hasNext ( ) ; ) { final ODocument curr = getDocument ( it . next ( ) , forceReload ) ; if ( curr == null ) { // EDGE REMOVED
it . remove ( ) ; iVertex . save ( ) ; continue ; } if ( iVertexToRemove . equals ( curr ) ) { // FOUND AS VERTEX
it . remove ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , curr , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; break ; } else if ( ODocumentInternal . getImmutableSchemaClass ( curr ) . isEdgeType ( ) ) { final Direction direction = OrientVertex . getConnectionDirection ( iFieldName , useVertexFieldsForEdgeLabels ) ; // EDGE , REMOVE THE EDGE
if ( iVertexToRemove . equals ( OrientEdge . getConnection ( curr , direction . opposite ( ) ) ) ) { it . remove ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , curr , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; break ; } } } deleteEdgeIfAny ( iVertexToRemove , forceReload ) ; } else { // DELETE ALL THE EDGES
for ( Iterator < OIdentifiable > it = bag . rawIterator ( ) ; it . hasNext ( ) ; ) { OIdentifiable edge = it . next ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , null , edge , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; deleteEdgeIfAny ( edge , forceReload ) ; } } if ( autoScaleEdgeType && bag . isEmpty ( ) ) // FORCE REMOVAL OF ENTIRE FIELD
iVertex . removeField ( iFieldName ) ; } else if ( fieldValue instanceof Collection ) { final Collection col = ( Collection ) fieldValue ; if ( iVertexToRemove != null ) { // SEARCH SEQUENTIALLY ( SLOWER )
for ( Iterator < OIdentifiable > it = col . iterator ( ) ; it . hasNext ( ) ; ) { final ODocument curr = getDocument ( it . next ( ) , forceReload ) ; if ( curr == null ) // EDGE REMOVED
continue ; if ( iVertexToRemove . equals ( curr ) ) { // FOUND AS VERTEX
it . remove ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , curr , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; break ; } else if ( ODocumentInternal . getImmutableSchemaClass ( curr ) . isVertexType ( ) ) { final Direction direction = OrientVertex . getConnectionDirection ( iFieldName , useVertexFieldsForEdgeLabels ) ; // EDGE , REMOVE THE EDGE
if ( iVertexToRemove . equals ( OrientEdge . getConnection ( curr , direction . opposite ( ) ) ) ) { it . remove ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , curr , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; break ; } } } deleteEdgeIfAny ( iVertexToRemove , forceReload ) ; } else { // DELETE ALL THE EDGES
for ( OIdentifiable edge : ( Iterable < OIdentifiable > ) col ) { if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , null , edge , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; deleteEdgeIfAny ( edge , forceReload ) ; } } if ( autoScaleEdgeType && col . isEmpty ( ) ) // FORCE REMOVAL OF ENTIRE FIELD
iVertex . removeField ( iFieldName ) ; }


signature:
public class OrientBaseGraph { /** * ( Internal only ) */
private static void removeInverseEdge ( final OrientBaseGraph graph , final ODocument iVertex , final String iFieldName , final OIdentifiable iVertexToRemove , final OIdentifiable currentRecord , final boolean useVertexFieldsForEdgeLabels , final boolean autoScaleEdgeType , boolean forceReload ) { } }

implementation:
final ODocument r = getDocument ( currentRecord , forceReload ) ; if ( r == null ) return ; final String inverseFieldName = OrientVertex . getInverseConnectionFieldName ( iFieldName , useVertexFieldsForEdgeLabels ) ; OImmutableClass immutableClass = ODocumentInternal . getImmutableSchemaClass ( r ) ; OClass klass = ODocumentInternal . getImmutableSchemaClass ( r ) ; if ( klass == null ) { graph . getDatabase ( ) . getMetadata ( ) . reload ( ) ; klass = graph . getDatabase ( ) . getMetadata ( ) . getSchema ( ) . getClass ( inverseFieldName ) ; if ( klass == null ) { OLogManager . instance ( ) . warn ( null , "Removing edge, schema class not found for " + r ) ; return ; } } if ( klass . isVertexType ( ) ) { // DIRECT VERTEX
removeEdges ( graph , r , inverseFieldName , iVertex , false , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; r . save ( ) ; } else if ( klass . isEdgeType ( ) ) { // EDGE , REMOVE THE EDGE
final OIdentifiable otherVertex = OrientEdge . getConnection ( r , OrientVertex . getConnectionDirection ( inverseFieldName , useVertexFieldsForEdgeLabels ) ) ; if ( otherVertex != null ) { if ( iVertexToRemove == null || otherVertex . equals ( iVertexToRemove ) ) { final int maxRetries = graph . getMaxRetries ( ) ; for ( int retry = 0 ; retry < maxRetries ; ++ retry ) { try { final ODocument otherVertexRecord = getDocument ( otherVertex , forceReload ) ; // BIDIRECTIONAL EDGE
removeEdges ( graph , otherVertexRecord , inverseFieldName , ( OIdentifiable ) currentRecord , false , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; if ( otherVertexRecord != null ) otherVertexRecord . save ( ) ; break ; } catch ( ONeedRetryException e ) { // RETRY
} } } } }


signature:
public class OrientBaseGraph { /** * ( Internal only ) */
protected static void deleteEdgeIfAny ( final OIdentifiable iRecord , boolean forceReload ) { } }

implementation:
if ( iRecord != null ) { final ODocument doc = getDocument ( iRecord , forceReload ) ; if ( doc != null ) { final OImmutableClass clazz = ODocumentInternal . getImmutableSchemaClass ( doc ) ; if ( clazz != null && clazz . isEdgeType ( ) ) // DELETE THE EDGE RECORD TOO
doc . delete ( ) ; } }


signature:
public class OWOWCache { /** * Removes listener which is triggered if exception is cast inside background flush data thread .
 * @ param listener Listener to remove */
@ Override public void removeBackgroundExceptionListener ( final OBackgroundExceptionListener listener ) { } }

implementation: final List < WeakReference < OBackgroundExceptionListener > > itemsToRemove = new ArrayList < > ( 1 ) ; for ( final WeakReference < OBackgroundExceptionListener > ref : backgroundExceptionListeners ) { final OBackgroundExceptionListener l = ref . get ( ) ; if ( l != null && l . equals ( listener ) ) { itemsToRemove . add ( ref ) ; } } backgroundExceptionListeners . removeAll ( itemsToRemove ) ;


signature:
public class OWOWCache { /** * Fires event about exception is thrown in data flush thread */
private void fireBackgroundDataFlushExceptionEvent ( final Throwable e ) { } }

implementation: for ( final WeakReference < OBackgroundExceptionListener > ref : backgroundExceptionListeners ) { final OBackgroundExceptionListener listener = ref . get ( ) ; if ( listener != null ) { listener . onException ( e ) ; } }


signature:
public class OWOWCache { /** * This method is called once new pages are added to the disk inside of
 * { @ link OWriteCache # load ( long , long , int , OModifiableBoolean , boolean ) } method .
 * If total amount of added pages minus amount of added pages at the time of last disk space check bigger than threshold value
 * { @ link # diskSizeCheckInterval } new disk space check is performed and if amount of space left on disk less than threshold
 * { @ link
 * # freeSpaceLimit } then database is switched in " read only " mode */
private void freeSpaceCheckAfterNewPageAdd ( ) throws IOException { } }

implementation:
final long newPagesAdded = amountOfNewPagesAdded . addAndGet ( 1 ) ; final long lastSpaceCheck = lastDiskSpaceCheck . get ( ) ; if ( newPagesAdded - lastSpaceCheck > diskSizeCheckInterval || lastSpaceCheck == 0 ) { // usable space may be less than free space
final long freeSpace = Files . getFileStore ( storagePath ) . getUsableSpace ( ) ; if ( freeSpace < freeSpaceLimit ) { callLowSpaceListeners ( new OLowDiskSpaceInformation ( freeSpace , freeSpaceLimit ) ) ; } lastDiskSpaceCheck . lazySet ( newPagesAdded ) ; }


signature:
public class OWOWCache { /** * Read information about files are registered inside of write cache / storage
 * File consist of rows of variable length which contains following entries : < ol > < li > Internal file id , may be positive or
 * negative depends on whether file is removed or not < / li > < li > Name of file inside of write cache , this name is case
 * sensitive < / li > < li > Name of file which is used inside file system it can be different from name of file used inside write
 * cache < / li > < / ol > */
private void readNameIdMapV2 ( ) throws IOException , InterruptedException { } }

implementation: nameIdMap . clear ( ) ; long localFileCounter = - 1 ; nameIdMapHolder . position ( 0 ) ; NameFileIdEntry nameFileIdEntry ; final Map < Integer , String > idFileNameMap = new HashMap < > ( 1_000 ) ; while ( ( nameFileIdEntry = readNextNameIdEntryV2 ( ) ) != null ) { final long absFileId = Math . abs ( nameFileIdEntry . fileId ) ; if ( localFileCounter < absFileId ) { localFileCounter = absFileId ; } nameIdMap . put ( nameFileIdEntry . name , nameFileIdEntry . fileId ) ; if ( nameFileIdEntry . fileId >= 0 ) { idNameMap . put ( nameFileIdEntry . fileId , nameFileIdEntry . name ) ; } idFileNameMap . put ( nameFileIdEntry . fileId , nameFileIdEntry . fileSystemName ) ; } if ( localFileCounter > 0 && nextInternalId < localFileCounter ) { nextInternalId = ( int ) localFileCounter ; } for ( final Map . Entry < String , Integer > nameIdEntry : nameIdMap . entrySet ( ) ) { final int fileId = nameIdEntry . getValue ( ) ; if ( fileId >= 0 ) { final long externalId = composeFileId ( id , nameIdEntry . getValue ( ) ) ; if ( files . get ( externalId ) == null ) { final Path path = storagePath . resolve ( idFileNameMap . get ( ( nameIdEntry . getValue ( ) ) ) ) ; final OFileClassic fileClassic = new OFileClassic ( path ) ; if ( fileClassic . exists ( ) ) { fileClassic . open ( ) ; files . add ( externalId , fileClassic ) ; } else { nameIdMap . put ( nameIdEntry . getKey ( ) , - fileId ) ; idNameMap . remove ( fileId ) ; } } } }


signature:
public class ONestedProjectionItem { /** * given a property name , calculates if this property name matches this nested projection item , eg .
 * < ul >
 * < li > this is a * , so it matches any property name < / li >
 * < li > the field name for this projection item is the same as the input property name < / li >
 * < li > this item has a wildcard and the partial field is a prefix of the input property name < / li >
 * < / ul >
 * @ param propertyName
 * @ return */
public boolean matches ( String propertyName ) { } }

implementation: if ( star ) { return true ; } if ( expression != null ) { String fieldString = expression . getDefaultAlias ( ) . getStringValue ( ) ; if ( fieldString . equals ( propertyName ) ) { return true ; } if ( rightWildcard && propertyName . startsWith ( fieldString ) ) { return true ; } } return false ;


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

implementation: if ( clusterName == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseDocumentInternal database = getDatabase ( ) ; final int clusterId = database . getClusterIdByName ( clusterName ) ; if ( clusterId < 0 ) { throw new ODatabaseException ( "Cluster with name " + clusterName + " does not exist" ) ; } final OSchema schema = database . getMetadata ( ) . getSchema ( ) ; final OClass clazz = schema . getClassByClusterId ( clusterId ) ; if ( clazz == null ) { final OStorage storage = database . getStorage ( ) ; final OCluster cluster = storage . getClusterById ( clusterId ) ; if ( cluster == null ) { throw new ODatabaseException ( "Cluster with name " + clusterName + " does not exist" ) ; } try { database . checkForClusterPermissions ( cluster . getName ( ) ) ; cluster . truncate ( ) ; } catch ( IOException ioe ) { throw OException . wrapException ( new ODatabaseException ( "Error during truncation of cluster with name " + clusterName ) , ioe ) ; } } else { clazz . truncateCluster ( clusterName ) ; } return true ;


signature:
public class OPerformanceStatisticManager { /** * Starts performance monitoring only for single thread .
 * After call of this method you can not start system wide monitoring till call of { @ link # stopThreadMonitoring ( ) } is performed . */
public void startThreadMonitoring ( ) { } }

implementation: switchLock . acquireWriteLock ( ) ; try { if ( enabled ) throw new IllegalStateException ( "Monitoring is already started on system level and can not be started on thread level" ) ; enabledForCurrentThread . set ( true ) ; statistics . put ( Thread . currentThread ( ) , new OSessionStoragePerformanceStatistic ( intervalBetweenSnapshots , Long . MAX_VALUE ) ) ; } finally { switchLock . releaseWriteLock ( ) ; }


signature:
public class OPerformanceStatisticManager { /** * Starts performance monitoring only for whole system .
 * After call of this method you can not start monitoring on thread level till call of { @ link # stopMonitoring ( ) } is performed . */
public void startMonitoring ( ) { } }

implementation: switchLock . acquireWriteLock ( ) ; try { if ( ! statistics . isEmpty ( ) && ! enabled ) throw new IllegalStateException ( "Monitoring is already started on thread level and can not be started on system level" ) ; deadThreadsStatistic = null ; postMeasurementStatistic = null ; enabled = true ; } finally { switchLock . releaseWriteLock ( ) ; }


signature:
public class OPerformanceStatisticManager { /** * Stops monitoring of performance statistic for whole system . */
public void stopMonitoring ( ) { } }

implementation: switchLock . acquireWriteLock ( ) ; try { enabled = false ; final PerformanceCountersHolder countersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; final Map < String , PerformanceCountersHolder > componentCountersHolder = new HashMap < > ( ) ; WritCacheCountersHolder writCacheCountersHolder = deadThreadsStatistic . writCacheCountersHolder ; StorageCountersHolder storageCountersHolder = deadThreadsStatistic . storageCountersHolder ; WALCountersHolder walCountersHolder = deadThreadsStatistic . walCountersHolder ; deadThreadsStatistic . countersHolder . pushData ( countersHolder ) ; componentCountersHolder . putAll ( deadThreadsStatistic . countersByComponents ) ; deadThreadsStatistic = null ; for ( OSessionStoragePerformanceStatistic statistic : statistics . values ( ) ) { statistic . pushSystemCounters ( countersHolder ) ; statistic . pushComponentCounters ( componentCountersHolder ) ; writCacheCountersHolder = statistic . pushWriteCacheCounters ( writCacheCountersHolder ) ; storageCountersHolder = statistic . pushStorageCounters ( storageCountersHolder ) ; walCountersHolder = statistic . pushWALCounters ( walCountersHolder ) ; } statistics . clear ( ) ; postMeasurementStatistic = new ImmutableStatistic ( countersHolder , componentCountersHolder , writCacheCountersHolder , storageCountersHolder , walCountersHolder ) ; } finally { switchLock . releaseWriteLock ( ) ; }


signature:
public class OPerformanceStatisticManager { /** * Registers JMX bean for current manager .
 * @ param storageName Name of storage of given manager
 * @ param storageId Id of storage of given manager
 * @ see OStorage # getName ( )
 * @ see OIdentifiableStorage # getId ( ) */
public void registerMBean ( String storageName , int storageId ) { } }

implementation: if ( mbeanIsRegistered . compareAndSet ( false , true ) ) { try { final MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; final ObjectName mbeanName = new ObjectName ( getMBeanName ( storageName , storageId ) ) ; if ( ! server . isRegistered ( mbeanName ) ) { server . registerMBean ( new OPerformanceStatisticManagerMBean ( this ) , mbeanName ) ; } else { mbeanIsRegistered . set ( false ) ; OLogManager . instance ( ) . warn ( this , "MBean with name %s has already registered. Probably your system was not shutdown correctly" + " or you have several running applications which use OrientDB engine inside" , mbeanName . getCanonicalName ( ) ) ; } } catch ( MalformedObjectNameException | InstanceAlreadyExistsException | NotCompliantMBeanException | MBeanRegistrationException e ) { throw OException . wrapException ( new OStorageException ( "Error during registration of profiler MBean" ) , e ) ; } }


signature:
public class OPerformanceStatisticManager { /** * Deregisters JMX bean for current manager .
 * @ param storageName Name of storage of given manager
 * @ param storageId Id of storage of given manager
 * @ see OStorage # getName ( )
 * @ see OIdentifiableStorage # getId ( ) */
public void unregisterMBean ( String storageName , int storageId ) { } }

implementation: if ( storageName == null ) { OLogManager . instance ( ) . warnNoDb ( this , "Can not unregister MBean for performance statistics, storage name is null" ) ; } if ( mbeanIsRegistered . compareAndSet ( true , false ) ) { try { final MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; final ObjectName mbeanName = new ObjectName ( getMBeanName ( storageName , storageId ) ) ; server . unregisterMBean ( mbeanName ) ; } catch ( MalformedObjectNameException | InstanceNotFoundException | MBeanRegistrationException e ) { throw OException . wrapException ( new OStorageException ( "Error during unregistration of profiler MBean" ) , e ) ; } }


signature:
public class OPerformanceStatisticManager { /** * Average amount of pages which were read from cache for component with given name during single data operation .
 * If null value is passed or data for component with passed in name does not exist then < code > - 1 < / code > will be returned .
 * @ param componentName Name of component data of which should be returned . Name is case sensitive .
 * @ return Average amount of pages which were read from cache for component with given name during single data operation or value
 * which is less than 0 , which means that value cannot be calculated . */
public long getAmountOfPagesPerOperation ( String componentName ) { } }

implementation: switchLock . acquireReadLock ( ) ; try { if ( enabled ) { final PerformanceCountersHolder componentCountersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; fetchComponentCounters ( componentName , componentCountersHolder ) ; return componentCountersHolder . getAmountOfPagesPerOperation ( ) ; } else { final ImmutableStatistic post = postMeasurementStatistic ; if ( post == null ) return - 1 ; final PerformanceCountersHolder holder = post . countersByComponents . get ( componentName ) ; if ( holder == null ) return - 1 ; return holder . getAmountOfPagesPerOperation ( ) ; } } finally { switchLock . releaseReadLock ( ) ; }


signature:
public class OPerformanceStatisticManager { /** * Percent of cache hits for component name of which is passed as method argument . If null value is passed then value for whole
 * system will be returned . If data for component with passed in name does not exist then < code > - 1 < / code > will be returned .
 * @ param componentName Name of component data of which should be returned . Name is case sensitive .
 * @ return Percent of cache hits or value which is less than 0 , which means that value cannot be calculated . */
public int getCacheHits ( String componentName ) { } }

implementation: switchLock . acquireReadLock ( ) ; try { if ( enabled ) { final PerformanceCountersHolder countersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; fetchComponentCounters ( componentName , countersHolder ) ; return countersHolder . getCacheHits ( ) ; } else { final ImmutableStatistic post = postMeasurementStatistic ; if ( post == null ) return - 1 ; final PerformanceCountersHolder holder = post . countersByComponents . get ( componentName ) ; if ( holder != null ) return holder . getCacheHits ( ) ; return - 1 ; } } finally { switchLock . releaseReadLock ( ) ; }


signature:
public class OPerformanceStatisticManager { /** * Iterates over all live threads and accumulates write performance statics gathered form threads ,
 * also accumulates statistic from dead threads which were alive when when gathering of performance measurements is started .
 * @ return Aggregated write cache performance statistic */
private WritCacheCountersHolder fetchWriteCacheCounters ( ) { } }

implementation:
// go through all threads and accumulate statistic only for live threads
// all dead threads will be removed and statistics from them will be
// later accumulated in # deadThreadsStatistic field , then result statistic from this field
// will be aggregated to countersHolder
// To decrease inter thread communication delay we fetch snapshots first
// and only after that we aggregate data from immutable snapshots
final Collection < ORawPair < Thread , PerformanceSnapshot > > snapshots = new ArrayList < > ( statistics . size ( ) ) ; final Collection < Thread > threadsToRemove = new ArrayList < > ( ) ; for ( Map . Entry < Thread , OSessionStoragePerformanceStatistic > entry : statistics . entrySet ( ) ) { final Thread thread = entry . getKey ( ) ; final OSessionStoragePerformanceStatistic statistic = entry . getValue ( ) ; snapshots . add ( new ORawPair < > ( thread , statistic . getSnapshot ( ) ) ) ; } WritCacheCountersHolder holder = null ; for ( ORawPair < Thread , PerformanceSnapshot > pair : snapshots ) { final Thread thread = pair . getFirst ( ) ; if ( thread . isAlive ( ) ) { final PerformanceSnapshot snapshot = pair . getSecond ( ) ; if ( snapshot . writCacheCountersHolder != null ) { if ( holder == null ) holder = new WritCacheCountersHolder ( ) ; snapshot . writCacheCountersHolder . pushData ( holder ) ; } } else { threadsToRemove . add ( thread ) ; } } if ( ! threadsToRemove . isEmpty ( ) ) { updateDeadThreadsStatistic ( threadsToRemove ) ; } final ImmutableStatistic ds = deadThreadsStatistic ; if ( ds != null ) { final WritCacheCountersHolder wch = ds . writCacheCountersHolder ; if ( wch != null ) { if ( holder == null ) holder = new WritCacheCountersHolder ( ) ; wch . pushData ( holder ) ; } } return holder ;


signature:
public class OPerformanceStatisticManager { /** * Iterates over all live threads and accumulates performance statics gathered form threads on system level ,
 * also accumulates statistic from dead threads which were alive when when gathering of performance measurements is started .
 * @ param countersHolder Holder which is used to accumulate all performance statistic data */
private void fetchSystemCounters ( PerformanceCountersHolder countersHolder ) { } }

implementation:
// go through all threads and accumulate statistic only for live threads
// all dead threads will be removed and statistics from them will be
// later accumulated in # deadThreadsStatistic field , then result statistic from this field
// will be aggregated to countersHolder
// To decrease inter thread communication delay we fetch snapshots first
// and only after that we aggregate data from immutable snapshots
final Collection < ORawPair < Thread , PerformanceSnapshot > > snapshots = new ArrayList < > ( statistics . size ( ) ) ; final Collection < Thread > threadsToRemove = new ArrayList < > ( ) ; for ( Map . Entry < Thread , OSessionStoragePerformanceStatistic > entry : statistics . entrySet ( ) ) { final Thread thread = entry . getKey ( ) ; final OSessionStoragePerformanceStatistic statistic = entry . getValue ( ) ; snapshots . add ( new ORawPair < > ( thread , statistic . getSnapshot ( ) ) ) ; } for ( ORawPair < Thread , PerformanceSnapshot > pair : snapshots ) { final Thread thread = pair . getFirst ( ) ; if ( thread . isAlive ( ) ) { final PerformanceSnapshot snapshot = pair . getSecond ( ) ; snapshot . performanceCountersHolder . pushData ( countersHolder ) ; } else { threadsToRemove . add ( thread ) ; } } if ( ! threadsToRemove . isEmpty ( ) ) { updateDeadThreadsStatistic ( threadsToRemove ) ; } final ImmutableStatistic ds = deadThreadsStatistic ; if ( ds != null ) { final PerformanceCountersHolder dch = ds . countersHolder ; dch . pushData ( countersHolder ) ; }


signature:
public class OPerformanceStatisticManager { /** * Iterates over all live threads and accumulates performance statics gathered form threads for provided component ,
 * also accumulates statistic from dead threads which were alive when when gathering of performance measurements is started .
 * @ param componentCountersHolder Holder which is used to accumulate all performance statistic data for given component
 * @ param componentName Name of component */
private void fetchComponentCounters ( String componentName , PerformanceCountersHolder componentCountersHolder ) { } }

implementation:
// go through all threads and accumulate statistic only for live threads
// all dead threads will be removed and statistics from them will be
// later accumulated in # deadThreadsStatistic field , then result statistic from this field
// will be aggregated to componentCountersHolder
// To decrease inter thread communication delay we fetch snapshots first
// and only after that we aggregate data from immutable snapshots
final Collection < ORawPair < Thread , PerformanceSnapshot > > snapshots = new ArrayList < > ( statistics . size ( ) ) ; final List < Thread > threadsToRemove = new ArrayList < > ( ) ; for ( Map . Entry < Thread , OSessionStoragePerformanceStatistic > entry : statistics . entrySet ( ) ) { final Thread thread = entry . getKey ( ) ; final OSessionStoragePerformanceStatistic statistic = entry . getValue ( ) ; snapshots . add ( new ORawPair < > ( thread , statistic . getSnapshot ( ) ) ) ; } for ( ORawPair < Thread , PerformanceSnapshot > pair : snapshots ) { final Thread thread = pair . getFirst ( ) ; if ( thread . isAlive ( ) ) { final PerformanceSnapshot snapshot = pair . getSecond ( ) ; final PerformanceCountersHolder holder = snapshot . countersByComponent . get ( componentName ) ; if ( holder != null ) holder . pushData ( componentCountersHolder ) ; } else { threadsToRemove . add ( thread ) ; } } if ( ! threadsToRemove . isEmpty ( ) ) { updateDeadThreadsStatistic ( threadsToRemove ) ; } final ImmutableStatistic ds = deadThreadsStatistic ; if ( ds != null ) { final PerformanceCountersHolder dch = ds . countersByComponents . get ( componentName ) ; if ( dch != null ) { dch . pushData ( componentCountersHolder ) ; } }


signature:
public class OPerformanceStatisticManager { /** * Removes provided dead threads from { @ link # statistics } field and accumulates data from them in { @ link # deadThreadsStatistic } .
 * @ param threadsToRemove Dead threads statistic of which should be moved to { @ link # deadThreadsStatistic } field . */
private void updateDeadThreadsStatistic ( Collection < Thread > threadsToRemove ) { } }

implementation:
deadThreadsUpdateLock . lock ( ) ; try { // we accumulate all statistic in intermediate fields and only then put
// results in # deadThreadsStatistic field to preserve thread safety features
final ImmutableStatistic oldDS = deadThreadsStatistic ; final PerformanceCountersHolder countersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; final Map < String , PerformanceCountersHolder > countersByComponents = new HashMap < > ( ) ; WritCacheCountersHolder writeCacheCountersHolder = null ; StorageCountersHolder storageCountersHolder = null ; WALCountersHolder walCountersHolder = null ; // fetch data from old statistic first
if ( oldDS != null ) { oldDS . countersHolder . pushData ( countersHolder ) ; for ( Map . Entry < String , PerformanceCountersHolder > oldEntry : oldDS . countersByComponents . entrySet ( ) ) { final PerformanceCountersHolder holder = oldEntry . getValue ( ) . newInstance ( ) ; oldEntry . getValue ( ) . pushData ( holder ) ; countersByComponents . put ( oldEntry . getKey ( ) , holder ) ; } if ( oldDS . writCacheCountersHolder != null ) { writeCacheCountersHolder = new WritCacheCountersHolder ( ) ; oldDS . writCacheCountersHolder . pushData ( writeCacheCountersHolder ) ; } if ( oldDS . storageCountersHolder != null ) { storageCountersHolder = new StorageCountersHolder ( ) ; oldDS . storageCountersHolder . pushData ( storageCountersHolder ) ; } if ( oldDS . walCountersHolder != null ) { walCountersHolder = new WALCountersHolder ( ) ; oldDS . walCountersHolder . pushData ( walCountersHolder ) ; } } // remove all threads from active statistic and put all in # deadThreadsStatistic field
for ( Thread deadThread : threadsToRemove ) { final OSessionStoragePerformanceStatistic sessionStoragePerformanceStatistic = statistics . remove ( deadThread ) ; if ( sessionStoragePerformanceStatistic != null ) { sessionStoragePerformanceStatistic . pushSystemCounters ( countersHolder ) ; sessionStoragePerformanceStatistic . pushComponentCounters ( countersByComponents ) ; writeCacheCountersHolder = sessionStoragePerformanceStatistic . pushWriteCacheCounters ( writeCacheCountersHolder ) ; storageCountersHolder = sessionStoragePerformanceStatistic . pushStorageCounters ( storageCountersHolder ) ; walCountersHolder = sessionStoragePerformanceStatistic . pushWALCounters ( walCountersHolder ) ; } } deadThreadsStatistic = new ImmutableStatistic ( countersHolder , countersByComponents , writeCacheCountersHolder , storageCountersHolder , walCountersHolder ) ; } finally { deadThreadsUpdateLock . unlock ( ) ; }


signature:
public class OSBTreeBucketSingleValue { /** * Obtains the value stored under the given entry index in this bucket .
 * @ param entryIndex the value entry index .
 * @ return the obtained value . */
public ORID getValue ( final int entryIndex ) { } }

implementation:
assert isLeaf ; int entryPosition = getIntValue ( entryIndex * OIntegerSerializer . INT_SIZE + POSITIONS_ARRAY_OFFSET ) ; // skip key
if ( encryption == null ) { entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedSize = getIntValue ( entryPosition ) ; entryPosition += OIntegerSerializer . INT_SIZE + encryptedSize ; } final int clusterId = getShortValue ( entryPosition ) ; final long clusterPosition = getLongValue ( entryPosition + OShortSerializer . SHORT_SIZE ) ; return new ORecordId ( clusterId , clusterPosition ) ;


signature:
public class OHttpResponse { /** * Compress content string */
public byte [ ] compress ( String jsonStr ) { } }

implementation:
if ( jsonStr == null || jsonStr . length ( ) == 0 ) { return null ; } GZIPOutputStream gout = null ; ByteArrayOutputStream baos = null ; try { byte [ ] incoming = jsonStr . getBytes ( "UTF-8" ) ; baos = new ByteArrayOutputStream ( ) ; gout = new GZIPOutputStream ( baos , 16384 ) ; // 16KB
gout . write ( incoming ) ; gout . finish ( ) ; return baos . toByteArray ( ) ; } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , "Error on compressing HTTP response" , ex ) ; } finally { try { if ( gout != null ) { gout . close ( ) ; } if ( baos != null ) { baos . close ( ) ; } } catch ( Exception ex ) { } } return null ;


signature:
public class OServerConfiguration { /** * Returns the property value configured , if any .
 * @ param iName
 * Property name to find
 * @ param iDefaultValue
 * Default value returned if not found */
public String getProperty ( final String iName , final String iDefaultValue ) { } }

implementation: if ( properties == null ) return null ; for ( OServerEntryConfiguration p : properties ) { if ( p . name . equals ( iName ) ) return p . value ; } return null ;


signature:
public class OObjectDatabaseTx { /** * Create a new POJO by its class name . Assure to have called the registerEntityClasses ( ) declaring the packages that are part of
 * entity classes .
 * @ see OEntityManager # registerEntityClasses ( String ) */
public < RET extends Object > RET newInstance ( final String iClassName , final Object iEnclosingClass , Object ... iArgs ) { } }

implementation: underlying . checkIfActive ( ) ; checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_CREATE , iClassName ) ; try { Class < ? > entityClass = entityManager . getEntityClass ( iClassName ) ; if ( entityClass != null ) { RET enhanced = ( RET ) OObjectEntityEnhancer . getInstance ( ) . getProxiedInstance ( entityManager . getEntityClass ( iClassName ) , iEnclosingClass , underlying . newInstance ( iClassName ) , null , iArgs ) ; return ( RET ) enhanced ; } else { throw new OSerializationException ( "Type " + iClassName + " cannot be serialized because is not part of registered entities. To fix this error register this class" ) ; } } catch ( Exception e ) { final String message = "Error on creating object of class " + iClassName ; OLogManager . instance ( ) . error ( this , message , e ) ; throw OException . wrapException ( new ODatabaseException ( message ) , e ) ; }


signature:
public class OObjectDatabaseTx { /** * Method that detaches all fields contained in the document to the given object .
 * @ param < RET >
 * @ param iPojo : - the object to detach
 * @ param returnNonProxiedInstance : - defines if the return object will be a proxied instance or not . If set to TRUE and the
 * object does not contains @ Id and @ Version fields it could procude data replication
 * @ return the object serialized or with detached data */
public < RET > RET detach ( final Object iPojo , boolean returnNonProxiedInstance ) { } }

implementation: return ( RET ) OObjectEntitySerializer . detach ( iPojo , this , returnNonProxiedInstance ) ;


signature:
public class OObjectDatabaseTx { /** * Method that detaches all fields contained in the document to the given object and recursively all object tree . This may throw a
 * { @ link StackOverflowError } with big objects tree . To avoid it set the stack size with - Xss java option
 * @ param < RET >
 * @ param iPojo : - the object to detach
 * @ param returnNonProxiedInstance : - defines if the return object will be a proxied instance or not . If set to TRUE and the
 * object does not contains @ Id and @ Version fields it could procude data replication
 * @ return the object serialized or with detached data */
public < RET > RET detachAll ( final Object iPojo , boolean returnNonProxiedInstance ) { } }

implementation: return detachAll ( iPojo , returnNonProxiedInstance , new HashMap < Object , Object > ( ) , new HashMap < Object , Object > ( ) ) ;


signature:
public class OObjectDatabaseTx { /** * Saves an object to the database specifying the mode . First checks if the object is new or not . In case it ' s new a new ODocument
 * is created and bound to the object , otherwise the ODocument is retrieved and updated . The object is introspected using the Java
 * Reflection to extract the field values . < br > If a multi value ( array , collection or map of objects ) is passed , then each single
 * object is stored separately . */
public < RET > RET save ( final Object iContent , OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { } }

implementation: return ( RET ) save ( iContent , null , iMode , false , iRecordCreatedCallback , iRecordUpdatedCallback ) ;


signature:
public class OObjectDatabaseTx { /** * Saves an object in synchronous mode to the database forcing a record cluster where to store it . First checks if the object is
 * new or not . In case it ' s new a new ODocument is created and bound to the object , otherwise the ODocument is retrieved and
 * updated . The object is introspected using the Java Reflection to extract the field values . < br > If a multi value ( array ,
 * collection or map of objects ) is passed , then each single object is stored separately .
 * Before to use the specified cluster a check is made to know if is allowed and figures in the configured and the record is valid
 * following the constraints declared in the schema .
 * @ see ODocument # validate ( ) */
public < RET > RET save ( final Object iPojo , final String iClusterName ) { } }

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


signature:
public class OObjectDatabaseTx { /** * Saves an object to the database forcing a record cluster where to store it . First checks if the object is new or not . In case
 * it ' s new a new ODocument is created and bound to the object , otherwise the ODocument is retrieved and updated . The object is
 * introspected using the Java Reflection to extract the field values . < br > If a multi value ( array , collection or map of objects )
 * is passed , then each single object is stored separately .
 * Before to use the specified cluster a check is made to know if is allowed and figures in the configured and the record is valid
 * following the constraints declared in the schema .
 * @ see ODocument # validate ( ) */
public < RET > RET save ( final Object iPojo , final String iClusterName , OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { } }

implementation:
checkOpenness ( ) ; if ( iPojo == null ) return ( RET ) iPojo ; else if ( OMultiValue . isMultiValue ( iPojo ) ) { // MULTI VALUE OBJECT : STORE SINGLE POJOS
for ( Object pojo : OMultiValue . getMultiValueIterable ( iPojo ) ) { save ( pojo , iClusterName ) ; } return ( RET ) iPojo ; } else { OSerializationThreadLocal . INSTANCE . get ( ) . clear ( ) ; // GET THE ASSOCIATED DOCUMENT
final Object proxiedObject = OObjectEntitySerializer . serializeObject ( iPojo , this ) ; final ODocument record = getRecordByUserObject ( proxiedObject , true ) ; try { record . setInternalStatus ( ORecordElement . STATUS . MARSHALLING ) ; if ( ! saveOnlyDirty || record . isDirty ( ) ) { // REGISTER BEFORE TO SERIALIZE TO AVOID PROBLEMS WITH CIRCULAR DEPENDENCY
// registerUserObject ( iPojo , record ) ;
deleteOrphans ( ( ( ( OObjectProxyMethodHandler ) ( ( ProxyObject ) proxiedObject ) . getHandler ( ) ) ) ) ; ODocument savedRecord = underlying . save ( record , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; ( ( OObjectProxyMethodHandler ) ( ( ProxyObject ) proxiedObject ) . getHandler ( ) ) . setDoc ( savedRecord ) ; ( ( OObjectProxyMethodHandler ) ( ( ProxyObject ) proxiedObject ) . getHandler ( ) ) . updateLoadedFieldMap ( proxiedObject , false ) ; // RE - REGISTER FOR NEW RECORDS SINCE THE ID HAS CHANGED
registerUserObject ( proxiedObject , record ) ; } } finally { record . setInternalStatus ( ORecordElement . STATUS . LOADED ) ; } return ( RET ) proxiedObject ; }


signature:
public class OObjectDatabaseTx { /** * Returns the version number of the object . Version starts from 0 assigned on creation .
 * @ param iPojo User object */
public int getVersion ( final Object iPojo ) { } }

implementation: checkOpenness ( ) ; final ODocument record = getRecordByUserObject ( iPojo , false ) ; if ( record != null ) return record . getVersion ( ) ; return OObjectSerializerHelper . getObjectVersion ( iPojo ) ;


signature:
public class OObjectDatabaseTx { /** * Register the static document binary mapping mode in the database context ( only if it ' s not already set ) */
private void registerFieldMappingStrategy ( ) { } }

implementation: if ( ! this . getConfiguration ( ) . getContextKeys ( ) . contains ( OGlobalConfiguration . DOCUMENT_BINARY_MAPPING . getKey ( ) ) ) { this . getConfiguration ( ) . setValue ( OGlobalConfiguration . DOCUMENT_BINARY_MAPPING , OGlobalConfiguration . DOCUMENT_BINARY_MAPPING . getValueAsInteger ( ) ) ; }


signature:
public class OObjectDatabaseTx { /** * Returns a wrapped OCommandRequest instance to catch the result - set by converting it before to return to the user application . */
public < RET extends OCommandRequest > RET command ( final OCommandRequest iCommand ) { } }

implementation: return ( RET ) new OCommandSQLPojoWrapper ( this , underlying . command ( iCommand ) ) ;


signature:
public class OObjectDatabaseTx { /** * Converts an array of parameters : if a POJO is used , then replace it with its record id .
 * @ param iArgs Array of parameters as Object
 * @ see # convertParameter ( Object ) */
protected void convertParameters ( final Object ... iArgs ) { } }

implementation:
if ( iArgs == null ) return ; // FILTER PARAMETERS
for ( int i = 0 ; i < iArgs . length ; ++ i ) iArgs [ i ] = convertParameter ( iArgs [ i ] ) ;


signature:
public class OObjectDatabaseTx { /** * Sets as dirty a POJO . This is useful when you change the object and need to tell to the engine to treat as dirty .
 * @ param iPojo User object */
public void setDirty ( final Object iPojo ) { } }

implementation: if ( iPojo == null ) return ; final ODocument record = getRecordByUserObject ( iPojo , false ) ; if ( record == null ) throw new OObjectNotManagedException ( "The object " + iPojo + " is not managed by current database" ) ; record . setDirty ( ) ;


signature:
public class OObjectDatabaseTx { /** * Sets as not dirty a POJO . This is useful when you change some other object and need to tell to the engine to treat this one as
 * not dirty .
 * @ param iPojo User object */
public void unsetDirty ( final Object iPojo ) { } }

implementation: if ( iPojo == null ) return ; final ODocument record = getRecordByUserObject ( iPojo , false ) ; if ( record == null ) return ; ORecordInternal . unsetDirty ( record ) ;


signature:
public class OObjectDatabaseTx { /** * Convert a parameter : if a POJO is used , then replace it with its record id .
 * @ param iParameter Parameter to convert , if applicable
 * @ see # convertParameters ( Object . . . ) */
protected Object convertParameter ( final Object iParameter ) { } }

implementation:
if ( iParameter != null ) // FILTER PARAMETERS
if ( iParameter instanceof Map < ? , ? > ) { Map < String , Object > map = ( Map < String , Object > ) iParameter ; for ( Map . Entry < String , Object > e : map . entrySet ( ) ) { map . put ( e . getKey ( ) , convertParameter ( e . getValue ( ) ) ) ; } return map ; } else if ( iParameter instanceof Collection < ? > ) { List < Object > result = new ArrayList < Object > ( ) ; for ( Object object : ( Collection < Object > ) iParameter ) { result . add ( convertParameter ( object ) ) ; } return result ; } else if ( iParameter . getClass ( ) . isEnum ( ) ) { return ( ( Enum < ? > ) iParameter ) . name ( ) ; } else if ( ! OType . isSimpleType ( iParameter ) ) { final ORID rid = getIdentity ( iParameter ) ; if ( rid != null && rid . isValid ( ) ) // REPLACE OBJECT INSTANCE WITH ITS RECORD ID
return rid ; } return iParameter ;


signature:
public class OIndexes { /** * Iterates on all factories and append all index types .
 * @ return Set of all index types . */
private static Set < String > getIndexTypes ( ) { } }

implementation: final Set < String > types = new HashSet < > ( ) ; final Iterator < OIndexFactory > ite = getAllFactories ( ) ; while ( ite . hasNext ( ) ) { types . addAll ( ite . next ( ) . getTypes ( ) ) ; } return types ;


signature:
public class OIndexes { /** * Iterates on all factories and append all index engines .
 * @ return Set of all index engines . */
public static Set < String > getIndexEngines ( ) { } }

implementation: final Set < String > engines = new HashSet < > ( ) ; final Iterator < OIndexFactory > ite = getAllFactories ( ) ; while ( ite . hasNext ( ) ) { engines . addAll ( ite . next ( ) . getAlgorithms ( ) ) ; } return engines ;


signature:
public class OIndexes { /** * @ param storage TODO
 * @ param indexType index type
 * @ return OIndexInternal
 * @ throws OConfigurationException if index creation failed
 * @ throws OIndexException if index type does not exist */
public static OIndexInternal < ? > createIndex ( OStorage storage , String name , String indexType , String algorithm , String valueContainerAlgorithm , ODocument metadata , int version ) throws OConfigurationException , OIndexException { } }

implementation: if ( indexType . equalsIgnoreCase ( OClass . INDEX_TYPE . UNIQUE_HASH_INDEX . name ( ) ) || indexType . equalsIgnoreCase ( OClass . INDEX_TYPE . NOTUNIQUE_HASH_INDEX . name ( ) ) || indexType . equalsIgnoreCase ( OClass . INDEX_TYPE . DICTIONARY_HASH_INDEX . name ( ) ) ) { if ( ! algorithm . equalsIgnoreCase ( "autosharding" ) ) { algorithm = OHashIndexFactory . HASH_INDEX_ALGORITHM ; } } return findFactoryByAlgorithmAndType ( algorithm , indexType ) . createIndex ( name , storage , indexType , algorithm , valueContainerAlgorithm , metadata , version ) ;


signature:
public class ODistributedResponseManagerImpl { /** * Not synchronized , it ' s called when a message arrives
 * @ param response Received response to collect
 * @ return True if all the nodes responded , otherwise false */
public boolean collectResponse ( final ODistributedResponse response ) { } }

implementation:
final String executorNode = response . getExecutorNodeName ( ) ; final String senderNode = response . getSenderNodeName ( ) ; response . setDistributedResponseManager ( this ) ; synchronousResponsesLock . lock ( ) ; try { if ( ! executorNode . equals ( dManager . getLocalNodeName ( ) ) && ! responses . containsKey ( executorNode ) ) { ODistributedServerLog . warn ( this , senderNode , executorNode , DIRECTION . IN , "Received response for request (%s) from unexpected node. Expected are: %s" , request , getExpectedNodes ( ) ) ; Orient . instance ( ) . getProfiler ( ) . updateCounter ( "distributed.node.unexpectedNodeResponse" , "Number of responses from unexpected nodes" , + 1 ) ; return false ; } dManager . getMessageService ( ) . updateLatency ( executorNode , sentOn ) ; responses . put ( executorNode , response ) ; receivedResponses ++ ; if ( waitForLocalNode && executorNode . equals ( senderNode ) ) receivedCurrentNode = true ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , senderNode , executorNode , DIRECTION . IN , "Received response '%s' for request (%s) (receivedCurrentNode=%s receivedResponses=%d totalExpectedResponses=%d quorum=%d)" , response , request , receivedCurrentNode , receivedResponses , totalExpectedResponses , quorum ) ; if ( groupResponsesByResult ) { // PUT THE RESPONSE IN THE RIGHT RESPONSE GROUP
// TODO : AVOID TO KEEP ALL THE RESULT FOR THE SAME RESP GROUP , BUT RATHER THE FIRST ONE + COUNTER
final Object responsePayload = response . getPayload ( ) ; boolean foundBucket = false ; for ( int i = 0 ; i < responseGroups . size ( ) ; ++ i ) { final List < ODistributedResponse > responseGroup = responseGroups . get ( i ) ; if ( responseGroup . isEmpty ( ) ) // ABSENT
foundBucket = true ; else { final Object rgPayload = responseGroup . get ( 0 ) . getPayload ( ) ; if ( rgPayload == null && responsePayload == null ) // BOTH NULL
foundBucket = true ; else if ( rgPayload != null ) { if ( rgPayload instanceof ODocument && responsePayload instanceof ODocument && ! ( ( ODocument ) rgPayload ) . getIdentity ( ) . isValid ( ) && ( ( ODocument ) rgPayload ) . hasSameContentOf ( ( ODocument ) responsePayload ) ) // SAME RESULT
foundBucket = true ; else if ( rgPayload . equals ( responsePayload ) ) // SAME RESULT
foundBucket = true ; else if ( rgPayload instanceof Collection && responsePayload instanceof Collection ) { if ( OMultiValue . equals ( ( Collection ) rgPayload , ( Collection ) responsePayload ) ) // COLLECTIONS WITH THE SAME VALUES
foundBucket = true ; } } } if ( foundBucket ) { responseGroup . add ( response ) ; break ; } } if ( ! foundBucket ) { // CREATE A NEW BUCKET
final ArrayList < ODistributedResponse > newBucket = new ArrayList < ODistributedResponse > ( ) ; responseGroups . add ( newBucket ) ; newBucket . add ( response ) ; } } // FOR EVERY RESPONSE COLLECTED , COMPUTE THE FINAL QUORUM RESPONSE IF POSSIBLE
computeQuorumResponse ( false ) ; return checkForCompletion ( ) ; } finally { synchronousResponsesLock . unlock ( ) ; }


signature:
public class ODistributedResponseManagerImpl { /** * @ param localNodeName
 * @ param localResult
 * @ return */
public boolean setLocalResult ( final String localNodeName , final Object localResult ) { } }

implementation: localResponse = new ODistributedResponse ( this , request . getId ( ) , localNodeName , localNodeName , localResult ) ; receivedCurrentNode = true ; return collectResponse ( localResponse ) ;


signature:
public class ODistributedResponseManagerImpl { /** * Waits until the minimum responses are collected or timeout occurs . If " waitForLocalNode " wait also for local node .
 * @ return True if the received responses are major or equals then the expected synchronous responses , otherwise false
 * @ throws InterruptedException */
public boolean waitForSynchronousResponses ( ) throws InterruptedException { } }

implementation:
final long beginTime = System . currentTimeMillis ( ) ; try { boolean reachedTimeout = false ; long currentTimeout = synchTimeout ; while ( currentTimeout > 0 ) { if ( currentTimeout > 10000 ) // CUT THE TIMEOUT IN BLOCKS OF 10S EACH TO ALLOW CHECKING FOR ANY SERVER IF UNREACHABLE
currentTimeout = 10000 ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , "Waiting max %dms for collecting all synchronous responses... (timeout=%d reqId=%s thread=%d)" , currentTimeout , synchTimeout , request . getId ( ) , Thread . currentThread ( ) . getId ( ) ) ; // WAIT FOR THE RESPONSES
if ( synchronousResponsesArrived . await ( currentTimeout , TimeUnit . MILLISECONDS ) ) { if ( canceled . get ( ) ) throw new ODistributedOperationException ( "Request has been canceled" ) ; // COMPLETED
if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , "All synchronous responses collected in %dms (reqId=%s thread=%d)" , ( System . currentTimeMillis ( ) - beginTime ) , request . getId ( ) , Thread . currentThread ( ) . getId ( ) ) ; return true ; } if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , "All synchronous responses not collected in %dms, waiting again... (reqId=%s thread=%d)" , ( System . currentTimeMillis ( ) - beginTime ) , request . getId ( ) , Thread . currentThread ( ) . getId ( ) ) ; if ( Thread . currentThread ( ) . isInterrupted ( ) ) { // INTERRUPTED
ODistributedServerLog . warn ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , "Thread has been interrupted wait for request (%s)" , request ) ; Thread . currentThread ( ) . interrupt ( ) ; break ; } synchronousResponsesLock . lock ( ) ; try { final long now = System . currentTimeMillis ( ) ; final long elapsed = now - beginTime ; if ( elapsed > synchTimeout ) reachedTimeout = true ; currentTimeout = synchTimeout - elapsed ; // CHECK IF ANY NODE ARE UNREACHABLE IN THE MEANWHILE
int synchronizingNodes = 0 ; int missingActiveNodes = 0 ; Map < String , ODistributedServerManager . DB_STATUS > missingResponseNodeStatuses = new HashMap < String , ODistributedServerManager . DB_STATUS > ( responses . size ( ) ) ; int missingResponses = 0 ; for ( Iterator < Map . Entry < String , Object > > iter = responses . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final Map . Entry < String , Object > curr = iter . next ( ) ; if ( curr . getValue ( ) == NO_RESPONSE ) { missingResponses ++ ; // ANALYZE THE NODE WITHOUT A RESPONSE
final ODistributedServerManager . DB_STATUS dbStatus = dManager . getDatabaseStatus ( curr . getKey ( ) , getDatabaseName ( ) ) ; missingResponseNodeStatuses . put ( curr . getKey ( ) , dbStatus ) ; switch ( dbStatus ) { case BACKUP : case SYNCHRONIZING : synchronizingNodes ++ ; missingActiveNodes ++ ; break ; case ONLINE : missingActiveNodes ++ ; break ; } } } if ( missingResponses == 0 ) { // ALL RESPONSE COLLECTED , BUT NO QUORUM REACHED
ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , "All responses collected %s, but no quorum reached (reqId=%s)" , responses , request . getId ( ) ) ; break ; } request . getTask ( ) . checkIsValid ( dManager ) ; if ( missingActiveNodes == 0 ) { // NO MORE ACTIVE NODES TO WAIT
ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , "No more active nodes to wait for request (%s): anticipate timeout (saved %d ms). Missing servers: %s" , request , currentTimeout , missingResponseNodeStatuses ) ; break ; } final long lastClusterChange = dManager . getLastClusterChangeOn ( ) ; if ( lastClusterChange > 0 && now - lastClusterChange < ( synchTimeout + ADDITIONAL_TIMEOUT_CLUSTER_SHAPE ) ) { // CHANGED CLUSTER SHAPE DURING WAIT : ENLARGE TIMEOUT
currentTimeout = synchTimeout ; ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , "Cluster shape changed during request (%s): enlarge timeout +%dms, wait again for %dms" , request , synchTimeout , currentTimeout ) ; continue ; } else if ( synchronizingNodes > 0 ) { // SOME NODE IS SYNCHRONIZING : WAIT FOR THEM
// currentTimeout = synchTimeout ;
// ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE ,
// " % d nodes are in synchronization mode during request ( % s ) : enlarge timeout + % dms , wait again for % dms " ,
// synchronizingNodes , request , synchTimeout , currentTimeout ) ;
} } finally { synchronousResponsesLock . unlock ( ) ; } } if ( canceled . get ( ) ) throw new ODistributedOperationException ( "Request has been canceled" ) ; return isMinimumQuorumReached ( reachedTimeout ) ; } finally { Orient . instance ( ) . getProfiler ( ) . stopChrono ( "distributed.synchResponses" , "Time to collect all the synchronous responses from distributed nodes" , beginTime ) ; }


signature:
public class ODistributedResponseManagerImpl { /** * Returns the list of node names that didn ' t provide a response . */
public List < String > getMissingNodes ( ) { } }

implementation: synchronousResponsesLock . lock ( ) ; try { final List < String > missingNodes = new ArrayList < String > ( ) ; for ( Map . Entry < String , Object > entry : responses . entrySet ( ) ) if ( entry . getValue ( ) == NO_RESPONSE ) missingNodes . add ( entry . getKey ( ) ) ; return missingNodes ; } finally { synchronousResponsesLock . unlock ( ) ; }


signature:
public class ODistributedResponseManagerImpl { /** * Returns all the responses in conflict . */
protected List < ODistributedResponse > getConflictResponses ( ) { } }

implementation: final List < ODistributedResponse > servers = new ArrayList < ODistributedResponse > ( ) ; int bestGroupSoFar = getBestResponsesGroup ( ) ; for ( int i = 0 ; i < responseGroups . size ( ) ; ++ i ) { if ( i != bestGroupSoFar ) { for ( ODistributedResponse r : responseGroups . get ( i ) ) servers . add ( r ) ; } } return servers ;


signature:
public class ODistributedResponseManagerImpl { /** * Returns the biggest response group .
 * @ return */
protected int getBestResponsesGroup ( ) { } }

implementation: int maxCoherentResponses = 0 ; int bestGroupSoFar = 0 ; for ( int i = 0 ; i < responseGroups . size ( ) ; ++ i ) { final int currentGroupSize = responseGroups . get ( i ) . size ( ) ; if ( currentGroupSize > maxCoherentResponses ) { maxCoherentResponses = currentGroupSize ; bestGroupSoFar = i ; } } return bestGroupSoFar ;


signature:
public class ODistributedResponseManagerImpl { /** * Computes the quorum response if possible by returning true and setting the field quorumResponse with the ODistributedResponse . */
private boolean computeQuorumResponse ( boolean reachedTimeout ) { } }

implementation:
if ( quorumResponse != null ) // ALREADY COMPUTED
return true ; if ( groupResponsesByResult ) { for ( List < ODistributedResponse > group : responseGroups ) { if ( group . size ( ) >= quorum ) { int responsesForQuorum = 0 ; for ( ODistributedResponse r : group ) { if ( nodesConcurInQuorum . contains ( r . getExecutorNodeName ( ) ) ) { final Object payload = r . getPayload ( ) ; if ( payload instanceof Throwable ) { if ( payload instanceof ODistributedRecordLockedException ) // JUST ONE ODistributedRecordLockedException IS ENOUGH TO FAIL THE OPERATION BECAUSE RESOURCES CANNOT BE LOCKED
break ; if ( payload instanceof OConcurrentCreateException ) // JUST ONE OConcurrentCreateException IS ENOUGH TO FAIL THE OPERATION BECAUSE RID ARE DIFFERENT
break ; } else if ( ++ responsesForQuorum >= quorum ) { // QUORUM REACHED
setQuorumResponse ( r ) ; return true ; } } } } } } else { if ( receivedResponses >= quorum ) { int responsesForQuorum = 0 ; for ( Map . Entry < String , Object > response : responses . entrySet ( ) ) { if ( response . getValue ( ) != NO_RESPONSE && nodesConcurInQuorum . contains ( response . getKey ( ) ) && ++ responsesForQuorum >= quorum ) { // QUORUM REACHED
ODistributedResponse resp = ( ODistributedResponse ) response . getValue ( ) ; if ( resp != null && ! ( resp . getPayload ( ) instanceof Throwable ) ) setQuorumResponse ( resp ) ; return true ; } } } } return false ;


signature:
public class ODistributedResponseManagerImpl { /** * Returns the received response objects . */
protected List < ODistributedResponse > getReceivedResponses ( ) { } }

implementation: final List < ODistributedResponse > parsed = new ArrayList < ODistributedResponse > ( ) ; for ( Object r : responses . values ( ) ) if ( r != NO_RESPONSE ) parsed . add ( ( ODistributedResponse ) r ) ; return parsed ;


signature:
public class OExecutionPlanCache { /** * returns an already prepared SQL execution plan , taking it from the cache if it exists or creating a new one if it doesn ' t
 * @ param statement the SQL statement
 * @ param ctx
 * @ param db the current DB instance
 * @ return a statement executor from the cache */
public static OExecutionPlan get ( String statement , OCommandContext ctx , ODatabaseDocumentInternal db ) { } }

implementation: if ( db == null ) { throw new IllegalArgumentException ( "DB cannot be null" ) ; } if ( statement == null ) { return null ; } OExecutionPlanCache resource = db . getSharedContext ( ) . getExecutionPlanCache ( ) ; OExecutionPlan result = resource . getInternal ( statement , ctx , db ) ; return result ;


signature:
public class OExecutionPlanCache { /** * @ param statement an SQL statement
 * @ param ctx
 * @ return the corresponding executor , taking it from the internal cache , if it exists */
public OExecutionPlan getInternal ( String statement , OCommandContext ctx , ODatabaseDocumentInternal db ) { } }

implementation:
OInternalExecutionPlan result ; if ( statement == null ) { return null ; } synchronized ( map ) { // LRU
result = map . remove ( statement ) ; if ( result != null ) { map . put ( statement , result ) ; result = result . copy ( ctx ) ; } } return result ;


signature:
public class OExpression { /** * if the condition involved the current pattern ( MATCH statement , eg . $ matched . something = foo ) , returns the name of involved
 * pattern aliases ( " something " in this case )
 * @ return a list of pattern aliases involved in this condition . Null it does not involve the pattern */
List < String > getMatchPatternInvolvedAliases ( ) { } }

implementation: if ( mathExpression != null ) return mathExpression . getMatchPatternInvolvedAliases ( ) ; if ( arrayConcatExpression != null ) return arrayConcatExpression . getMatchPatternInvolvedAliases ( ) ; return null ;


signature:
public class OBinaryCondition { /** * tests if current expression involves an indexed function AND that function can be used on this target
 * @ param target the query target
 * @ param context the execution context
 * @ return true if current expression involves an indexed function AND that function can be used on this target , false otherwise */
public boolean allowsIndexedFunctionExecutionOnTarget ( OFromClause target , OCommandContext context ) { } }

implementation: return left . allowsIndexedFunctionExecutionOnTarget ( target , context , operator , right . execute ( ( OResult ) null , context ) ) ;


signature:
public class OScriptManager { /** * Formats the library of functions for a language .
 * @ param db Current database instance
 * @ param iLanguage Language as filter
 * @ return String containing all the functions */
public String getLibrary ( final ODatabase < ? > db , final String iLanguage ) { } }

implementation:
if ( db == null ) // NO DB = NO LIBRARY
return null ; final StringBuilder code = new StringBuilder ( ) ; final Set < String > functions = db . getMetadata ( ) . getFunctionLibrary ( ) . getFunctionNames ( ) ; for ( String fName : functions ) { final OFunction f = db . getMetadata ( ) . getFunctionLibrary ( ) . getFunction ( fName ) ; if ( f . getLanguage ( ) == null ) throw new OConfigurationException ( "Database function '" + fName + "' has no language" ) ; if ( f . getLanguage ( ) . equalsIgnoreCase ( iLanguage ) ) { final String def = getFunctionDefinition ( f ) ; if ( def != null ) { code . append ( def ) ; code . append ( "\n" ) ; } } } return code . length ( ) == 0 ? null : code . toString ( ) ;


signature:
public class OScriptManager { /** * Acquires a database engine from the pool . Once finished using it , the instance MUST be returned in the pool by calling the
 * method # releaseDatabaseEngine ( String , ScriptEngine ) .
 * @ param databaseName Database name
 * @ param language Script language
 * @ return ScriptEngine instance with the function library already parsed
 * @ see # releaseDatabaseEngine ( String , String , OPartitionedObjectPool . PoolEntry ) */
public OPartitionedObjectPool . PoolEntry < ScriptEngine > acquireDatabaseEngine ( final String databaseName , final String language ) { } }

implementation:
ODatabaseScriptManager dbManager = dbManagers . get ( databaseName ) ; if ( dbManager == null ) { // CREATE A NEW DATABASE SCRIPT MANAGER
dbManager = new ODatabaseScriptManager ( this , databaseName ) ; final ODatabaseScriptManager prev = dbManagers . putIfAbsent ( databaseName , dbManager ) ; if ( prev != null ) { dbManager . close ( ) ; // GET PREVIOUS ONE
dbManager = prev ; } } return dbManager . acquireEngine ( language ) ;


signature:
public class OScriptManager { /** * Acquires a database engine from the pool . Once finished using it , the instance MUST be returned in the pool by calling the
 * method
 * @ param iLanguage Script language
 * @ param iDatabaseName Database name
 * @ param poolEntry Pool entry to free
 * @ see # acquireDatabaseEngine ( String , String ) */
public void releaseDatabaseEngine ( final String iLanguage , final String iDatabaseName , final OPartitionedObjectPool . PoolEntry < ScriptEngine > poolEntry ) { } }

implementation:
final ODatabaseScriptManager dbManager = dbManagers . get ( iDatabaseName ) ; // We check if there is still a valid pool because it could be removed by the function reload
if ( dbManager != null ) { dbManager . releaseEngine ( iLanguage , poolEntry ) ; }


signature:
public class OClusterPositionMapV0 { /** * Returns the next position available . */
long getNextPosition ( final OAtomicOperation atomicOperation ) throws IOException { } }

implementation: final long filledUpTo = getFilledUpTo ( atomicOperation , fileId ) ; final long pageIndex = filledUpTo - 1 ; final OCacheEntry cacheEntry = loadPageForRead ( atomicOperation , fileId , pageIndex , false , 1 ) ; try { final OClusterPositionMapBucket bucket = new OClusterPositionMapBucket ( cacheEntry , false ) ; final int bucketSize = bucket . getSize ( ) ; return pageIndex * OClusterPositionMapBucket . MAX_ENTRIES + bucketSize ; } finally { releasePageFromRead ( atomicOperation , cacheEntry ) ; }


signature:
public class OSBTreeRidBag { /** * Recalculates real bag size .
 * @ return real size */
private int updateSize ( ) { } }

implementation: int size = 0 ; if ( collectionPointer != null ) { final OSBTreeBonsai < OIdentifiable , Integer > tree = loadTree ( ) ; if ( tree == null ) { throw new IllegalStateException ( "RidBag is not properly initialized, can not load tree implementation" ) ; } try { size = tree . getRealBagSize ( changes ) ; } finally { releaseTree ( ) ; } } else { for ( Change change : changes . values ( ) ) { size += change . applyTo ( 0 ) ; } } for ( OModifiableInteger diff : newEntries . values ( ) ) { size += diff . getValue ( ) ; } this . size = size ; return size ;


signature:
public class OSBTreeRidBag { /** * Removes entry with given key from { @ link # newEntries } .
 * @ param identifiable key to remove
 * @ return true if entry have been removed */
private boolean removeFromNewEntries ( final OIdentifiable identifiable ) { } }

implementation: OModifiableInteger counter = newEntries . get ( identifiable ) ; if ( counter == null ) { return false ; } else { if ( counter . getValue ( ) == 1 ) { newEntries . remove ( identifiable ) ; } else { counter . decrement ( ) ; } return true ; }


signature:
public class FetchFromIndexStep { /** * it ' s not key = [ . . . ] but a real condition on field names , already ordered ( field names will be ignored ) */
private void processAndBlock ( ) { } }

implementation: OCollection fromKey = indexKeyFrom ( ( OAndBlock ) condition , additionalRangeCondition ) ; OCollection toKey = indexKeyTo ( ( OAndBlock ) condition , additionalRangeCondition ) ; boolean fromKeyIncluded = indexKeyFromIncluded ( ( OAndBlock ) condition , additionalRangeCondition ) ; boolean toKeyIncluded = indexKeyToIncluded ( ( OAndBlock ) condition , additionalRangeCondition ) ; init ( fromKey , fromKeyIncluded , toKey , toKeyIncluded ) ;


signature:
public class FetchFromIndexStep { /** * this is for subqueries , when a OResult is found < ul > < li > if it ' s a projection with a single column , the value is returned < / li >
 * < li > if it ' s a document , the RID is returned < / li > < / ul >
 * @ param value
 * @ return */
private Object unboxOResult ( Object value ) { } }

implementation: if ( value instanceof List ) { return ( ( List ) value ) . stream ( ) . map ( x -> unboxOResult ( x ) ) . collect ( Collectors . toList ( ) ) ; } if ( value instanceof OResult ) { if ( ( ( OResult ) value ) . isElement ( ) ) { return ( ( OResult ) value ) . getIdentity ( ) . orElse ( null ) ; } Set < String > props = ( ( OResult ) value ) . getPropertyNames ( ) ; if ( props . size ( ) == 1 ) { return ( ( OResult ) value ) . getProperty ( props . iterator ( ) . next ( ) ) ; } } return value ;


signature:
public class OHashIndexBucket { /** * Obtains the value stored under the given index in this bucket .
 * @ param index the value index .
 * @ return the obtained value . */
public V getValue ( int index ) { } }

implementation:
int entryPosition = getIntValue ( POSITIONS_ARRAY_OFFSET + index * OIntegerSerializer . INT_SIZE ) ; // skip hash code
entryPosition += OLongSerializer . LONG_SIZE ; if ( encryption == null ) { // skip key
entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedLength = getIntValue ( entryPosition ) ; entryPosition += encryptedLength + OIntegerSerializer . INT_SIZE ; } return deserializeFromDirectMemory ( valueSerializer , entryPosition ) ;


signature:
public class OOrderByOptimizer { /** * checks if , given a list of " = " conditions and a set of ORDER BY fields
 * @ param index
 * @ param equalsFilterFields
 * @ param orderedFields
 * @ return */
boolean canBeUsedByOrderByAfterFilter ( OIndex < ? > index , List < String > equalsFilterFields , List < OPair < String , String > > orderedFields ) { } }

implementation:
if ( orderedFields . isEmpty ( ) ) return false ; if ( ! index . supportsOrderedIterations ( ) ) return false ; final OIndexDefinition definition = index . getDefinition ( ) ; final List < String > indexFields = definition . getFields ( ) ; int endIndex = Math . min ( indexFields . size ( ) , equalsFilterFields . size ( ) ) ; final String firstOrder = orderedFields . get ( 0 ) . getValue ( ) ; // check that all the " equals " clauses are a prefix for the index
for ( int i = 0 ; i < endIndex ; i ++ ) { final String equalsFieldName = equalsFilterFields . get ( i ) ; final String indexFieldName = indexFields . get ( i ) ; if ( ! equalsFieldName . equals ( indexFieldName ) ) return false ; } endIndex = Math . min ( indexFields . size ( ) , orderedFields . size ( ) + equalsFilterFields . size ( ) ) ; if ( endIndex == equalsFilterFields . size ( ) ) { // the index is used only for filtering
return false ; } // check that after that prefix there all the Order By fields in the right order
for ( int i = equalsFilterFields . size ( ) ; i < endIndex ; i ++ ) { int fieldOrderInOrderByClause = i - equalsFilterFields . size ( ) ; final OPair < String , String > pair = orderedFields . get ( fieldOrderInOrderByClause ) ; if ( ! firstOrder . equals ( pair . getValue ( ) ) ) return false ; final String orderFieldName = pair . getKey ( ) ; final String indexFieldName = indexFields . get ( i ) ; if ( ! orderFieldName . equals ( indexFieldName ) ) return false ; } return true ;


signature:
public class OStringParser { /** * Finds a character inside a string specyfing the limits and direction . If iFrom is minor than iTo , then it moves forward ,
 * otherwise backward . */
public static int indexOfOutsideStrings ( final String iText , final char iToFind , int iFrom , int iTo ) { } }

implementation:
if ( iTo == - 1 ) iTo = iText . length ( ) - 1 ; if ( iFrom == - 1 ) iFrom = iText . length ( ) - 1 ; char c ; char stringChar = ' ' ; boolean escape = false ; final StringBuilder buffer = new StringBuilder ( 1024 ) ; int i = iFrom ; while ( true ) { c = iText . charAt ( i ) ; if ( ! escape && c == '\\' && ( ( i + 1 ) < iText . length ( ) ) ) { if ( iText . charAt ( i + 1 ) == 'u' ) { i = readUnicode ( iText , i + 2 , buffer ) ; } else escape = true ; } else { if ( c == '\'' || c == '"' ) { // BEGIN / END STRING
if ( stringChar == ' ' ) { // BEGIN
stringChar = c ; } else { // END
if ( ! escape && c == stringChar ) stringChar = ' ' ; } } if ( c == iToFind && stringChar == ' ' ) return i ; if ( escape ) escape = false ; } if ( iFrom < iTo ) { // MOVE FORWARD
if ( ++ i > iTo ) break ; } else { // MOVE BACKWARD
if ( -- i < iFrom ) break ; } } return - 1 ;


signature:
public class OStringParser { /** * Jump white spaces .
 * @ param iText
 * String to analyze
 * @ param iCurrentPosition
 * Current position in text
 * @ param iMaxPosition
 * TODO
 * @ return The new offset inside the string analyzed */
public static int jumpWhiteSpaces ( final CharSequence iText , final int iCurrentPosition , final int iMaxPosition ) { } }

implementation: return jump ( iText , iCurrentPosition , iMaxPosition , COMMON_JUMP ) ;


signature:
public class OStringParser { /** * Jump some characters reading from an offset of a String .
 * @ param iText
 * String to analyze
 * @ param iCurrentPosition
 * Current position in text
 * @ param iMaxPosition
 * Maximum position to read
 * @ param iJumpChars
 * String as char array of chars to jump
 * @ return The new offset inside the string analyzed */
public static int jump ( final CharSequence iText , int iCurrentPosition , final int iMaxPosition , final String iJumpChars ) { } }

implementation: if ( iCurrentPosition < 0 ) return - 1 ; final int size = iMaxPosition > - 1 ? Math . min ( iMaxPosition , iText . length ( ) ) : iText . length ( ) ; final int jumpCharSize = iJumpChars . length ( ) ; boolean found = true ; char c ; for ( ; iCurrentPosition < size ; ++ iCurrentPosition ) { found = false ; c = iText . charAt ( iCurrentPosition ) ; for ( int jumpIndex = 0 ; jumpIndex < jumpCharSize ; ++ jumpIndex ) { if ( iJumpChars . charAt ( jumpIndex ) == c ) { found = true ; break ; } } if ( ! found ) break ; } return iCurrentPosition >= size ? - 1 : iCurrentPosition ;


signature:
public class OStringParser { /** * Like String . startsWith ( ) but ignoring case */
public static boolean startsWithIgnoreCase ( final String iText , final String iToFind ) { } }

implementation: if ( iText . length ( ) < iToFind . length ( ) ) return false ; return iText . substring ( 0 , iToFind . length ( ) ) . equalsIgnoreCase ( iToFind ) ;


signature:
public class OQueryAbstract { /** * Sets the fetch plan to use . */
public OQueryAbstract setFetchPlan ( final String fetchPlan ) { } }

implementation: OFetchHelper . checkFetchPlanValid ( fetchPlan ) ; if ( fetchPlan != null && fetchPlan . length ( ) == 0 ) this . fetchPlan = null ; else this . fetchPlan = fetchPlan ; return this ;


signature:
public class OConflictResolverDatabaseRepairer { /** * Adds the record to repair int the map of records and cluster . The decision about repairing is taken by the timer task .
 * @ param rid RecordId to repair */
@ Override public void enqueueRepairRecord ( final ORecordId rid ) { } }

implementation:
if ( ! active ) return ; if ( rid == null || ! rid . isPersistent ( ) ) return ; if ( rid . getClusterPosition ( ) < - 1 ) // SKIP TRANSACTIONAL RIDS
return ; recordProcessed . incrementAndGet ( ) ; // ADD RECORD TO REPAIR
records . put ( rid , Boolean . TRUE ) ;


signature:
public class OConflictResolverDatabaseRepairer { /** * Cancel the repair against a record because the update succeed .
 * @ param rid RecordId to remove from repair */
@ Override public void cancelRepairRecord ( final ORecordId rid ) { } }

implementation:
if ( ! active ) return ; if ( rid . getClusterPosition ( ) < - 1 ) // SKIP TRANSACTIONAL RIDS
return ; // REMOVE THE RECORD TO REPAIR
if ( records . remove ( rid ) != null ) // REMOVED
recordCanceled . incrementAndGet ( ) ;


signature:
public class OConflictResolverDatabaseRepairer { /** * Enqueues the request to repair a cluster . The decision about repairing is taken by the timer task .
 * @ param clusterId Broken cluster id to start repairing */
@ Override public void enqueueRepairCluster ( final int clusterId ) { } }

implementation:
if ( ! active ) return ; if ( clusterId < - 1 ) // SKIP TRANSACTIONAL RIDS
return ; recordProcessed . incrementAndGet ( ) ; // ADD CLUSTER TO REPAIR
clusters . put ( clusterId , Boolean . TRUE ) ;


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

implementation: final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . SERVER , "status" , ORole . PERMISSION_READ ) ; 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 ( ) ; final ODistributedConfiguration cfg = dManager . getDatabaseConfiguration ( databaseName ) ; if ( parsedStatement . outputText ) { final StringBuilder output = new StringBuilder ( ) ; if ( parsedStatement . servers ) output . append ( ODistributedOutput . formatServerStatus ( dManager , dManager . getClusterConfiguration ( ) ) ) ; if ( parsedStatement . db ) output . append ( ODistributedOutput . formatClusterTable ( dManager , databaseName , cfg , dManager . getTotalNodes ( databaseName ) ) ) ; if ( parsedStatement . latency ) output . append ( ODistributedOutput . formatLatency ( dManager , dManager . getClusterConfiguration ( ) ) ) ; if ( parsedStatement . messages ) output . append ( ODistributedOutput . formatMessages ( dManager , dManager . getClusterConfiguration ( ) ) ) ; return output . toString ( ) ; } final ODocument output = new ODocument ( ) ; if ( parsedStatement . servers ) output . field ( "servers" , dManager . getClusterConfiguration ( ) , OType . EMBEDDED ) ; if ( parsedStatement . db ) output . field ( "database" , cfg . getDocument ( ) , OType . EMBEDDED ) ; return output ;


signature:
public class OMatchExecutionPlanner { /** * Calculate the set of dependency aliases for each alias in the pattern .
 * @ param pattern
 * @ return map of alias to the set of aliases it depends on */
private Map < String , Set < String > > getDependencies ( Pattern pattern ) { } }

implementation: Map < String , Set < String > > result = new HashMap < String , Set < String > > ( ) ; for ( PatternNode node : pattern . aliasToNode . values ( ) ) { Set < String > currentDependencies = new HashSet < String > ( ) ; OWhereClause filter = aliasFilters . get ( node . alias ) ; if ( filter != null && filter . getBaseExpression ( ) != null ) { List < String > involvedAliases = filter . getBaseExpression ( ) . getMatchPatternInvolvedAliases ( ) ; if ( involvedAliases != null ) { currentDependencies . addAll ( involvedAliases ) ; } } result . put ( node . alias , currentDependencies ) ; } return result ;


signature:
public class OMatchExecutionPlanner { /** * sort edges in the order they will be matched */
private List < EdgeTraversal > sortEdges ( Map < String , Long > estimatedRootEntries , Pattern pattern , OCommandContext ctx ) { } }

implementation:
OQueryStats stats = null ; if ( ctx != null && ctx . getDatabase ( ) != null ) { stats = OQueryStats . get ( ( ODatabaseDocumentInternal ) ctx . getDatabase ( ) ) ; } // TODO use the stats
List < EdgeTraversal > result = new ArrayList < EdgeTraversal > ( ) ; List < OPair < Long , String > > rootWeights = new ArrayList < OPair < Long , String > > ( ) ; for ( Map . Entry < String , Long > root : estimatedRootEntries . entrySet ( ) ) { rootWeights . add ( new OPair < Long , String > ( root . getValue ( ) , root . getKey ( ) ) ) ; } Collections . sort ( rootWeights ) ; Set < PatternEdge > traversedEdges = new HashSet < PatternEdge > ( ) ; Set < PatternNode > traversedNodes = new HashSet < PatternNode > ( ) ; List < PatternNode > nextNodes = new ArrayList < PatternNode > ( ) ; while ( result . size ( ) < pattern . getNumOfEdges ( ) ) { for ( OPair < Long , String > rootPair : rootWeights ) { PatternNode root = pattern . get ( rootPair . getValue ( ) ) ; if ( root . isOptionalNode ( ) ) { continue ; } if ( ! traversedNodes . contains ( root ) ) { nextNodes . add ( root ) ; break ; } } if ( nextNodes . isEmpty ( ) ) { break ; } while ( ! nextNodes . isEmpty ( ) ) { PatternNode node = nextNodes . remove ( 0 ) ; traversedNodes . add ( node ) ; for ( PatternEdge edge : node . out ) { if ( ! traversedEdges . contains ( edge ) ) { result . add ( new EdgeTraversal ( edge , true ) ) ; traversedEdges . add ( edge ) ; if ( ! traversedNodes . contains ( edge . in ) && ! nextNodes . contains ( edge . in ) ) { nextNodes . add ( edge . in ) ; } } } for ( PatternEdge edge : node . in ) { if ( ! traversedEdges . contains ( edge ) && edge . item . isBidirectional ( ) ) { result . add ( new EdgeTraversal ( edge , false ) ) ; traversedEdges . add ( edge ) ; if ( ! traversedNodes . contains ( edge . out ) && ! nextNodes . contains ( edge . out ) ) { nextNodes . add ( edge . out ) ; } } } } } return result ;


signature:
public class OMatchExecutionPlanner { /** * assigns default aliases to pattern nodes that do not have an explicit alias
 * @ param matchExpressions */
private void assignDefaultAliases ( List < OMatchExpression > matchExpressions ) { } }

implementation: int counter = 0 ; for ( OMatchExpression expression : matchExpressions ) { if ( expression . getOrigin ( ) . getAlias ( ) == null ) { expression . getOrigin ( ) . setAlias ( DEFAULT_ALIAS_PREFIX + ( counter ++ ) ) ; } for ( OMatchPathItem item : expression . getItems ( ) ) { if ( item . getFilter ( ) == null ) { item . setFilter ( new OMatchFilter ( - 1 ) ) ; } if ( item . getFilter ( ) . getAlias ( ) == null ) { item . getFilter ( ) . setAlias ( DEFAULT_ALIAS_PREFIX + ( counter ++ ) ) ; } } }


signature:
public class OEntityManager { /** * Create a POJO by its class name .
 * @ see # registerEntityClasses ( String ) */
public synchronized Object createPojo ( final String iClassName ) throws OConfigurationException { } }

implementation:
if ( iClassName == null ) throw new IllegalArgumentException ( "Cannot create the object: class name is empty" ) ; final Class < ? > entityClass = classHandler . getEntityClass ( iClassName ) ; try { if ( entityClass != null ) return createInstance ( entityClass ) ; } catch ( Exception e ) { throw OException . wrapException ( new OConfigurationException ( "Error while creating new pojo of class '" + iClassName + "'" ) , e ) ; } try { // TRY TO INSTANTIATE THE CLASS DIRECTLY BY ITS NAME
return createInstance ( Class . forName ( iClassName ) ) ; } catch ( Exception e ) { throw OException . wrapException ( new OConfigurationException ( "The class '" + iClassName + "' was not found between the entity classes. Ensure registerEntityClasses(package) has been called first" ) , e ) ; }


signature:
public class OEntityManager { /** * Scans all classes accessible from the context class loader which belong to the given package and subpackages .
 * @ param iPackageName
 * The base package */
public synchronized void deregisterEntityClasses ( final String iPackageName , final ClassLoader iClassLoader ) { } }

implementation: OLogManager . instance ( ) . debug ( this , "Discovering entity classes inside package: %s" , iPackageName ) ; List < Class < ? > > classes = null ; try { classes = OReflectionHelper . getClassesFor ( iPackageName , iClassLoader ) ; } catch ( ClassNotFoundException e ) { throw OException . wrapException ( new ODatabaseException ( "Class cannot be found in package " + iPackageName ) , e ) ; } for ( Class < ? > c : classes ) { deregisterEntityClass ( c ) ; } if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) { for ( Entry < String , Class < ? > > entry : classHandler . getClassesEntrySet ( ) ) { OLogManager . instance ( ) . debug ( this , "Unloaded entity class '%s' from: %s" , entry . getKey ( ) , entry . getValue ( ) ) ; } }


signature:
public class OEntityManager { /** * Registers provided classes
 * @ param iClassNames
 * to be registered
 * @ param iClassLoader */
public synchronized void registerEntityClasses ( final Collection < String > iClassNames , final ClassLoader iClassLoader ) { } }

implementation: OLogManager . instance ( ) . debug ( this , "Discovering entity classes for class names: %s" , iClassNames ) ; try { registerEntityClasses ( OReflectionHelper . getClassesFor ( iClassNames , iClassLoader ) ) ; } catch ( ClassNotFoundException e ) { throw OException . wrapException ( new ODatabaseException ( "Entity class cannot be found" ) , e ) ; }


signature:
public class OEntityManager { /** * Scans all classes accessible from the context class loader which belong to the given class and all it ' s attributes - classes .
 * @ param aClass
 * The class to start from
 * @ param recursive
 * Beginning from the class , it will register all classes that are direct or indirect a attribute class */
public synchronized void registerEntityClasses ( Class < ? > aClass , boolean recursive ) { } }

implementation: if ( recursive ) { classHandler . registerEntityClass ( aClass ) ; Field [ ] declaredFields = aClass . getDeclaredFields ( ) ; for ( Field declaredField : declaredFields ) { Class < ? > declaredFieldType = declaredField . getType ( ) ; if ( ! classHandler . containsEntityClass ( declaredFieldType ) ) { registerEntityClasses ( declaredFieldType , recursive ) ; } } } else { classHandler . registerEntityClass ( aClass ) ; }


signature:
public class OEntityManager { /** * Sets the received handler as default and merges the classes all together .
 * @ param iClassHandler */
public synchronized void setClassHandler ( final OEntityManagerClassHandler iClassHandler ) { } }

implementation: Iterator < Entry < String , Class < ? > > > iterator = classHandler . getClassesEntrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Entry < String , Class < ? > > entry = iterator . next ( ) ; boolean forceSchemaReload = ! iterator . hasNext ( ) ; iClassHandler . registerEntityClass ( entry . getValue ( ) , forceSchemaReload ) ; } this . classHandler = iClassHandler ;


signature:
public class ODatabasePoolBase { /** * Acquires a connection from the pool . If the pool is empty , then the caller thread will wait for it .
 * @ param iName
 * Database name
 * @ param iUserName
 * User name
 * @ param iUserPassword
 * User password
 * @ return A pooled database instance */
public DB acquire ( final String iName , final String iUserName , final String iUserPassword ) { } }

implementation: setup ( ) ; return dbPool . acquire ( iName , iUserName , iUserPassword ) ;


signature:
public class ODatabasePoolBase { /** * Returns amount of available connections which you can acquire for given source and user name . Source id is consist of
 * " source name " and " source user name " .
 * @ param name
 * Source name .
 * @ param userName
 * User name which is used to acquire source .
 * @ return amount of available connections which you can acquire for given source and user name . */
public int getAvailableConnections ( final String name , final String userName ) { } }

implementation: setup ( ) ; return dbPool . getAvailableConnections ( name , userName ) ;


signature:
public class ODatabasePoolBase { /** * Acquires a connection from the pool specifying options . If the pool is empty , then the caller thread will wait for it .
 * @ param iName
 * Database name
 * @ param iUserName
 * User name
 * @ param iUserPassword
 * User password
 * @ return A pooled database instance */
public DB acquire ( final String iName , final String iUserName , final String iUserPassword , final Map < String , Object > iOptionalParams ) { } }

implementation: setup ( ) ; return dbPool . acquire ( iName , iUserName , iUserPassword , iOptionalParams ) ;


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

implementation:
final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . CLUSTER , "sync" , ORole . PERMISSION_UPDATE ) ; 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 ( ) ; try { if ( this . parsedStatement . modeFull ) { return replaceCluster ( dManager , database , dManager . getServerInstance ( ) , databaseName , this . parsedStatement . clusterName . getStringValue ( ) ) ; } // else {
// int merged = 0;
// return String . format ( " Merged % d records " , merged ) ;
} catch ( Exception e ) { throw OException . wrapException ( new OCommandExecutionException ( "Cannot execute synchronization of cluster" ) , e ) ; } return "Mode not supported" ;


signature:
public class OClusterPage { /** * Writes binary dump of this cluster page to the log . */
public void dumpToLog ( ) { } }

implementation: final StringBuilder text = new StringBuilder ( ) ; text . append ( "Dump of " ) . append ( this ) . append ( '\n' ) ; text . append ( "Magic:\t\t\t" ) . append ( String . format ( "%016X" , getLongValue ( MAGIC_NUMBER_OFFSET ) ) ) . append ( '\n' ) ; text . append ( "CRC32:\t\t\t" ) . append ( String . format ( "%08X" , getIntValue ( CRC32_OFFSET ) ) ) . append ( '\n' ) ; text . append ( "WAL Segment:\t" ) . append ( String . format ( "%016X" , getLongValue ( WAL_SEGMENT_OFFSET ) ) ) . append ( '\n' ) ; text . append ( "WAL Position:\t" ) . append ( String . format ( "%016X" , getLongValue ( WAL_POSITION_OFFSET ) ) ) . append ( '\n' ) ; text . append ( "Next Page:\t\t" ) . append ( String . format ( "%016X" , getLongValue ( NEXT_PAGE_OFFSET ) ) ) . append ( '\n' ) ; text . append ( "Prev Page:\t\t" ) . append ( String . format ( "%016X" , getLongValue ( PREV_PAGE_OFFSET ) ) ) . append ( '\n' ) ; text . append ( "Free List:\t\t" ) . append ( String . format ( "%08X" , getIntValue ( FREELIST_HEADER_OFFSET ) ) ) . append ( '\n' ) ; text . append ( "Free Pointer:\t" ) . append ( String . format ( "%08X" , getIntValue ( FREE_POSITION_OFFSET ) ) ) . append ( '\n' ) ; text . append ( "Free Space:\t\t" ) . append ( String . format ( "%08X" , getIntValue ( FREE_SPACE_COUNTER_OFFSET ) ) ) . append ( '\n' ) ; text . append ( "Entry Count:\t" ) . append ( String . format ( "%08X" , getIntValue ( ENTRIES_COUNT_OFFSET ) ) ) . append ( '\n' ) ; final int indexCount = getIntValue ( PAGE_INDEXES_LENGTH_OFFSET ) ; text . append ( "Index Count:\t" ) . append ( String . format ( "%08X" , indexCount ) ) . append ( "\n\n" ) ; int foundEntries = 0 ; for ( int i = 0 ; i < indexCount ; ++ i ) { final int offset = getIntValue ( PAGE_INDEXES_OFFSET + i * INDEX_ITEM_SIZE ) ; text . append ( "\tOffset:\t\t" ) . append ( String . format ( "%08X" , offset ) ) . append ( " (" ) . append ( i ) . append ( ")\n" ) ; text . append ( "\tVersion:\t" ) . append ( String . format ( "%08X" , getIntValue ( PAGE_INDEXES_OFFSET + i * INDEX_ITEM_SIZE + OIntegerSerializer . INT_SIZE ) ) ) . append ( '\n' ) ; if ( ( offset & MARKED_AS_DELETED_FLAG ) != 0 ) { continue ; } final int cleanOffset = offset & POSITION_MASK ; text . append ( "\t\tEntry Size:\t" ) ; if ( cleanOffset + OIntegerSerializer . INT_SIZE <= MAX_PAGE_SIZE_BYTES ) { text . append ( String . format ( "%08X" , getIntValue ( cleanOffset ) ) ) . append ( " (" ) . append ( foundEntries ) . append ( ")\n" ) ; } else { text . append ( "?\n" ) ; } if ( cleanOffset + OIntegerSerializer . INT_SIZE * 2 <= MAX_PAGE_SIZE_BYTES ) { text . append ( "\t\tIndex:\t\t" ) . append ( String . format ( "%08X" , getIntValue ( cleanOffset + OIntegerSerializer . INT_SIZE ) ) ) . append ( '\n' ) ; } else { text . append ( "?\n" ) ; } if ( cleanOffset + OIntegerSerializer . INT_SIZE * 3 <= MAX_PAGE_SIZE_BYTES ) { text . append ( "\t\tData Size:\t" ) . append ( String . format ( "%08X" , getIntValue ( cleanOffset + OIntegerSerializer . INT_SIZE * 2 ) ) ) . append ( '\n' ) ; } else { text . append ( "?\n" ) ; } ++ foundEntries ; } OLogManager . instance ( ) . error ( this , "%s" , null , text ) ;


signature:
public class OClassLoaderHelper { /** * Switch to the OrientDb classloader before lookups on ServiceRegistry for implementation of the given Class . Useful under OSGI
 * and generally under applications where jars are loaded by another class loader
 * @ param clazz
 * the class to lookup foor
 * @ return an Iterator on the class implementation */
public static synchronized < T extends Object > Iterator < T > lookupProviderWithOrientClassLoader ( Class < T > clazz ) { } }

implementation: return lookupProviderWithOrientClassLoader ( clazz , OClassLoaderHelper . class . getClassLoader ( ) ) ;


signature:
public class OMemory { /** * @ param unlimitedCap the upper limit on reported memory , if JVM reports unlimited memory .
 * @ return same as { @ link Runtime # maxMemory ( ) } except that { @ code unlimitedCap } limit is applied if JVM reports { @ link
 * Long # MAX _ VALUE unlimited memory } . */
public static long getCappedRuntimeMaxMemory ( long unlimitedCap ) { } }

implementation: final long jvmMaxMemory = Runtime . getRuntime ( ) . maxMemory ( ) ; return jvmMaxMemory == Long . MAX_VALUE ? unlimitedCap : jvmMaxMemory ;


signature:
public class OMemory { /** * Checks the OrientDB cache memory configuration and emits a warning if configuration is invalid . */
public static void checkCacheMemoryConfiguration ( ) { } }

implementation: final long maxHeapSize = Runtime . getRuntime ( ) . maxMemory ( ) ; final long maxCacheSize = getMaxCacheMemorySize ( ) ; final ONative . MemoryLimitResult physicalMemory = ONative . instance ( ) . getMemoryLimit ( false ) ; if ( maxHeapSize != Long . MAX_VALUE && physicalMemory != null && maxHeapSize + maxCacheSize > physicalMemory . memoryLimit ) OLogManager . instance ( ) . warnNoDb ( OMemory . class , "The sum of the configured JVM maximum heap size (" + maxHeapSize + " bytes) " + "and the OrientDB maximum cache size (" + maxCacheSize + " bytes) is larger than the available physical memory size " + "(" + physicalMemory + " bytes). That may cause out of memory errors, please tune the configuration up. Use the " + "-Xmx JVM option to lower the JVM maximum heap memory size or storage.diskCache.bufferSize OrientDB option to " + "lower memory requirements of the cache." ) ;


signature:
public class OMemory { /** * Tries to fix some common cache / memory configuration problems : < ul > < li > Cache size is larger than direct memory size . < / li >
 * < li > Memory chunk size is larger than cache size . < / li > < ul / > */
public static void fixCommonConfigurationProblems ( ) { } }

implementation: long diskCacheSize = OGlobalConfiguration . DISK_CACHE_SIZE . getValueAsLong ( ) ; final int max32BitCacheSize = 512 ; if ( getJavaBitWidth ( ) == 32 && diskCacheSize > max32BitCacheSize ) { OLogManager . instance ( ) . infoNoDb ( OGlobalConfiguration . class , "32 bit JVM is detected. Lowering disk cache size from %,dMB to %,dMB." , diskCacheSize , max32BitCacheSize ) ; OGlobalConfiguration . DISK_CACHE_SIZE . setValue ( max32BitCacheSize ) ; }


signature:
public class OGraphSONUtility { /** * Creates a vertex from GraphSON using settings supplied in the constructor . */
public Vertex vertexFromJson ( final InputStream json ) throws IOException { } }

implementation: final JsonParser jp = jsonFactory . createParser ( json ) ; final JsonNode node = jp . readValueAsTree ( ) ; return this . vertexFromJson ( node ) ;


signature:
public class OGraphSONUtility { /** * Creates a vertex from GraphSON using settings supplied in the constructor . */
public Vertex vertexFromJson ( final JsonNode json ) throws IOException { } }

implementation:
final Map < String , Object > props = readProperties ( json , true , this . hasEmbeddedTypes ) ; final Object vertexId = getTypedValueFromJsonNode ( json . get ( GraphSONTokens . _ID ) ) ; final Vertex v = factory . createVertex ( vertexId ) ; for ( Map . Entry < String , Object > entry : props . entrySet ( ) ) { // if ( this . vertexPropertyKeys = = null | | vertexPropertyKeys . contains ( entry . getKey ( ) ) ) {
if ( includeKey ( entry . getKey ( ) , vertexPropertyKeys , this . vertexPropertiesRule ) ) { v . setProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return v ;


signature:
public class OGraphSONUtility { /** * Creates an edge from GraphSON using settings supplied in the constructor . */
public Edge edgeFromJson ( final JSONObject json , final Vertex out , final Vertex in ) throws IOException { } }

implementation: return this . edgeFromJson ( json . toString ( ) , out , in ) ;


signature:
public class OGraphSONUtility { /** * Creates an edge from GraphSON using settings supplied in the constructor . */
public Edge edgeFromJson ( final String json , final Vertex out , final Vertex in ) throws IOException { } }

implementation: final JsonParser jp = jsonFactory . createParser ( json ) ; final JsonNode node = jp . readValueAsTree ( ) ; return this . edgeFromJson ( node , out , in ) ;


signature:
public class OGraphSONUtility { /** * Creates an edge from GraphSON using settings supplied in the constructor . */
public Edge edgeFromJson ( final JsonNode json , final Vertex out , final Vertex in ) throws IOException { } }

implementation:
final Map < String , Object > props = OGraphSONUtility . readProperties ( json , true , this . hasEmbeddedTypes ) ; final Object edgeId = getTypedValueFromJsonNode ( json . get ( GraphSONTokens . _ID ) ) ; final JsonNode nodeLabel = json . get ( GraphSONTokens . _LABEL ) ; // assigned an empty string edge label in cases where one does not exist . this gets around the requirement
// that blueprints graphs have a non - null label while ensuring that GraphSON can stay flexible in parsing
// partial bits from the JSON . Not sure if there is any gotchas developing out of this .
final String label = nodeLabel == null ? EMPTY_STRING : nodeLabel . textValue ( ) ; final Edge e = factory . createEdge ( edgeId , out , in , label ) ; for ( Map . Entry < String , Object > entry : props . entrySet ( ) ) { // if ( this . edgePropertyKeys = = null | | this . edgePropertyKeys . contains ( entry . getKey ( ) ) ) {
if ( includeKey ( entry . getKey ( ) , edgePropertyKeys , this . edgePropertiesRule ) ) { e . setProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return e ;


signature:
public class OGraphSONUtility { /** * Creates GraphSON for a single graph element . */
public JSONObject jsonFromElement ( final Element element ) throws JSONException { } }

implementation:
final ObjectNode objectNode = this . objectNodeFromElement ( element ) ; try { return new JSONObject ( new JSONTokener ( mapper . writeValueAsString ( objectNode ) ) ) ; } catch ( IOException ioe ) { // repackage this as a JSONException . . . seems sensible as the caller will only know about
// the jettison object not being created
throw new JSONException ( ioe ) ; }