signature:
public class OSelectExecutionPlanner { /** * if GROUP BY is performed on an expression that is not explicitly in the pre - aggregate projections , then that expression has to
 * be put in the pre - aggregate ( only here , in subsequent steps it ' s removed ) */
private static void addGroupByExpressionsToProjections ( QueryPlanningInfo info ) { } }

implementation:
if ( info . groupBy == null || info . groupBy . getItems ( ) == null || info . groupBy . getItems ( ) . size ( ) == 0 ) { return ; } OGroupBy newGroupBy = new OGroupBy ( - 1 ) ; int i = 0 ; for ( OExpression exp : info . groupBy . getItems ( ) ) { if ( exp . isAggregate ( ) ) { throw new OCommandExecutionException ( "Cannot group by an aggregate function" ) ; } boolean found = false ; if ( info . preAggregateProjection != null ) { for ( String alias : info . preAggregateProjection . getAllAliases ( ) ) { // if it ' s a simple identifier and it ' s the same as one of the projections in the query ,
// then the projection itself is used for GROUP BY without recalculating ; in all the other cases , it is evaluated separately
if ( alias . equals ( exp . getDefaultAlias ( ) . getStringValue ( ) ) && exp . isBaseIdentifier ( ) ) { found = true ; newGroupBy . getItems ( ) . add ( exp ) ; break ; } } } if ( ! found ) { OProjectionItem newItem = new OProjectionItem ( - 1 ) ; newItem . setExpression ( exp ) ; OIdentifier groupByAlias = new OIdentifier ( "_$$$GROUP_BY_ALIAS$$$_" + ( i ++ ) ) ; newItem . setAlias ( groupByAlias ) ; if ( info . preAggregateProjection == null ) { info . preAggregateProjection = new OProjection ( - 1 ) ; } if ( info . preAggregateProjection . getItems ( ) == null ) { info . preAggregateProjection . setItems ( new ArrayList < > ( ) ) ; } info . preAggregateProjection . getItems ( ) . add ( newItem ) ; newGroupBy . getItems ( ) . add ( new OExpression ( groupByAlias ) ) ; } info . groupBy = newGroupBy ; }


signature:
public class OSelectExecutionPlanner { /** * translates subqueries to LET statements */
private static void extractSubQueries ( QueryPlanningInfo info ) { } }

implementation: SubQueryCollector collector = new SubQueryCollector ( ) ; if ( info . perRecordLetClause != null ) { info . perRecordLetClause . extractSubQueries ( collector ) ; } int i = 0 ; int j = 0 ; for ( Map . Entry < OIdentifier , OStatement > entry : collector . getSubQueries ( ) . entrySet ( ) ) { OIdentifier alias = entry . getKey ( ) ; OStatement query = entry . getValue ( ) ; if ( query . refersToParent ( ) ) { addRecordLevelLet ( info , alias , query , j ++ ) ; } else { addGlobalLet ( info , alias , query , i ++ ) ; } } collector . reset ( ) ; if ( info . whereClause != null ) { info . whereClause . extractSubQueries ( collector ) ; } if ( info . projection != null ) { info . projection . extractSubQueries ( collector ) ; } if ( info . orderBy != null ) { info . orderBy . extractSubQueries ( collector ) ; } if ( info . groupBy != null ) { info . groupBy . extractSubQueries ( collector ) ; } for ( Map . Entry < OIdentifier , OStatement > entry : collector . getSubQueries ( ) . entrySet ( ) ) { OIdentifier alias = entry . getKey ( ) ; OStatement query = entry . getValue ( ) ; if ( query . refersToParent ( ) ) { addRecordLevelLet ( info , alias , query ) ; } else { addGlobalLet ( info , alias , query ) ; } }


signature:
public class OSelectExecutionPlanner { /** * checks if this RID is from one of these clusters
 * @ param rid
 * @ param filterClusters
 * @ param database
 * @ return */
private boolean isFromClusters ( ORid rid , Set < String > filterClusters , ODatabase database ) { } }

implementation: if ( filterClusters == null ) { throw new IllegalArgumentException ( ) ; } String clusterName = database . getClusterNameById ( rid . getCluster ( ) . getValue ( ) . intValue ( ) ) ; return filterClusters . contains ( clusterName ) ;


signature:
public class OSelectExecutionPlanner { /** * tries to use an index for sorting only . Also adds the fetch step to the execution plan
 * @ param plan current execution plan
 * @ param info the query planning information
 * @ param ctx the current context
 * @ return true if it succeeded to use an index to sort , false otherwise . */
private boolean handleClassWithIndexForSortOnly ( OSelectExecutionPlan plan , OIdentifier queryTarget , Set < String > filterClusters , QueryPlanningInfo info , OCommandContext ctx , boolean profilingEnabled ) { } }

implementation:
OSchema schema = getSchemaFromContext ( ctx ) ; OClass clazz = schema . getClass ( queryTarget . getStringValue ( ) ) ; if ( clazz == null ) { clazz = schema . getView ( queryTarget . getStringValue ( ) ) ; if ( clazz == null ) { throw new OCommandExecutionException ( "Class not found: " + queryTarget ) ; } } for ( OIndex idx : clazz . getIndexes ( ) . stream ( ) . filter ( i -> i . supportsOrderedIterations ( ) ) . filter ( i -> i . getDefinition ( ) != null ) . collect ( Collectors . toList ( ) ) ) { List < String > indexFields = idx . getDefinition ( ) . getFields ( ) ; if ( indexFields . size ( ) < info . orderBy . getItems ( ) . size ( ) ) { continue ; } boolean indexFound = true ; String orderType = null ; for ( int i = 0 ; i < info . orderBy . getItems ( ) . size ( ) ; i ++ ) { OOrderByItem orderItem = info . orderBy . getItems ( ) . get ( i ) ; if ( orderItem . getCollate ( ) != null ) { return false ; } String indexField = indexFields . get ( i ) ; if ( i == 0 ) { orderType = orderItem . getType ( ) ; } else { if ( orderType == null || ! orderType . equals ( orderItem . getType ( ) ) ) { indexFound = false ; break ; // ASC / DESC interleaved , cannot be used with index .
} } if ( ! ( indexField . equals ( orderItem . getAlias ( ) ) || isInOriginalProjection ( indexField , orderItem . getAlias ( ) ) ) ) { indexFound = false ; break ; } } if ( indexFound && orderType != null ) { plan . chain ( new FetchFromIndexValuesStep ( idx , orderType . equals ( OOrderByItem . ASC ) , ctx , profilingEnabled ) ) ; int [ ] filterClusterIds = null ; if ( filterClusters != null ) { filterClusterIds = filterClusters . stream ( ) . map ( name -> ctx . getDatabase ( ) . getClusterIdByName ( name ) ) . mapToInt ( i -> i ) . toArray ( ) ; } plan . chain ( new GetValueFromIndexEntryStep ( ctx , filterClusterIds , profilingEnabled ) ) ; if ( info . serverToClusters . size ( ) == 1 ) { info . orderApplied = true ; } return true ; } } return false ;


signature:
public class OSelectExecutionPlanner { /** * checks if a class is the top of a diamond hierarchy
 * @ param clazz
 * @ return */
private boolean isDiamondHierarchy ( OClass clazz ) { } }

implementation: Set < OClass > traversed = new HashSet < > ( ) ; List < OClass > stack = new ArrayList < > ( ) ; stack . add ( clazz ) ; while ( ! stack . isEmpty ( ) ) { OClass current = stack . remove ( 0 ) ; traversed . add ( current ) ; for ( OClass sub : current . getSubclasses ( ) ) { if ( traversed . contains ( sub ) ) { return true ; } stack . add ( sub ) ; traversed . add ( sub ) ; } } return false ;


signature:
public class OSelectExecutionPlanner { /** * returns TRUE if all the order clauses are ASC , FALSE if all are DESC , null otherwise
 * @ return TRUE if all the order clauses are ASC , FALSE if all are DESC , null otherwise */
private Boolean getOrderDirection ( QueryPlanningInfo info ) { } }

implementation: if ( info . orderBy == null ) { return null ; } String result = null ; for ( OOrderByItem item : info . orderBy . getItems ( ) ) { if ( result == null ) { result = item . getType ( ) == null ? OOrderByItem . ASC : item . getType ( ) ; } else { String newType = item . getType ( ) == null ? OOrderByItem . ASC : item . getType ( ) ; if ( ! newType . equals ( result ) ) { return null ; } } } return result == null || result . equals ( OOrderByItem . ASC ) ;


signature:
public class OSelectExecutionPlanner { /** * checks whether the condition has CONTAINSANY or similar expressions , that require multiple index evaluations
 * @ param keyCondition
 * @ return */
private boolean requiresMultipleIndexLookups ( OAndBlock keyCondition ) { } }

implementation: for ( OBooleanExpression oBooleanExpression : keyCondition . getSubBlocks ( ) ) { if ( ! ( oBooleanExpression instanceof OBinaryCondition ) ) { return true ; } } return false ;


signature:
public class OSelectExecutionPlanner { /** * given a flat AND block and a set of indexes , returns the best index to be used to process it , with the complete description on
 * how to use it
 * @ param ctx
 * @ param indexes
 * @ param block
 * @ return */
private IndexSearchDescriptor findBestIndexFor ( OCommandContext ctx , Set < OIndex < ? > > indexes , OAndBlock block , OClass clazz ) { } }

implementation:
// get all valid index descriptors
List < IndexSearchDescriptor > descriptors = indexes . stream ( ) . filter ( x -> x . getInternal ( ) . canBeUsedInEqualityOperators ( ) ) . map ( index -> buildIndexSearchDescriptor ( ctx , index , block , clazz ) ) . filter ( Objects :: nonNull ) . filter ( x -> x . keyCondition != null ) . filter ( x -> x . keyCondition . getSubBlocks ( ) . size ( ) > 0 ) . collect ( Collectors . toList ( ) ) ; List < IndexSearchDescriptor > fullTextIndexDescriptors = indexes . stream ( ) . filter ( idx -> idx . getType ( ) . equalsIgnoreCase ( "FULLTEXT" ) ) . filter ( idx -> ! idx . getAlgorithm ( ) . equalsIgnoreCase ( "LUCENE" ) ) . map ( idx -> buildIndexSearchDescriptorForFulltext ( ctx , idx , block , clazz ) ) . filter ( Objects :: nonNull ) . filter ( x -> x . keyCondition != null ) . filter ( x -> x . keyCondition . getSubBlocks ( ) . size ( ) > 0 ) . collect ( Collectors . toList ( ) ) ; descriptors . addAll ( fullTextIndexDescriptors ) ; // remove the redundant descriptors ( eg . if I have one on [ a ] and one on [ a , b ] , the first one is redundant , just discard it )
descriptors = removePrefixIndexes ( descriptors ) ; // sort by cost
List < OPair < Integer , IndexSearchDescriptor > > sortedDescriptors = descriptors . stream ( ) . map ( x -> ( OPair < Integer , IndexSearchDescriptor > ) new OPair ( x . cost ( ctx ) , x ) ) . sorted ( ) . collect ( Collectors . toList ( ) ) ; // get only the descriptors with the lowest cost
descriptors = sortedDescriptors . isEmpty ( ) ? Collections . emptyList ( ) : sortedDescriptors . stream ( ) . filter ( x -> x . key . equals ( sortedDescriptors . get ( 0 ) . key ) ) . map ( x -> x . value ) . collect ( Collectors . toList ( ) ) ; // sort remaining by the number of indexed fields
descriptors = descriptors . stream ( ) . sorted ( Comparator . comparingInt ( x -> x . keyCondition . getSubBlocks ( ) . size ( ) ) ) . collect ( Collectors . toList ( ) ) ; // get the one that has more indexed fields
return descriptors . isEmpty ( ) ? null : descriptors . get ( descriptors . size ( ) - 1 ) ;


signature:
public class OSelectExecutionPlanner { /** * finds prefix conditions for a given condition , eg . if the condition is on [ a , b ] and in the list there is another condition on
 * [ a ] or on [ a , b ] , then that condition is returned .
 * @ param desc
 * @ param descriptors
 * @ return */
private List < IndexSearchDescriptor > findPrefixes ( IndexSearchDescriptor desc , List < IndexSearchDescriptor > descriptors ) { } }

implementation: List < IndexSearchDescriptor > result = new ArrayList < > ( ) ; for ( IndexSearchDescriptor item : descriptors ) { if ( isPrefixOf ( item , desc ) ) { result . add ( item ) ; } } return result ;


signature:
public class OSelectExecutionPlanner { /** * returns true if the first argument is a prefix for the second argument , eg . if the first argument is [ a ] and the second
 * argument is [ a , b ]
 * @ param item
 * @ param desc
 * @ return */
private boolean isPrefixOf ( IndexSearchDescriptor item , IndexSearchDescriptor desc ) { } }

implementation: List < OBooleanExpression > left = item . keyCondition . getSubBlocks ( ) ; List < OBooleanExpression > right = desc . keyCondition . getSubBlocks ( ) ; if ( left . size ( ) > right . size ( ) ) { return false ; } for ( int i = 0 ; i < left . size ( ) ; i ++ ) { if ( ! left . get ( i ) . equals ( right . get ( i ) ) ) { return false ; } } return true ;


signature:
public class OSelectExecutionPlanner { /** * given an index and a flat AND block , returns a descriptor on how to process it with an index ( index , index key and additional
 * filters to apply after index fetch
 * @ param ctx
 * @ param index
 * @ param block
 * @ param clazz
 * @ return */
private IndexSearchDescriptor buildIndexSearchDescriptor ( OCommandContext ctx , OIndex < ? > index , OAndBlock block , OClass clazz ) { } }

implementation:
List < String > indexFields = index . getDefinition ( ) . getFields ( ) ; OBinaryCondition keyCondition = new OBinaryCondition ( - 1 ) ; OIdentifier key = new OIdentifier ( "key" ) ; keyCondition . setLeft ( new OExpression ( key ) ) ; boolean allowsRange = allowsRangeQueries ( index ) ; boolean found = false ; OAndBlock blockCopy = block . copy ( ) ; Iterator < OBooleanExpression > blockIterator ; OAndBlock indexKeyValue = new OAndBlock ( - 1 ) ; IndexSearchDescriptor result = new IndexSearchDescriptor ( ) ; result . idx = index ; result . keyCondition = indexKeyValue ; for ( String indexField : indexFields ) { blockIterator = blockCopy . getSubBlocks ( ) . iterator ( ) ; boolean breakHere = false ; boolean indexFieldFound = false ; while ( blockIterator . hasNext ( ) ) { OBooleanExpression singleExp = blockIterator . next ( ) ; if ( singleExp instanceof OBinaryCondition ) { OExpression left = ( ( OBinaryCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { OBinaryCompareOperator operator = ( ( OBinaryCondition ) singleExp ) . getOperator ( ) ; if ( ! ( ( OBinaryCondition ) singleExp ) . getRight ( ) . isEarlyCalculated ( ctx ) ) { continue ; // this cannot be used because the value depends on single record
} if ( operator instanceof OEqualsCompareOperator ) { found = true ; indexFieldFound = true ; OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( operator ) ; condition . setRight ( ( ( OBinaryCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } else if ( operator instanceof OContainsKeyOperator && isMap ( clazz , indexField ) && isIndexByKey ( index , indexField ) ) { found = true ; indexFieldFound = true ; OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( operator ) ; condition . setRight ( ( ( OBinaryCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } else if ( allowsRange && operator . isRangeOperator ( ) ) { found = true ; indexFieldFound = true ; breakHere = true ; // this is last element , no other fields can be added to the key because this is a range condition
OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( operator ) ; condition . setRight ( ( ( OBinaryCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; // look for the opposite condition , on the same field , for range queries ( the other side of the range )
while ( blockIterator . hasNext ( ) ) { OBooleanExpression next = blockIterator . next ( ) ; if ( createsRangeWith ( ( OBinaryCondition ) singleExp , next ) ) { result . additionalRangeCondition = ( OBinaryCondition ) next ; blockIterator . remove ( ) ; break ; } } break ; } } } } else if ( singleExp instanceof OContainsValueCondition && ( ( OContainsValueCondition ) singleExp ) . getExpression ( ) != null && isMap ( clazz , indexField ) && isIndexByValue ( index , indexField ) ) { OExpression left = ( ( OContainsValueCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { found = true ; indexFieldFound = true ; OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( new OContainsValueOperator ( - 1 ) ) ; condition . setRight ( ( ( OContainsValueCondition ) singleExp ) . getExpression ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } else if ( singleExp instanceof OContainsAnyCondition ) { OExpression left = ( ( OContainsAnyCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { if ( ! ( ( OContainsAnyCondition ) singleExp ) . getRight ( ) . isEarlyCalculated ( ctx ) ) { continue ; // this cannot be used because the value depends on single record
} found = true ; indexFieldFound = true ; OContainsAnyCondition condition = new OContainsAnyCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRight ( ( ( OContainsAnyCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } else if ( singleExp instanceof OInCondition ) { OExpression left = ( ( OInCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { if ( ( ( OInCondition ) singleExp ) . getRightMathExpression ( ) != null ) { if ( ! ( ( OInCondition ) singleExp ) . getRightMathExpression ( ) . isEarlyCalculated ( ctx ) ) { continue ; // this cannot be used because the value depends on single record
} found = true ; indexFieldFound = true ; OInCondition condition = new OInCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRightMathExpression ( ( ( OInCondition ) singleExp ) . getRightMathExpression ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } else if ( ( ( OInCondition ) singleExp ) . getRightParam ( ) != null ) { found = true ; indexFieldFound = true ; OInCondition condition = new OInCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRightParam ( ( ( OInCondition ) singleExp ) . getRightParam ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } } } if ( breakHere || ! indexFieldFound ) { break ; } } if ( result . keyCondition . getSubBlocks ( ) . size ( ) < index . getDefinition ( ) . getFields ( ) . size ( ) && ! index . supportsOrderedIterations ( ) ) { // hash indexes do not support partial key match
return null ; } if ( found ) { result . remainingCondition = blockCopy ; return result ; } return null ;


signature:
public class OSelectExecutionPlanner { /** * given a full text index and a flat AND block , returns a descriptor on how to process it with an index ( index , index key and additional
 * filters to apply after index fetch
 * @ param ctx
 * @ param index
 * @ param block
 * @ param clazz
 * @ return */
private IndexSearchDescriptor buildIndexSearchDescriptorForFulltext ( OCommandContext ctx , OIndex < ? > index , OAndBlock block , OClass clazz ) { } }

implementation:
List < String > indexFields = index . getDefinition ( ) . getFields ( ) ; OBinaryCondition keyCondition = new OBinaryCondition ( - 1 ) ; OIdentifier key = new OIdentifier ( "key" ) ; keyCondition . setLeft ( new OExpression ( key ) ) ; boolean found = false ; OAndBlock blockCopy = block . copy ( ) ; Iterator < OBooleanExpression > blockIterator ; OAndBlock indexKeyValue = new OAndBlock ( - 1 ) ; IndexSearchDescriptor result = new IndexSearchDescriptor ( ) ; result . idx = index ; result . keyCondition = indexKeyValue ; for ( String indexField : indexFields ) { blockIterator = blockCopy . getSubBlocks ( ) . iterator ( ) ; boolean breakHere = false ; boolean indexFieldFound = false ; while ( blockIterator . hasNext ( ) ) { OBooleanExpression singleExp = blockIterator . next ( ) ; if ( singleExp instanceof OContainsTextCondition ) { OExpression left = ( ( OContainsTextCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { found = true ; indexFieldFound = true ; OContainsTextCondition condition = new OContainsTextCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRight ( ( ( OContainsTextCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } } if ( breakHere || ! indexFieldFound ) { break ; } } if ( result . keyCondition . getSubBlocks ( ) . size ( ) < index . getDefinition ( ) . getFields ( ) . size ( ) && ! index . supportsOrderedIterations ( ) ) { // hash indexes do not support partial key match
return null ; } if ( found ) { result . remainingCondition = blockCopy ; return result ; } return null ;


signature:
public class OSelectExecutionPlanner { /** * aggregates multiple index conditions that refer to the same key search
 * @ param indexSearchDescriptors
 * @ return */
private List < IndexSearchDescriptor > commonFactor ( List < IndexSearchDescriptor > indexSearchDescriptors ) { } }

implementation:
// index , key condition , additional filter ( to aggregate in OR )
Map < OIndex , Map < IndexCondPair , OOrBlock > > aggregation = new HashMap < > ( ) ; for ( IndexSearchDescriptor item : indexSearchDescriptors ) { Map < IndexCondPair , OOrBlock > filtersForIndex = aggregation . get ( item . idx ) ; if ( filtersForIndex == null ) { filtersForIndex = new HashMap < > ( ) ; aggregation . put ( item . idx , filtersForIndex ) ; } IndexCondPair extendedCond = new IndexCondPair ( item . keyCondition , item . additionalRangeCondition ) ; OOrBlock existingAdditionalConditions = filtersForIndex . get ( extendedCond ) ; if ( existingAdditionalConditions == null ) { existingAdditionalConditions = new OOrBlock ( - 1 ) ; filtersForIndex . put ( extendedCond , existingAdditionalConditions ) ; } existingAdditionalConditions . getSubBlocks ( ) . add ( item . remainingCondition ) ; } List < IndexSearchDescriptor > result = new ArrayList < > ( ) ; for ( Map . Entry < OIndex , Map < IndexCondPair , OOrBlock > > item : aggregation . entrySet ( ) ) { for ( Map . Entry < IndexCondPair , OOrBlock > filters : item . getValue ( ) . entrySet ( ) ) { result . add ( new IndexSearchDescriptor ( item . getKey ( ) , filters . getKey ( ) . mainCondition , filters . getKey ( ) . additionalRange , filters . getValue ( ) ) ) ; } } return result ;


signature:
public class ODocumentFieldHandlingStrategyFactory { /** * Creates a new instance of the requested strategy . Since strategies are stateless , if an existing instance already exists then
 * it ' s returned .
 * @ param strategy
 * @ return strategy instance */
public ODocumentFieldHandlingStrategy create ( int strategy ) { } }

implementation: Optional < ODocumentFieldHandlingStrategy > registered = ODocumentFieldHandlingStrategyRegistry . getInstance ( ) . getStrategy ( strategy ) ; if ( registered . isPresent ( ) ) { return registered . get ( ) ; } Map < OType , ODocumentFieldOTypeHandlingStrategy > typeHandlingStrategies = new HashMap < OType , ODocumentFieldOTypeHandlingStrategy > ( ) ; switch ( strategy ) { case SINGLE_ORECORD_BYTES : typeHandlingStrategies . put ( OType . BINARY , new ODocumentSingleRecordBytesOTypeHandlingStrategy ( ) ) ; break ; case SPLIT_ORECORD_BYTES : typeHandlingStrategies . put ( OType . BINARY , new ODocumentSplitRecordBytesOTypeHandlingStrategy ( ) ) ; break ; case SIMPLE : default : break ; } ODocumentSmartFieldHandlingStrategy strategyInstance = new ODocumentSmartFieldHandlingStrategy ( typeHandlingStrategies ) ; ODocumentFieldHandlingStrategyRegistry . getInstance ( ) . registerStrategy ( strategy , strategyInstance ) ; return strategyInstance ;


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

implementation:
if ( iStream == null || iStream . length ( ) == 0 ) // NULL VALUE
return null ; OSerializableStream instance = null ; int propertyPos = iStream . indexOf ( ':' ) ; int pos = iStream . indexOf ( OStringSerializerEmbedded . SEPARATOR ) ; if ( pos < 0 || propertyPos > - 1 && pos > propertyPos ) { instance = new ODocument ( ) ; pos = - 1 ; } else { final String className = iStream . substring ( 0 , pos ) ; try { final Class < ? > clazz = Class . forName ( className ) ; instance = ( OSerializableStream ) clazz . newInstance ( ) ; } catch ( Exception e ) { final String message = "Error on unmarshalling content. Class: " + className ; OLogManager . instance ( ) . error ( this , message , e ) ; throw OException . wrapException ( new OSerializationException ( message ) , e ) ; } } instance . fromStream ( Base64 . getDecoder ( ) . decode ( iStream . substring ( pos + 1 ) ) ) ; return instance ;


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

implementation: if ( iValue != null ) { if ( ! ( iValue instanceof OSerializableStream ) ) throw new OSerializationException ( "Cannot serialize the object since it's not implements the OSerializableStream interface" ) ; OSerializableStream stream = ( OSerializableStream ) iValue ; iOutput . append ( iValue . getClass ( ) . getName ( ) ) ; iOutput . append ( OStringSerializerEmbedded . SEPARATOR ) ; iOutput . append ( Base64 . getEncoder ( ) . encodeToString ( stream . toStream ( ) ) ) ; } return iOutput ;


signature:
public class OSQLFunctionRuntime { /** * Execute a function .
 * @ param iCurrentRecord
 * Current record
 * @ param iCurrentResult
 * TODO
 * @ param iContext
 * @ return */
public Object execute ( final Object iThis , final OIdentifiable iCurrentRecord , final Object iCurrentResult , final OCommandContext iContext ) { } }

implementation:
// RESOLVE VALUES USING THE CURRENT RECORD
for ( int i = 0 ; i < configuredParameters . length ; ++ i ) { runtimeParameters [ i ] = configuredParameters [ i ] ; if ( configuredParameters [ i ] instanceof OSQLFilterItemField ) { runtimeParameters [ i ] = ( ( OSQLFilterItemField ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OSQLFunctionRuntime ) runtimeParameters [ i ] = ( ( OSQLFunctionRuntime ) configuredParameters [ i ] ) . execute ( iThis , iCurrentRecord , iCurrentResult , iContext ) ; else if ( configuredParameters [ i ] instanceof OSQLFilterItemVariable ) { runtimeParameters [ i ] = ( ( OSQLFilterItemVariable ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OCommandSQL ) { try { runtimeParameters [ i ] = ( ( OCommandSQL ) configuredParameters [ i ] ) . setContext ( iContext ) . execute ( ) ; } catch ( OCommandExecutorNotFoundException ignore ) { // TRY WITH SIMPLE CONDITION
final String text = ( ( OCommandSQL ) configuredParameters [ i ] ) . getText ( ) ; final OSQLPredicate pred = new OSQLPredicate ( text ) ; runtimeParameters [ i ] = pred . evaluate ( iCurrentRecord instanceof ORecord ? ( ORecord ) iCurrentRecord : null , ( ODocument ) iCurrentResult , iContext ) ; // REPLACE ORIGINAL PARAM
configuredParameters [ i ] = pred ; } } else if ( configuredParameters [ i ] instanceof OSQLPredicate ) runtimeParameters [ i ] = ( ( OSQLPredicate ) configuredParameters [ i ] ) . evaluate ( iCurrentRecord . getRecord ( ) , ( iCurrentRecord instanceof ODocument ? ( ODocument ) iCurrentResult : null ) , iContext ) ; else if ( configuredParameters [ i ] instanceof String ) { if ( configuredParameters [ i ] . toString ( ) . startsWith ( "\"" ) || configuredParameters [ i ] . toString ( ) . startsWith ( "'" ) ) runtimeParameters [ i ] = OIOUtils . getStringContent ( configuredParameters [ i ] ) ; } } if ( function . getMaxParams ( ) == - 1 || function . getMaxParams ( ) > 0 ) { if ( runtimeParameters . length < function . getMinParams ( ) || ( function . getMaxParams ( ) > - 1 && runtimeParameters . length > function . getMaxParams ( ) ) ) throw new OCommandExecutionException ( "Syntax error: function '" + function . getName ( ) + "' needs " + ( function . getMinParams ( ) == function . getMaxParams ( ) ? function . getMinParams ( ) : function . getMinParams ( ) + "-" + function . getMaxParams ( ) ) + " argument(s) while has been received " + runtimeParameters . length ) ; } final Object functionResult = function . execute ( iThis , iCurrentRecord , iCurrentResult , runtimeParameters , iContext ) ; if ( functionResult instanceof OAutoConvertToRecord ) // FORCE AVOIDING TO CONVERT IN RECORD
( ( OAutoConvertToRecord ) functionResult ) . setAutoConvertToRecord ( false ) ; return transformValue ( iCurrentRecord , iContext , functionResult ) ;


signature:
public class OUser { /** * Checks if the user has the permission to access to the requested resource for the requested operation .
 * @ param iOperation Requested operation
 * @ return The role that has granted the permission if any , otherwise a OSecurityAccessException exception is raised
 * @ throws OSecurityAccessException */
public ORole allow ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific , final int iOperation ) { } }

implementation: if ( roles == null || roles . isEmpty ( ) ) { if ( document . field ( "roles" ) != null && ! ( ( Collection < OIdentifiable > ) document . field ( "roles" ) ) . isEmpty ( ) ) { final ODocument doc = document ; document = null ; fromStream ( doc ) ; } else throw new OSecurityAccessException ( document . getDatabase ( ) . getName ( ) , "User '" + document . field ( "name" ) + "' has no role defined" ) ; } final ORole role = checkIfAllowed ( resourceGeneric , resourceSpecific , iOperation ) ; if ( role == null ) throw new OSecurityAccessException ( document . getDatabase ( ) . getName ( ) , "User '" + document . field ( "name" ) + "' does not have permission to execute the operation '" + ORole . permissionToString ( iOperation ) + "' against the resource: " + resourceGeneric + "." + resourceSpecific ) ; return role ;


signature:
public class OUser { /** * Checks if a rule was defined for the user .
 * @ return True is a rule is defined , otherwise false */
public boolean isRuleDefined ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific ) { } }

implementation: for ( ORole r : roles ) if ( r == null ) OLogManager . instance ( ) . warn ( this , "User '%s' has a null role, bypass it. Consider to fix this user roles before to continue" , getName ( ) ) ; else if ( r . hasRule ( resourceGeneric , resourceSpecific ) ) return true ; return false ;


signature:
public class ODistributedOutput { /** * Create a compact string with all the relevant information .
 * @ param manager
 * @ param distribCfg
 * @ return */
public static String getCompactServerStatus ( final ODistributedServerManager manager , final ODocument distribCfg ) { } }

implementation: final StringBuilder buffer = new StringBuilder ( ) ; final Collection < ODocument > members = distribCfg . field ( "members" ) ; if ( members != null ) { buffer . append ( members . size ( ) ) ; buffer . append ( ":[" ) ; int memberCount = 0 ; for ( ODocument m : members ) { if ( m == null ) continue ; if ( memberCount ++ > 0 ) buffer . append ( "," ) ; final String serverName = m . field ( "name" ) ; buffer . append ( serverName ) ; buffer . append ( ( Object ) m . field ( "status" ) ) ; final Collection < String > databases = m . field ( "databases" ) ; if ( databases != null ) { buffer . append ( "{" ) ; int dbCount = 0 ; for ( String dbName : databases ) { final ODistributedConfiguration dbCfg = manager . getDatabaseConfiguration ( dbName , false ) ; if ( dbCfg == null ) continue ; if ( dbCount ++ > 0 ) buffer . append ( "," ) ; buffer . append ( dbName ) ; buffer . append ( "=" ) ; buffer . append ( manager . getDatabaseStatus ( serverName , dbName ) ) ; buffer . append ( " (" ) ; buffer . append ( dbCfg . getServerRole ( serverName ) ) ; buffer . append ( ")" ) ; } buffer . append ( "}" ) ; } } buffer . append ( "]" ) ; } return buffer . toString ( ) ;


signature:
public class OHazelcastPlugin { /** * Protecte system database from being replicated */
protected void initSystemDatabase ( ) { } }

implementation: final ODocument defaultCfg = getStorage ( OSystemDatabase . SYSTEM_DB_NAME ) . loadDatabaseConfiguration ( getDefaultDatabaseConfigFile ( ) ) ; defaultCfg . field ( "autoDeploy" , false ) ; final OModifiableDistributedConfiguration sysCfg = new OModifiableDistributedConfiguration ( defaultCfg ) ; sysCfg . removeServer ( "<NEW_NODE>" ) ; messageService . registerDatabase ( OSystemDatabase . SYSTEM_DB_NAME , sysCfg ) ; sysCfg . addNewNodeInServerList ( getLocalNodeName ( ) ) ;


signature:
public class OHazelcastPlugin { /** * Initializes all the available server ' s databases as distributed . */
protected void loadLocalDatabases ( ) { } }

implementation:
final List < String > dbs = new ArrayList < String > ( serverInstance . getAvailableStorageNames ( ) . keySet ( ) ) ; Collections . sort ( dbs ) ; for ( final String databaseName : dbs ) { if ( messageService . getDatabase ( databaseName ) == null ) { ODistributedServerLog . info ( this , nodeName , null , DIRECTION . NONE , "Opening database '%s'..." , databaseName ) ; // INIT THE STORAGE
final ODistributedStorage stg = getStorage ( databaseName ) ; executeInDistributedDatabaseLock ( databaseName , 60000 , null , new OCallable < Object , OModifiableDistributedConfiguration > ( ) { @ Override public Object call ( OModifiableDistributedConfiguration cfg ) { ODistributedServerLog . info ( this , nodeName , null , DIRECTION . NONE , "Current node started as %s for database '%s'" , cfg . getServerRole ( nodeName ) , databaseName ) ; final ODistributedDatabaseImpl ddb = messageService . registerDatabase ( databaseName , cfg ) ; ddb . resume ( ) ; // 1ST NODE TO HAVE THE DATABASE
cfg . addNewNodeInServerList ( nodeName ) ; // COLLECT ALL THE CLUSTERS WITH REMOVED NODE AS OWNER
reassignClustersOwnership ( nodeName , databaseName , cfg , true ) ; try { ddb . getSyncConfiguration ( ) . setLastLSN ( nodeName , ( ( OAbstractPaginatedStorage ) stg . getUnderlying ( ) ) . getLSN ( ) , false ) ; } catch ( IOException e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , "Error on saving distributed LSN for database '%s' (err=%s)." , databaseName , e . getMessage ( ) ) ; } ddb . setOnline ( ) ; return null ; } } ) ; } }


signature:
public class OHazelcastPlugin { /** * Removes the node map entry . */
@ Override public void memberRemoved ( final MembershipEvent iEvent ) { } }

implementation: try { updateLastClusterChange ( ) ; if ( iEvent . getMember ( ) == null ) return ; final String nodeLeftName = getNodeName ( iEvent . getMember ( ) ) ; if ( nodeLeftName == null ) return ; removeServer ( nodeLeftName , true ) ; } catch ( HazelcastInstanceNotActiveException | RetryableHazelcastException e ) { OLogManager . instance ( ) . error ( this , "Hazelcast is not running" , e ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Error on removing the server '%s'" , e , getNodeName ( iEvent . getMember ( ) ) ) ; }


signature:
public class OHazelcastPlugin { /** * Elects a new server as coordinator . The election browse the ordered server list . */
@ Override public String electNewLockManager ( ) { } }

implementation:
if ( hazelcastInstance == null ) throw new HazelcastInstanceNotActiveException ( ) ; final ILock lock = hazelcastInstance . getLock ( "orientdb.lockManagerElection" ) ; lock . lock ( ) ; try { // TRY ALL THE SERVERS IN ORDER ( ALL THE SERVERS HAVE THE SAME LIST )
String lockManagerServer = getLockManagerRequester ( ) . getServer ( ) ; // PROTECT FROM DOUBLE LOCK MANAGER ELECTION IN CASE OF REMOVE OF LOCK MANAGER
if ( lockManagerServer != null && getActiveServers ( ) . contains ( lockManagerServer ) ) return lockManagerServer ; final String originalLockManager = lockManagerServer ; ODistributedServerLog . debug ( this , nodeName , originalLockManager , DIRECTION . OUT , "lock '%s' is unreachable, electing a new lock..." , originalLockManager ) ; int lockManagerServerId = - 1 ; if ( lockManagerServer != null && registeredNodeByName . containsKey ( lockManagerServer ) ) lockManagerServerId = registeredNodeByName . get ( lockManagerServer ) ; String newServer = null ; int currIndex = lockManagerServerId ; for ( int i = 0 ; i < registeredNodeById . size ( ) ; ++ i ) { currIndex ++ ; if ( currIndex >= registeredNodeById . size ( ) ) // RESTART FROM THE FIRST
currIndex = 0 ; newServer = registeredNodeById . get ( currIndex ) ; if ( newServer == null ) throw new OConfigurationException ( "Found null server at index " + currIndex + " of server list " + registeredNodeById ) ; if ( newServer . equalsIgnoreCase ( getLocalNodeName ( ) ) || activeNodes . containsKey ( newServer ) ) { // TODO : IMPROVE ELECTION BY CHECKING AL THE NODES AGREE ON IT
ODistributedServerLog . debug ( this , nodeName , newServer , DIRECTION . OUT , "Trying to elected server '%s' as new lock (old=%s)..." , newServer , originalLockManager ) ; try { getLockManagerRequester ( ) . setServer ( newServer ) ; configurationMap . put ( CONFIG_LOCKMANAGER , getLockManagerRequester ( ) . getServer ( ) ) ; ODistributedServerLog . info ( this , nodeName , newServer , DIRECTION . OUT , "Elected server '%s' as new lock (old=%s)" , newServer , originalLockManager ) ; break ; } catch ( Exception e ) { // NO SERVER RESPONDED , THE SERVER COULD BE ISOLATED , GO AHEAD WITH THE NEXT IN THE LIST
ODistributedServerLog . info ( this , nodeName , newServer , DIRECTION . OUT , "Error on electing server '%s' as new lock (error: %s)" , newServer , e ) ; } } } return newServer ; } finally { lock . unlock ( ) ; }


signature:
public class OHazelcastPlugin { /** * ASSIGN THE LOCK MANAGER AT STARTUP */
private void assignLockManagerFromCluster ( ) { } }

implementation:
String lockManagerServer = null ; while ( lockManagerServer == null ) { if ( activeNodes . size ( ) == 1 ) { // ONLY CURRENT NODE ONLINE , SET IT AS INITIAL LOCK MANAGER
lockManagerServer = nodeName ; if ( configurationMap . putIfAbsent ( CONFIG_LOCKMANAGER , lockManagerServer ) == null ) break ; } else { lockManagerServer = ( String ) configurationMap . get ( CONFIG_LOCKMANAGER ) ; if ( lockManagerServer != null && lockManagerServer . equals ( nodeName ) ) { // LAST LOCK MANAGER WAS CURRENT NODE ? TRY TO FORCE A NEW ELECTION
OLogManager . instance ( ) . info ( this , "Found lock as current node, even if it was offline. Forcing a new election..." ) ; getLockManagerRequester ( ) . setServer ( lockManagerServer ) ; lockManagerServer = electNewLockManager ( ) ; break ; } if ( lockManagerServer != null ) break ; } try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { break ; } } getLockManagerRequester ( ) . setServer ( lockManagerServer ) ; OLogManager . instance ( ) . info ( this , "Distributed Lock Manager server is '%s'" , lockManagerServer ) ;


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

implementation: buffer . putLong ( Double . doubleToLongBits ( object ) ) ;


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

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


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

implementation: OLinkSerializer . INSTANCE . serializeInByteBufferObject ( object , buffer ) ;


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

implementation: return OLinkSerializer . INSTANCE . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ;


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

implementation: return OLinkSerializer . INSTANCE . getObjectSizeInByteBuffer ( buffer , walChanges , offset ) ;


signature:
public class OMicroTransaction { /** * Commits the micro - transaction if it ' s a top - level micro - transaction . */
public void commit ( ) { } }

implementation: if ( ! active ) throw error ( "Inactive micro-transaction on commit" ) ; if ( level < 1 ) throw error ( "Unbalanced micro-transaction, level = " + level ) ; -- level ; if ( level == 0 ) { active = false ; doCommit ( ) ; }


signature:
public class OMicroTransaction { /** * Rollbacks the micro - transaction if it ' s a top - level micro - transaction . */
public void rollback ( ) { } }

implementation: if ( ! active ) throw error ( "Inactive micro-transaction on rollback" ) ; if ( level < 1 ) throw error ( "Unbalanced micro-transaction, level = " + level ) ; -- level ; if ( level == 0 ) { active = false ; doRollback ( ) ; }


signature:
public class OMicroTransaction { /** * Updates the record identity after its successful commit . */
public void updateIdentityAfterRecordCommit ( final ORID oldRid , final ORID newRid ) { } }

implementation:
if ( oldRid . equals ( newRid ) ) return ; // no change , ignore
// XXX : Identity update may mutate the index keys , so we have to identify and reinsert potentially affected index keys to keep
// the OTransactionIndexChanges . changesPerKey in a consistent state .
final List < KeyChangesUpdateRecord > keyRecordsToReinsert = new ArrayList < > ( ) ; final OIndexManager indexManager = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) ; for ( Map . Entry < String , OTransactionIndexChanges > entry : indexOperations . entrySet ( ) ) { final OIndex < ? > index = indexManager . getIndex ( entry . getKey ( ) ) ; if ( index == null ) throw new OTransactionException ( "Cannot find index '" + entry . getValue ( ) + "' while committing transaction" ) ; final Dependency [ ] fieldRidDependencies = getIndexFieldRidDependencies ( index ) ; if ( ! isIndexMayDependOnRids ( fieldRidDependencies ) ) continue ; final OTransactionIndexChanges indexChanges = entry . getValue ( ) ; for ( final Iterator < OTransactionIndexChangesPerKey > iterator = indexChanges . changesPerKey . values ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { final OTransactionIndexChangesPerKey keyChanges = iterator . next ( ) ; if ( isIndexKeyMayDependOnRid ( keyChanges . key , oldRid , fieldRidDependencies ) ) { keyRecordsToReinsert . add ( new KeyChangesUpdateRecord ( keyChanges , indexChanges ) ) ; iterator . remove ( ) ; } } } // Update the identity .
final ORecordOperation rec = resolveRecordOperation ( oldRid ) ; if ( rec != null ) { updatedRids . put ( newRid . copy ( ) , oldRid . copy ( ) ) ; if ( ! rec . getRecord ( ) . getIdentity ( ) . equals ( newRid ) ) { ORecordInternal . onBeforeIdentityChanged ( rec . getRecord ( ) ) ; final ORecordId recordId = ( ORecordId ) rec . getRecord ( ) . getIdentity ( ) ; if ( recordId == null ) { ORecordInternal . setIdentity ( rec . getRecord ( ) , new ORecordId ( newRid ) ) ; } else { recordId . setClusterPosition ( newRid . getClusterPosition ( ) ) ; recordId . setClusterId ( newRid . getClusterId ( ) ) ; } ORecordInternal . onAfterIdentityChanged ( rec . getRecord ( ) ) ; } } // Reinsert the potentially affected index keys .
for ( KeyChangesUpdateRecord record : keyRecordsToReinsert ) record . indexChanges . changesPerKey . put ( record . keyChanges . key , record . keyChanges ) ; // Update the indexes .
final List < OTransactionRecordIndexOperation > transactionIndexOperations = recordIndexOperations . get ( translateRid ( oldRid ) ) ; if ( transactionIndexOperations != null ) { for ( final OTransactionRecordIndexOperation indexOperation : transactionIndexOperations ) { OTransactionIndexChanges indexEntryChanges = indexOperations . get ( indexOperation . index ) ; if ( indexEntryChanges == null ) continue ; final OTransactionIndexChangesPerKey keyChanges ; if ( indexOperation . key == null ) { keyChanges = indexEntryChanges . nullKeyChanges ; } else { keyChanges = indexEntryChanges . changesPerKey . get ( indexOperation . key ) ; } if ( keyChanges != null ) updateChangesIdentity ( oldRid , newRid , keyChanges ) ; } }


signature:
public class OMicroTransaction { /** * Updates the record cache after unsuccessful micro - transaction commit . */
public void updateRecordCacheAfterRollback ( ) { } }

implementation: final OLocalRecordCache databaseLocalCache = database . getLocalCache ( ) ; for ( ORecordOperation recordOperation : recordOperations . values ( ) ) databaseLocalCache . deleteRecord ( recordOperation . getRecord ( ) . getIdentity ( ) ) ;


signature:
public class OFileUtils { /** * Prepares the path for a file creation or replacement . If the file pointed by the path already exists , it will be deleted , a
 * warning will be emitted to the log in this case . All absent directories along the path will be created .
 * @ param path the file path .
 * @ param requester the requester of an operation being performed to produce user - friendly log messages .
 * @ param operation the description of an operation being performed to produce user - friendly log messages . Use descriptions like
 * " exporting " , " backing up " , etc . */
public static void prepareForFileCreationOrReplacement ( Path path , Object requester , String operation ) throws IOException { } }

implementation: if ( Files . deleteIfExists ( path ) ) OLogManager . instance ( ) . warn ( requester , "'%s' deleted while %s" , path , operation ) ; final Path parent = path . getParent ( ) ; if ( parent != null ) Files . createDirectories ( parent ) ;


signature:
public class OFileUtils { /** * Tries to move a file from the source to the target atomically . If atomic move is not possible , falls back to regular move .
 * @ param source the source to move the file from .
 * @ param target the target to move the file to .
 * @ param requester the requester of the move being performed to produce user - friendly log messages .
 * @ see Files # move ( Path , Path , CopyOption . . . )
 * @ see StandardCopyOption # ATOMIC _ MOVE */
public static void atomicMoveWithFallback ( Path source , Path target , Object requester ) throws IOException { } }

implementation: try { Files . move ( source , target , StandardCopyOption . ATOMIC_MOVE ) ; } catch ( AtomicMoveNotSupportedException ignore ) { OLogManager . instance ( ) . warn ( requester , "atomic file move is not possible, falling back to regular move (moving '%s' to '%s')" , source , target ) ; Files . move ( source , target ) ; }


signature:
public class Pattern { /** * splits this pattern into multiple
 * @ return */
public List < Pattern > getDisjointPatterns ( ) { } }

implementation: Map < PatternNode , String > reverseMap = new IdentityHashMap < > ( ) ; reverseMap . putAll ( this . aliasToNode . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( x -> x . getValue ( ) , x -> x . getKey ( ) ) ) ) ; List < Pattern > result = new ArrayList < > ( ) ; while ( ! reverseMap . isEmpty ( ) ) { Pattern pattern = new Pattern ( ) ; result . add ( pattern ) ; Map . Entry < PatternNode , String > nextNode = reverseMap . entrySet ( ) . iterator ( ) . next ( ) ; Set < PatternNode > toVisit = new HashSet < > ( ) ; toVisit . add ( nextNode . getKey ( ) ) ; while ( toVisit . size ( ) > 0 ) { PatternNode currentNode = toVisit . iterator ( ) . next ( ) ; toVisit . remove ( currentNode ) ; if ( reverseMap . containsKey ( currentNode ) ) { pattern . aliasToNode . put ( reverseMap . get ( currentNode ) , currentNode ) ; reverseMap . remove ( currentNode ) ; for ( PatternEdge x : currentNode . out ) { toVisit . add ( x . in ) ; } for ( PatternEdge x : currentNode . in ) { toVisit . add ( x . out ) ; } } } pattern . recalculateNumOfEdges ( ) ; } return result ;


signature:
public class ODistributedStorage { /** * Only idempotent commands that don ' t involve any other node can be executed locally . */
protected boolean executeOnlyLocally ( final String localNodeName , final ODistributedConfiguration dbCfg , final OCommandExecutor exec , final Collection < String > involvedClusters , final Collection < String > nodes ) { } }

implementation:
boolean executeLocally = false ; if ( exec . isIdempotent ( ) ) { final int availableNodes = nodes . size ( ) ; // IDEMPOTENT : CHECK IF CAN WORK LOCALLY ONLY
int maxReadQuorum ; if ( involvedClusters . isEmpty ( ) ) maxReadQuorum = dbCfg . getReadQuorum ( null , availableNodes , localNodeName ) ; else { maxReadQuorum = 0 ; for ( String cl : involvedClusters ) maxReadQuorum = Math . max ( maxReadQuorum , dbCfg . getReadQuorum ( cl , availableNodes , localNodeName ) ) ; } if ( nodes . contains ( localNodeName ) && maxReadQuorum <= 1 ) executeLocally = true ; } return executeLocally ; } public boolean isLocalEnv ( ) { return localDistributedDatabase == null || dManager == null || distributedConfiguration == null || OScenarioThreadLocal . INSTANCE . isRunModeDistributed ( ) ; } public OStorageOperationResult < ORawBuffer > readRecord ( final ORecordId iRecordId , final String iFetchPlan , final boolean iIgnoreCache , final boolean prefetchRecords , final ORecordCallback < ORawBuffer > iCallback ) { if ( isLocalEnv ( ) ) { // ALREADY DISTRIBUTED
return wrapped . readRecord ( iRecordId , iFetchPlan , iIgnoreCache , prefetchRecords , iCallback ) ; } final ORawBuffer memCopy = localDistributedDatabase . getRecordIfLocked ( iRecordId ) ; if ( memCopy != null ) return new OStorageOperationResult < ORawBuffer > ( memCopy ) ; try { final String clusterName = getClusterNameByRID ( iRecordId ) ; final ODistributedConfiguration dbCfg = distributedConfiguration ; final List < String > nodes = dbCfg . getServers ( clusterName , null ) ; final int availableNodes = nodes . size ( ) ; // CHECK IF LOCAL NODE OWNS THE DATA AND READ - QUORUM = 1 : GET IT LOCALLY BECAUSE IT ' S FASTER
final String localNodeName = dManager . getLocalNodeName ( ) ; if ( nodes . isEmpty ( ) || nodes . contains ( dManager . getLocalNodeName ( ) ) && dbCfg . getReadQuorum ( clusterName , availableNodes , localNodeName ) <= 1 ) { // DON ' T REPLICATE
return ( OStorageOperationResult < ORawBuffer > ) OScenarioThreadLocal . executeAsDistributed ( new Callable ( ) { @ Override public Object call ( ) throws Exception { return wrapped . readRecord ( iRecordId , iFetchPlan , iIgnoreCache , prefetchRecords , iCallback ) ; } } ) ; } final OReadRecordTask task = ( ( OReadRecordTask ) dManager . getTaskFactoryManager ( ) . getFactoryByServerNames ( nodes ) . createTask ( OReadRecordTask . FACTORYID ) ) . init ( iRecordId ) ; // DISTRIBUTE IT
final ODistributedResponse response = dManager . sendRequest ( getName ( ) , Collections . singleton ( clusterName ) , nodes , task , dManager . getNextMessageIdCounter ( ) , EXECUTION_MODE . RESPONSE , null , null , null ) ; final Object dResult = response != null ? response . getPayload ( ) : null ; if ( dResult instanceof ONeedRetryException ) throw ( ONeedRetryException ) dResult ; else if ( dResult instanceof Exception ) throw OException . wrapException ( new ODistributedException ( "Error on execution distributed read record" ) , ( Exception ) dResult ) ; return new OStorageOperationResult < ORawBuffer > ( ( ORawBuffer ) dResult ) ; } catch ( ONeedRetryException e ) { // PASS THROUGH
throw e ; } catch ( Exception e ) { handleDistributedException ( "Cannot route read record operation for %s to the distributed node" , e , iRecordId ) ; // UNREACHABLE
return null ; } } @ Override public OStorageOperationResult < ORawBuffer > readRecordIfVersionIsNotLatest ( final ORecordId rid , final String fetchPlan , final boolean ignoreCache , final int recordVersion ) throws ORecordNotFoundException { if ( isLocalEnv ( ) ) { return wrapped . readRecordIfVersionIsNotLatest ( rid , fetchPlan , ignoreCache , recordVersion ) ; } final ORawBuffer memCopy = localDistributedDatabase . getRecordIfLocked ( rid ) ; if ( memCopy != null ) return new OStorageOperationResult < ORawBuffer > ( memCopy ) ; try { final String clusterName = getClusterNameByRID ( rid ) ; final ODistributedConfiguration dbCfg = distributedConfiguration ; final List < String > nodes = dbCfg . getServers ( clusterName , null ) ; final int availableNodes = nodes . size ( ) ; // CHECK IF LOCAL NODE OWNS THE DATA AND READ - QUORUM = 1 : GET IT LOCALLY BECAUSE IT ' S FASTER
final String localNodeName = dManager . getLocalNodeName ( ) ; if ( nodes . isEmpty ( ) || nodes . contains ( dManager . getLocalNodeName ( ) ) && dbCfg . getReadQuorum ( clusterName , availableNodes , localNodeName ) <= 1 ) { // DON ' T REPLICATE
return ( OStorageOperationResult < ORawBuffer > ) OScenarioThreadLocal . executeAsDistributed ( new Callable ( ) { @ Override public Object call ( ) throws Exception { return wrapped . readRecordIfVersionIsNotLatest ( rid , fetchPlan , ignoreCache , recordVersion ) ; } } ) ; } final OReadRecordIfNotLatestTask task = ( OReadRecordIfNotLatestTask ) dManager . getTaskFactoryManager ( ) . getFactoryByServerNames ( nodes ) . createTask ( OReadRecordIfNotLatestTask . FACTORYID ) ; task . init ( rid , recordVersion ) ; // DISTRIBUTE IT
final Object result = dManager . sendRequest ( getName ( ) , Collections . singleton ( clusterName ) , nodes , task , dManager . getNextMessageIdCounter ( ) , EXECUTION_MODE . RESPONSE , null , null , null ) . getPayload ( ) ; if ( result instanceof ONeedRetryException ) throw ( ONeedRetryException ) result ; else if ( result instanceof Exception ) throw OException . wrapException ( new ODistributedException ( "Error on execution distributed read record" ) , ( Exception ) result ) ; return new OStorageOperationResult < ORawBuffer > ( ( ORawBuffer ) result ) ; } catch ( ONeedRetryException e ) { // PASS THROUGH
throw e ; } catch ( Exception e ) { handleDistributedException ( "Cannot route read record operation for %s to the distributed node" , e , rid ) ; // UNREACHABLE
return null ; } } @ Override public OStorageOperationResult < Boolean > deleteRecord ( final ORecordId iRecordId , final int iVersion , final int iMode , final ORecordCallback < Boolean > iCallback ) { // IF is a real delete should be with a tx
return wrapped . deleteRecord ( iRecordId , iVersion , iMode , iCallback ) ;


signature:
public class JPAHandler { /** * Collect up the characters , as element ' s characters may be split across multiple calls . Isn ' t SAX lovely . . . */
@ Override public void characters ( char [ ] ch , int start , int length ) throws SAXException { } }

implementation: builder . append ( ch , start , length ) ;


signature:
public class OLuceneDateTools { /** * Converts a string produced by < code > timeToString < / code > or
 * < code > dateToString < / code > back to a time , represented as a
 * Date object .
 * @ param dateString the date string to be converted
 * @ return the parsed time as a Date object
 * @ throws ParseException if < code > dateString < / code > is not in the expected format */
public static Date stringToDate ( String dateString ) throws ParseException { } }

implementation:
try { SimpleDateFormat format = RESOLUTIONS [ dateString . length ( ) ] . format ( ) ; return format . parse ( dateString ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( OLuceneDateTools . class , "Exception is suppressed, original exception is " , e ) ; // noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException
throw new ParseException ( "Input is not a valid date string: " + dateString , 0 ) ; }


signature:
public class OChannelBinaryAsynchClient { /** * Tells if the channel is connected .
 * @ return true if it ' s connected , otherwise false . */
public boolean isConnected ( ) { } }

implementation: final Socket s = socket ; return s != null && ! s . isClosed ( ) && s . isConnected ( ) && ! s . isInputShutdown ( ) && ! s . isOutputShutdown ( ) ;


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

implementation: if ( name == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; if ( name . isEmpty ( ) ) throw new OCommandExecutionException ( "Syntax Error. You must specify a function name: " + getSyntax ( ) ) ; if ( code == null || code . isEmpty ( ) ) throw new OCommandExecutionException ( "Syntax Error. You must specify the function code: " + getSyntax ( ) ) ; ODatabaseDocument database = getDatabase ( ) ; final OFunction f = database . getMetadata ( ) . getFunctionLibrary ( ) . createFunction ( name ) ; f . setCode ( code ) ; f . setIdempotent ( idempotent ) ; if ( parameters != null ) f . setParameters ( parameters ) ; if ( language != null ) f . setLanguage ( language ) ; f . save ( ) ; return f . getId ( ) ;


signature:
public class OByteBufferUtils { /** * Merge short value from two byte buffer . First byte of short will be extracted from first byte buffer and second from second
 * one .
 * @ param buffer
 * to read first part of value
 * @ param buffer1
 * to read second part of value
 * @ return merged value */
public static short mergeShortFromBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 ) { } }

implementation: short result = 0 ; result = ( short ) ( result | ( buffer . get ( ) & MASK ) ) ; result = ( short ) ( result << SIZE_OF_BYTE_IN_BITS ) ; result = ( short ) ( result | ( buffer1 . get ( ) & MASK ) ) ; return result ;


signature:
public class OByteBufferUtils { /** * Merge int value from two byte buffer . First bytes of int will be extracted from first byte buffer and second from second one .
 * How many bytes will be read from first buffer determines based on < code > buffer . remaining ( ) < / code > value
 * @ param buffer
 * to read first part of value
 * @ param buffer1
 * to read second part of value
 * @ return merged value */
public static int mergeIntFromBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 ) { } }

implementation: int result = 0 ; final int remaining = buffer . remaining ( ) ; for ( int i = 0 ; i < remaining ; ++ i ) { result = result | ( buffer . get ( ) & MASK ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } for ( int i = 0 ; i < SIZE_OF_INT - remaining - 1 ; ++ i ) { result = result | ( buffer1 . get ( ) & MASK ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } result = result | ( buffer1 . get ( ) & MASK ) ; return result ;


signature:
public class OByteBufferUtils { /** * Merge long value from two byte buffer . First bytes of long will be extracted from first byte buffer and second from second one .
 * How many bytes will be read from first buffer determines based on < code > buffer . remaining ( ) < / code > value
 * @ param buffer
 * to read first part of value
 * @ param buffer1
 * to read second part of value
 * @ return merged value */
public static long mergeLongFromBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 ) { } }

implementation: long result = 0 ; final int remaining = buffer . remaining ( ) ; for ( int i = 0 ; i < remaining ; ++ i ) { result = result | ( MASK & buffer . get ( ) ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } for ( int i = 0 ; i < SIZE_OF_LONG - remaining - 1 ; ++ i ) { result = result | ( MASK & buffer1 . get ( ) ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } result = result | ( MASK & buffer1 . get ( ) ) ; return result ;


signature:
public class OByteBufferUtils { /** * Split short value into two byte buffer . First byte of short will be written to first byte buffer and second to second one .
 * @ param buffer
 * to write first part of value
 * @ param buffer1
 * to write second part of value */
public static void splitShortToBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 , final short iValue ) { } }

implementation: buffer . put ( ( byte ) ( MASK & ( iValue >>> SIZE_OF_BYTE_IN_BITS ) ) ) ; buffer1 . put ( ( byte ) ( MASK & iValue ) ) ;


signature:
public class OByteBufferUtils { /** * Split int value into two byte buffer . First byte of int will be written to first byte buffer and second to second one . How many
 * bytes will be written to first buffer determines based on < code > buffer . remaining ( ) < / code > value
 * @ param buffer
 * to write first part of value
 * @ param buffer1
 * to write second part of value */
public static void splitIntToBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 , final int iValue ) { } }

implementation: final int remaining = buffer . remaining ( ) ; int i ; for ( i = 0 ; i < remaining ; ++ i ) { buffer . put ( ( byte ) ( MASK & ( iValue >>> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_INT - i - 1 ) ) ) ) ; } for ( int j = 0 ; j < SIZE_OF_INT - remaining ; ++ j ) { buffer1 . put ( ( byte ) ( MASK & ( iValue >>> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_INT - i - j - 1 ) ) ) ) ; }


signature:
public class OByteBufferUtils { /** * Split long value into two byte buffer . First byte of long will be written to first byte buffer and second to second one . How
 * many bytes will be written to first buffer determines based on < code > buffer . remaining ( ) < / code > value
 * @ param buffer
 * to write first part of value
 * @ param buffer1
 * to write second part of value */
public static void splitLongToBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 , final long iValue ) { } }

implementation: final int remaining = buffer . remaining ( ) ; int i ; for ( i = 0 ; i < remaining ; ++ i ) { buffer . put ( ( byte ) ( iValue >> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_LONG - i - 1 ) ) ) ; } for ( int j = 0 ; j < SIZE_OF_LONG - remaining ; ++ j ) { buffer1 . put ( ( byte ) ( iValue >> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_LONG - i - j - 1 ) ) ) ; }


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

implementation:
if ( type == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseDocument database = getDatabase ( ) ; final OClassEmbedded sourceClass = ( OClassEmbedded ) database . getMetadata ( ) . getSchema ( ) . getClass ( className ) ; if ( sourceClass == null ) throw new OCommandExecutionException ( "Source class '" + className + "' not found" ) ; OPropertyImpl prop = ( OPropertyImpl ) sourceClass . getProperty ( fieldName ) ; if ( prop != null ) { if ( ifNotExists ) { return sourceClass . properties ( ) . size ( ) ; } throw new OCommandExecutionException ( "Property '" + className + "." + fieldName + "' already exists. Remove it before to retry." ) ; } // CREATE THE PROPERTY
OClass linkedClass = null ; OType linkedType = null ; if ( linked != null ) { // FIRST SEARCH BETWEEN CLASSES
linkedClass = database . getMetadata ( ) . getSchema ( ) . getClass ( linked ) ; if ( linkedClass == null ) // NOT FOUND : SEARCH BETWEEN TYPES
linkedType = OType . valueOf ( linked . toUpperCase ( Locale . ENGLISH ) ) ; } // CREATE IT LOCALLY
OPropertyImpl internalProp = sourceClass . addPropertyInternal ( fieldName , type , linkedType , linkedClass , unsafe ) ; if ( readonly ) { internalProp . setReadonly ( true ) ; } if ( mandatory ) { internalProp . setMandatory ( true ) ; } if ( notnull ) { internalProp . setNotNull ( true ) ; } if ( max != null ) { internalProp . setMax ( max ) ; } if ( min != null ) { internalProp . setMin ( min ) ; } if ( defaultValue != null ) { internalProp . setDefaultValue ( defaultValue ) ; } return sourceClass . properties ( ) . size ( ) ;


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

implementation:
if ( attribute == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final List < OCluster > clusters = getClusters ( ) ; if ( clusters . isEmpty ( ) ) throw new OCommandExecutionException ( "Cluster '" + clusterName + "' not found" ) ; Object result = null ; for ( OCluster cluster : getClusters ( ) ) { if ( clusterId > - 1 && clusterName . equals ( String . valueOf ( clusterId ) ) ) { clusterName = cluster . getName ( ) ; } else { clusterId = cluster . getId ( ) ; } try { if ( attribute == ATTRIBUTES . STATUS && OStorageClusterConfiguration . STATUS . OFFLINE . toString ( ) . equalsIgnoreCase ( value ) ) // REMOVE CACHE OF COMMAND RESULTS IF ACTIVE
getDatabase ( ) . getMetadata ( ) . getCommandCache ( ) . invalidateResultsOfCluster ( clusterName ) ; if ( attribute == ATTRIBUTES . NAME ) // REMOVE CACHE OF COMMAND RESULTS IF ACTIVE
getDatabase ( ) . getMetadata ( ) . getCommandCache ( ) . invalidateResultsOfCluster ( clusterName ) ; result = cluster . set ( attribute , value ) ; } catch ( IOException ioe ) { throw OException . wrapException ( new OCommandExecutionException ( "Error altering cluster '" + clusterName + "'" ) , ioe ) ; } } return result ;


signature:
public class OIndexFullText { /** * Indexes a value and save the index . Splits the value in single words and index each one . Save of the index is responsibility of
 * the caller . */
@ Override public OIndexFullText put ( Object key , final OIdentifiable singleValue ) { } }

implementation:
if ( key == null ) { return this ; } key = getCollatingValue ( key ) ; final Set < String > words = splitIntoWords ( key . toString ( ) ) ; // FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT
for ( final String word : words ) { acquireSharedLock ( ) ; try { if ( apiVersion == 0 ) { doPutV0 ( singleValue , word ) ; } else if ( apiVersion == 1 ) { doPutV1 ( singleValue , word ) ; } else { throw new IllegalStateException ( "Invalid API version, " + apiVersion ) ; } } finally { releaseSharedLock ( ) ; } } return this ;


signature:
public class OIndexFullText { /** * Splits passed in key on several words and remove records with keys equals to any item of split result and values equals to
 * passed in value .
 * @ param key Key to remove .
 * @ param value Value to remove .
 * @ return < code > true < / code > if at least one record is removed . */
@ Override public boolean remove ( Object key , final OIdentifiable value ) { } }

implementation: if ( key == null ) { return false ; } key = getCollatingValue ( key ) ; final Set < String > words = splitIntoWords ( key . toString ( ) ) ; final OModifiableBoolean removed = new OModifiableBoolean ( false ) ; for ( final String word : words ) { acquireSharedLock ( ) ; try { if ( apiVersion == 0 ) { removeV0 ( value , removed , word ) ; } else if ( apiVersion == 1 ) { removeV1 ( value , removed , word ) ; } else { throw new IllegalStateException ( "Invalid API version, " + apiVersion ) ; } } finally { releaseSharedLock ( ) ; } } return removed . getValue ( ) ;


signature:
public class OSQLQuery { /** * Delegates to the OQueryExecutor the query execution . */
@ SuppressWarnings ( "unchecked" ) public List < T > run ( final Object ... iArgs ) { } }

implementation: final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; if ( database == null ) throw new OQueryParsingException ( "No database configured" ) ; ( ( OMetadataInternal ) database . getMetadata ( ) ) . makeThreadLocalSchemaSnapshot ( ) ; try { setParameters ( iArgs ) ; Object o = database . getStorage ( ) . command ( this ) ; if ( o instanceof List ) { return ( List < T > ) o ; } else { return ( List < T > ) Collections . singletonList ( o ) ; } } finally { ( ( OMetadataInternal ) database . getMetadata ( ) ) . clearThreadLocalSchemaSnapshot ( ) ; }


signature:
public class OSQLQuery { /** * Returns only the first record if any . */
public T runFirst ( final Object ... iArgs ) { } }

implementation: setLimit ( 1 ) ; final List < T > result = execute ( iArgs ) ; return result != null && ! result . isEmpty ( ) ? result . get ( 0 ) : null ;


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

implementation:
assert isLeaf ; int entryPosition = getIntValue ( entryIndex * OIntegerSerializer . INT_SIZE + positionsArrayOffset ) ; // skip key
if ( encryption == null ) { entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedSize = getIntValue ( entryPosition ) ; entryPosition += OIntegerSerializer . INT_SIZE + encryptedSize ; } boolean isLinkValue = getByteValue ( entryPosition ) > 0 ; long link = - 1 ; V value = null ; if ( isLinkValue ) link = deserializeFromDirectMemory ( OLongSerializer . INSTANCE , entryPosition + OByteSerializer . BYTE_SIZE ) ; else value = deserializeFromDirectMemory ( valueSerializer , entryPosition + OByteSerializer . BYTE_SIZE ) ; return new OSBTreeValue < > ( link >= 0 , link , value ) ;


signature:
public class OFileClassic { /** * Shrink the file content ( filledUpTo attribute only ) */
public void shrink ( final long size ) throws IOException { } }

implementation:
int attempts = 0 ; while ( true ) { try { acquireWriteLock ( ) ; try { // noinspection resource
channel . truncate ( HEADER_SIZE + size ) ; this . size = size ; assert this . size >= 0 ; break ; } finally { releaseWriteLock ( ) ; attempts ++ ; } } catch ( final IOException e ) { OLogManager . instance ( ) . error ( this , "Error during file shrink for file '" + getName ( ) + "' " + attempts + "-th attempt" , e ) ; reopenFile ( attempts , e ) ; } }


signature:
public class OFileClassic { /** * Creates the file . */
public void create ( ) throws IOException { } }

implementation: acquireWriteLock ( ) ; try { acquireExclusiveAccess ( ) ; openChannel ( ) ; init ( ) ; setVersion ( OFileClassic . CURRENT_VERSION ) ; version = OFileClassic . CURRENT_VERSION ; initAllocationMode ( ) ; } finally { releaseWriteLock ( ) ; }


signature:
public class OFileClassic { /** * ALWAYS ADD THE HEADER SIZE BECAUSE ON THIS TYPE IS ALWAYS NEEDED */
private long checkRegions ( final long iOffset , final long iLength ) { } }

implementation: acquireReadLock ( ) ; try { if ( iOffset < 0 || iOffset + iLength > size ) { throw new OIOException ( "You cannot access outside the file size (" + size + " bytes). You have requested portion " + iOffset + "-" + ( iOffset + iLength ) + " bytes. File: " + this ) ; } return iOffset + HEADER_SIZE ; } finally { releaseReadLock ( ) ; }


signature:
public class OFileClassic { /** * ( non - Javadoc )
 * @ see com . orientechnologies . orient . core . storage . fs . OFileAAA # open ( ) */
public void open ( ) { } }

implementation: acquireWriteLock ( ) ; try { if ( ! Files . exists ( osFile ) ) { throw new FileNotFoundException ( "File: " + osFile ) ; } acquireExclusiveAccess ( ) ; openChannel ( ) ; init ( ) ; OLogManager . instance ( ) . debug ( this , "Checking file integrity of " + osFile . getFileName ( ) + "..." ) ; if ( version < CURRENT_VERSION ) { setVersion ( CURRENT_VERSION ) ; version = CURRENT_VERSION ; } initAllocationMode ( ) ; } catch ( final IOException e ) { throw OException . wrapException ( new OIOException ( "Error during file open" ) , e ) ; } finally { releaseWriteLock ( ) ; }


signature:
public class OFileClassic { /** * ( non - Javadoc )
 * @ see com . orientechnologies . orient . core . storage . fs . OFileAAA # close ( ) */
public void close ( ) { } }

implementation: int attempts = 0 ; while ( true ) { try { acquireWriteLock ( ) ; try { if ( channel != null && channel . isOpen ( ) ) { channel . close ( ) ; channel = null ; } if ( frnd != null ) { frnd . close ( ) ; frnd = null ; } closeFD ( ) ; } finally { releaseWriteLock ( ) ; attempts ++ ; } releaseExclusiveAccess ( ) ; break ; } catch ( final IOException ioe ) { OLogManager . instance ( ) . error ( this , "Error during closing of file '" + getName ( ) + "' " + attempts + "-th attempt" , ioe ) ; try { reopenFile ( attempts , ioe ) ; } catch ( final IOException e ) { throw OException . wrapException ( new OIOException ( "Error during file close" ) , e ) ; } } }


signature:
public class OFileClassic { /** * ( non - Javadoc )
 * @ see com . orientechnologies . orient . core . storage . fs . OFileAAA # delete ( ) */
public void delete ( ) throws IOException { } }

implementation: int attempts = 0 ; while ( true ) { try { acquireWriteLock ( ) ; try { close ( ) ; if ( osFile != null ) { Files . deleteIfExists ( osFile ) ; } } finally { releaseWriteLock ( ) ; attempts ++ ; } break ; } catch ( final IOException ioe ) { OLogManager . instance ( ) . error ( this , "Error during deletion of file '" + getName ( ) + "' " + attempts + "-th attempt" , ioe ) ; reopenFile ( attempts , ioe ) ; } }


signature:
public class OFileClassic { /** * Replaces the file content with the content of the provided file .
 * @ param newContentFile the new content file to replace the content with . */
public void replaceContentWith ( final Path newContentFile ) throws IOException { } }

implementation: acquireWriteLock ( ) ; try { close ( ) ; Files . copy ( newContentFile , osFile , StandardCopyOption . REPLACE_EXISTING ) ; open ( ) ; } finally { releaseWriteLock ( ) ; }


signature:
public class OStorageRemote { /** * Execute the command remotely and get the results back . */
public Object command ( final OCommandRequestText iCommand ) { } }

implementation: final boolean live = iCommand instanceof OLiveQuery ; final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; final boolean asynch = iCommand instanceof OCommandRequestAsynch && ( ( OCommandRequestAsynch ) iCommand ) . isAsynchronous ( ) ; OCommandRequest request = new OCommandRequest ( database , asynch , iCommand , live ) ; OCommandResponse response = networkOperation ( request , "Error on executing command: " + iCommand ) ; return response . getResult ( ) ;


signature:
public class OStorageRemote { /** * Ends the request and unlock the write lock */
public void endRequest ( final OChannelBinaryAsynchClient iNetwork ) throws IOException { } }

implementation: if ( iNetwork == null ) return ; iNetwork . flush ( ) ; iNetwork . releaseWriteLock ( ) ;


signature:
public class OStorageRemote { /** * Parse the URLs . Multiple URLs must be separated by semicolon ( ; ) */
protected void parseServerURLs ( ) { } }

implementation:
String lastHost = null ; int dbPos = url . indexOf ( '/' ) ; if ( dbPos == - 1 ) { // SHORT FORM
addHost ( url ) ; lastHost = url ; name = url ; } else { name = url . substring ( url . lastIndexOf ( "/" ) + 1 ) ; for ( String host : url . substring ( 0 , dbPos ) . split ( ADDRESS_SEPARATOR ) ) { lastHost = host ; addHost ( host ) ; } } synchronized ( serverURLs ) { if ( serverURLs . size ( ) == 1 && getClientConfiguration ( ) . getValueAsBoolean ( OGlobalConfiguration . NETWORK_BINARY_DNS_LOADBALANCING_ENABLED ) ) { // LOOK FOR LOAD BALANCING DNS TXT RECORD
final String primaryServer = lastHost ; OLogManager . instance ( ) . debug ( this , "Retrieving URLs from DNS '%s' (timeout=%d)..." , primaryServer , getClientConfiguration ( ) . getValueAsInteger ( OGlobalConfiguration . NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT ) ) ; try { final Hashtable < String , String > env = new Hashtable < String , String > ( ) ; env . put ( "java.naming.factory.initial" , "com.sun.jndi.dns.DnsContextFactory" ) ; env . put ( "com.sun.jndi.ldap.connect.timeout" , getClientConfiguration ( ) . getValueAsString ( OGlobalConfiguration . NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT ) ) ; final DirContext ictx = new InitialDirContext ( env ) ; final String hostName = ! primaryServer . contains ( ":" ) ? primaryServer : primaryServer . substring ( 0 , primaryServer . indexOf ( ":" ) ) ; final Attributes attrs = ictx . getAttributes ( hostName , new String [ ] { "TXT" } ) ; final Attribute attr = attrs . get ( "TXT" ) ; if ( attr != null ) { for ( int i = 0 ; i < attr . size ( ) ; ++ i ) { String configuration = ( String ) attr . get ( i ) ; if ( configuration . startsWith ( "\"" ) ) configuration = configuration . substring ( 1 , configuration . length ( ) - 1 ) ; if ( configuration != null ) { final String [ ] parts = configuration . split ( " " ) ; List < String > toAdd = new ArrayList < > ( ) ; for ( String part : parts ) { if ( part . startsWith ( "s=" ) ) { toAdd . add ( part . substring ( "s=" . length ( ) ) ) ; } } if ( toAdd . size ( ) > 0 ) { serverURLs . clear ( ) ; for ( String host : toAdd ) addHost ( host ) ; } } } } } catch ( NamingException ignore ) { } } }


signature:
public class OStorageRemote { /** * Registers the remote server with port . */
protected String addHost ( String host ) { } }

implementation:
if ( host . startsWith ( LOCALHOST ) ) host = LOCAL_IP + host . substring ( "localhost" . length ( ) ) ; if ( host . contains ( "/" ) ) host = host . substring ( 0 , host . indexOf ( "/" ) ) ; // REGISTER THE REMOTE SERVER + PORT
if ( ! host . contains ( ":" ) ) host += ":" + ( clientConfiguration . getValueAsBoolean ( OGlobalConfiguration . CLIENT_USE_SSL ) ? getDefaultSSLPort ( ) : getDefaultPort ( ) ) ; else if ( host . split ( ":" ) . length < 2 || host . split ( ":" ) [ 1 ] . trim ( ) . length ( ) == 0 ) host += ( clientConfiguration . getValueAsBoolean ( OGlobalConfiguration . CLIENT_USE_SSL ) ? getDefaultSSLPort ( ) : getDefaultPort ( ) ) ; // DISABLED BECAUSE THIS DID NOT ALLOW TO CONNECT TO LOCAL HOST ANYMORE IF THE SERVER IS BOUND TO 127.0.0.1
// CONVERT 127.0.0.1 TO THE PUBLIC IP IF POSSIBLE
// if ( host . startsWith ( LOCAL _ IP ) ) {
// try {
// final String publicIP = InetAddress . getLocalHost ( ) . getHostAddress ( ) ;
// host = publicIP + host . substring ( LOCAL _ IP . length ( ) ) ;
// } catch ( UnknownHostException e ) {
// / / IGNORE IT
synchronized ( serverURLs ) { if ( ! serverURLs . contains ( host ) ) { serverURLs . add ( host ) ; OLogManager . instance ( ) . debug ( this , "Registered the new available server '%s'" , host ) ; } } return host ;


signature:
public class OStorageRemote { /** * Acquire a network channel from the pool . Don ' t lock the write stream since the connection usage is exclusive .
 * @ param iCommand id . Ids described at { @ link OChannelBinaryProtocol }
 * @ return connection to server */
public OChannelBinaryAsynchClient beginRequest ( final OChannelBinaryAsynchClient network , final byte iCommand , OStorageRemoteSession session ) throws IOException { } }

implementation: network . beginRequest ( iCommand , session ) ; return network ;


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

implementation: buffer . putShort ( object ) ;


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

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


signature:
public class OLazyCollectionUtil { /** * Gets the current thread database as a ODatabasePojoAbstract , wrapping it where necessary . */
protected static OObjectDatabaseTx getDatabase ( ) { } }

implementation: ODatabaseInternal < ? > databaseOwner = ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getDatabaseOwner ( ) ; if ( databaseOwner instanceof OObjectDatabaseTx ) { return ( OObjectDatabaseTx ) databaseOwner ; } else if ( databaseOwner instanceof ODatabaseDocumentInternal ) { return new OObjectDatabaseTx ( ( ODatabaseDocumentInternal ) databaseOwner ) ; } throw new IllegalStateException ( "Current database not of expected type" ) ;


signature:
public class OPropertyIndexDefinition { /** * { @ inheritDoc }
 * @ param indexName
 * @ param indexType */
public String toCreateIndexDDL ( final String indexName , final String indexType , final String engine ) { } }

implementation: return createIndexDDLWithFieldType ( indexName , indexType , engine ) . toString ( ) ;


signature:
public class OrientConfigurableGraph { /** * Builds a OrientGraph instance passing a configuration . Supported configuration settings are :
 * < table >
 * < tr >
 * < td > < b > Name < / b > < / td >
 * < td > < b > Description < / b > < / td >
 * < td > < b > Default value < / b > < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . url < / td >
 * < td > Database URL < / td >
 * < td > - < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . username < / td >
 * < td > User name < / td >
 * < td > admin < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . password < / td >
 * < td > User password < / td >
 * < td > admin < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . saveOriginalIds < / td >
 * < td > Saves the original element IDs by using the property origId . This could be useful on import of graph to preserve original
 * ids < / td >
 * < td > false < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . keepInMemoryReferences < / td >
 * < td > Avoid to keep records in memory but only RIDs < / td >
 * < td > false < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . useCustomClassesForEdges < / td >
 * < td > Use Edge ' s label as OrientDB class . If doesn ' t exist create it under the hood < / td >
 * < td > true < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . useCustomClassesForVertex < / td >
 * < td > Use Vertex ' s label as OrientDB class . If doesn ' t exist create it under the hood < / td >
 * < td > true < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . useVertexFieldsForEdgeLabels < / td >
 * < td > Store the edge relationships in vertex by using the Edge ' s class . This allow to use multiple fields and make faster
 * traversal by edge ' s label ( class ) < / td >
 * < td > true < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . lightweightEdges < / td >
 * < td > Uses lightweight edges . This avoid to create a physical document per edge . Documents are created only when they have
 * properties < / td >
 * < td > true < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . autoScaleEdgeType < / td >
 * < td > Set auto scale of edge type . True means one edge is managed as LINK , 2 or more are managed with a LINKBAG < / td >
 * < td > false < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . edgeContainerEmbedded2TreeThreshold < / td >
 * < td > Changes the minimum number of edges for edge containers to transform the underlying structure from embedded to tree . Use - 1
 * to disable transformation < / td >
 * < td > - 1 < / td >
 * < / tr >
 * < tr >
 * < td > blueprints . orientdb . edgeContainerTree2EmbeddedThreshold < / td >
 * < td > Changes the minimum number of edges for edge containers to transform the underlying structure from tree to embedded . Use - 1
 * to disable transformation < / td >
 * < td > - 1 < / td >
 * < / tr >
 * < / table >
 * @ param configuration of graph */
protected void init ( final Configuration configuration ) { } }

implementation: final Boolean saveOriginalIds = configuration . getBoolean ( "blueprints.orientdb.saveOriginalIds" , null ) ; if ( saveOriginalIds != null ) setSaveOriginalIds ( saveOriginalIds ) ; final Boolean keepInMemoryReferences = configuration . getBoolean ( "blueprints.orientdb.keepInMemoryReferences" , null ) ; if ( keepInMemoryReferences != null ) setKeepInMemoryReferences ( keepInMemoryReferences ) ; final Boolean useCustomClassesForEdges = configuration . getBoolean ( "blueprints.orientdb.useCustomClassesForEdges" , null ) ; if ( useCustomClassesForEdges != null ) setUseClassForEdgeLabel ( useCustomClassesForEdges ) ; final Boolean useCustomClassesForVertex = configuration . getBoolean ( "blueprints.orientdb.useCustomClassesForVertex" , null ) ; if ( useCustomClassesForVertex != null ) setUseClassForVertexLabel ( useCustomClassesForVertex ) ; final Boolean useVertexFieldsForEdgeLabels = configuration . getBoolean ( "blueprints.orientdb.useVertexFieldsForEdgeLabels" , null ) ; if ( useVertexFieldsForEdgeLabels != null ) setUseVertexFieldsForEdgeLabels ( useVertexFieldsForEdgeLabels ) ; final Boolean lightweightEdges = configuration . getBoolean ( "blueprints.orientdb.lightweightEdges" , null ) ; if ( lightweightEdges != null ) setUseLightweightEdges ( lightweightEdges ) ; final Boolean autoScaleEdgeType = configuration . getBoolean ( "blueprints.orientdb.autoScaleEdgeType" , null ) ; if ( autoScaleEdgeType != null ) setAutoScaleEdgeType ( autoScaleEdgeType ) ; final Boolean requireTransaction = configuration . getBoolean ( "blueprints.orientdb.requireTransaction" , null ) ; if ( requireTransaction != null ) setRequireTransaction ( requireTransaction ) ; final Boolean txRequiredForSQLGraphOperations = configuration . getBoolean ( "blueprints.orientdb.txRequiredForSQLGraphOperations" , null ) ; if ( txRequiredForSQLGraphOperations != null ) setTxRequiredForSQLGraphOperations ( txRequiredForSQLGraphOperations ) ; final Integer maxRetries = configuration . getInt ( "blueprints.orientdb.maxRetries" , 50 ) ; if ( maxRetries != null ) setMaxRetries ( maxRetries ) ;


signature:
public class OClientConnectionManager { /** * Create a connection .
 * @ param iProtocol protocol which will be used by connection
 * @ return new connection */
public OClientConnection connect ( final ONetworkProtocol iProtocol ) { } }

implementation: final OClientConnection connection ; connection = new OClientConnection ( connectionSerial . incrementAndGet ( ) , iProtocol ) ; connections . put ( connection . getId ( ) , connection ) ; OLogManager . instance ( ) . config ( this , "Remote client connected from: " + connection ) ; OServerPluginHelper . invokeHandlerCallbackOnClientConnection ( iProtocol . getServer ( ) , connection ) ; return connection ;


signature:
public class OClientConnectionManager { /** * Create a connection .
 * @ param iProtocol protocol which will be used by connection
 * @ return new connection */
public OClientConnection connect ( final ONetworkProtocol iProtocol , final OClientConnection connection , final byte [ ] tokenBytes , final OTokenHandler handler ) { } }

implementation: final OToken token ; try { token = handler . parseBinaryToken ( tokenBytes ) ; } catch ( Exception e ) { throw OException . wrapException ( new OTokenSecurityException ( "Error on token parsing" ) , e ) ; } OClientSessions session ; synchronized ( sessions ) { session = new OClientSessions ( tokenBytes , token ) ; sessions . put ( new OHashToken ( tokenBytes ) , session ) ; } connection . setTokenBytes ( tokenBytes ) ; connection . setTokenBased ( true ) ; connection . setToken ( token ) ; session . addConnection ( connection ) ; OLogManager . instance ( ) . config ( this , "Remote client connected from: " + connection ) ; OServerPluginHelper . invokeHandlerCallbackOnClientConnection ( iProtocol . getServer ( ) , connection ) ; return connection ;


signature:
public class OClientConnectionManager { /** * Retrieves the connection by id .
 * @ param iChannelId id of connection
 * @ return The connection if any , otherwise null */
public OClientConnection getConnection ( final int iChannelId , ONetworkProtocol protocol ) { } }

implementation:
// SEARCH THE CONNECTION BY ID
OClientConnection connection = connections . get ( iChannelId ) ; if ( connection != null ) connection . setProtocol ( protocol ) ; return connection ;


signature:
public class OClientConnectionManager { /** * Retrieves the connection by address / port .
 * @ param iAddress The address as string in the format address as format < ip > : < port >
 * @ return The connection if any , otherwise null */
public OClientConnection getConnection ( final String iAddress ) { } }

implementation: for ( OClientConnection conn : connections . values ( ) ) { if ( iAddress . equals ( conn . getRemoteAddress ( ) ) ) return conn ; } return null ;


signature:
public class OClientConnectionManager { /** * Disconnects and kill the associated network manager .
 * @ param connection connection to kill */
public void kill ( final OClientConnection connection ) { } }

implementation:
if ( connection != null ) { final ONetworkProtocol protocol = connection . getProtocol ( ) ; try { // INTERRUPT THE NEWTORK MANAGER TOO
protocol . interrupt ( ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Error during interruption of binary protocol" , e ) ; } disconnect ( connection ) ; // KILL THE NETWORK MANAGER TOO
protocol . sendShutdown ( ) ; }


signature:
public class OClientConnectionManager { /** * Interrupt the associated network manager .
 * @ param iChannelId id of connection */
public void interrupt ( final int iChannelId ) { } }

implementation:
final OClientConnection connection = connections . get ( iChannelId ) ; if ( connection != null ) { final ONetworkProtocol protocol = connection . getProtocol ( ) ; if ( protocol != null ) // INTERRUPT THE NEWTORK MANAGER
protocol . softShutdown ( ) ; }


signature:
public class OClientConnectionManager { /** * Disconnects a client connections
 * @ param iChannelId id of connection
 * @ return true if was last one , otherwise false */
public boolean disconnect ( final int iChannelId ) { } }

implementation:
OLogManager . instance ( ) . debug ( this , "Disconnecting connection with id=%d" , iChannelId ) ; final OClientConnection connection = connections . remove ( iChannelId ) ; if ( connection != null ) { OServerPluginHelper . invokeHandlerCallbackOnClientDisconnection ( server , connection ) ; connection . close ( ) ; removeConnectionFromSession ( connection ) ; // CHECK IF THERE ARE OTHER CONNECTIONS
for ( Entry < Integer , OClientConnection > entry : connections . entrySet ( ) ) { if ( entry . getValue ( ) . getProtocol ( ) . equals ( connection . getProtocol ( ) ) ) { OLogManager . instance ( ) . debug ( this , "Disconnected connection with id=%d but are present other active channels" , iChannelId ) ; return false ; } } OLogManager . instance ( ) . debug ( this , "Disconnected connection with id=%d, no other active channels found" , iChannelId ) ; return true ; } OLogManager . instance ( ) . debug ( this , "Cannot find connection with id=%d" , iChannelId ) ; return false ;


signature:
public class OClientConnectionManager { /** * Pushes the distributed configuration to all the connected clients . */
public void pushDistribCfg2Clients ( final ODocument iConfig ) { } }

implementation:
if ( iConfig == null ) return ; final Set < String > pushed = new HashSet < String > ( ) ; for ( OClientConnection c : connections . values ( ) ) { if ( ! c . getData ( ) . supportsLegacyPushMessages ) continue ; try { final String remoteAddress = c . getRemoteAddress ( ) ; if ( pushed . contains ( remoteAddress ) ) // ALREADY SENT : JUMP IT
continue ; } catch ( Exception e ) { // SOCKET EXCEPTION SKIP IT
continue ; } if ( ! ( c . getProtocol ( ) instanceof ONetworkProtocolBinary ) || c . getData ( ) . getSerializationImpl ( ) == null ) // INVOLVE ONLY BINARY PROTOCOLS
continue ; final ONetworkProtocolBinary p = ( ONetworkProtocolBinary ) c . getProtocol ( ) ; final OChannelBinary channel = p . getChannel ( ) ; final ORecordSerializer ser = ORecordSerializerFactory . instance ( ) . getFormat ( c . getData ( ) . getSerializationImpl ( ) ) ; if ( ser == null ) return ; final byte [ ] content = ser . toStream ( iConfig , false ) ; try { // TRY ACQUIRING THE LOCK FOR MAXIMUM 3 SECS TO AVOID TO FREEZE CURRENT THREAD
if ( channel . tryAcquireWriteLock ( TIMEOUT_PUSH ) ) { try { channel . writeByte ( OChannelBinaryProtocol . PUSH_DATA ) ; channel . writeInt ( Integer . MIN_VALUE ) ; channel . writeByte ( OChannelBinaryProtocol . REQUEST_PUSH_DISTRIB_CONFIG ) ; channel . writeBytes ( content ) ; channel . flush ( ) ; pushed . add ( c . getRemoteAddress ( ) ) ; OLogManager . instance ( ) . debug ( this , "Sent updated cluster configuration to the remote client %s" , c . getRemoteAddress ( ) ) ; } finally { channel . releaseWriteLock ( ) ; } } else { OLogManager . instance ( ) . info ( this , "Timeout on sending updated cluster configuration to the remote client %s" , c . getRemoteAddress ( ) ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . warn ( this , "Cannot push cluster configuration to the client %s" , e , c . getRemoteAddress ( ) ) ; } }


signature:
public class OEmbeddedRidBag { /** * for internal use only
 * @ param index
 * @ param newValue
 * @ return */
public boolean swap ( int index , OIdentifiable newValue ) { } }

implementation: EntriesIterator iter = ( EntriesIterator ) rawIterator ( ) ; int currIndex = 0 ; while ( iter . hasNext ( ) ) { iter . next ( ) ; if ( index == currIndex ) { iter . swapValueOnCurrent ( newValue ) ; return true ; } currIndex ++ ; } return false ;


signature:
public class OTransactionAbstract { /** * Closes the transaction and releases all the acquired locks . */
@ Override public void close ( ) { } }

implementation: for ( Map . Entry < ORID , LockedRecordMetadata > lock : locks . entrySet ( ) ) { try { final LockedRecordMetadata lockedRecordMetadata = lock . getValue ( ) ; if ( lockedRecordMetadata . strategy . equals ( OStorage . LOCKING_STRATEGY . EXCLUSIVE_LOCK ) ) { ( ( OAbstractPaginatedStorage ) getDatabase ( ) . getStorage ( ) . getUnderlying ( ) ) . releaseWriteLock ( lock . getKey ( ) ) ; } else if ( lockedRecordMetadata . strategy . equals ( OStorage . LOCKING_STRATEGY . SHARED_LOCK ) ) { ( ( OAbstractPaginatedStorage ) getDatabase ( ) . getStorage ( ) . getUnderlying ( ) ) . releaseReadLock ( lock . getKey ( ) ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . debug ( this , "Error on releasing lock against record " + lock . getKey ( ) , e ) ; } } locks . clear ( ) ;


signature:
public class UpdateEdgePointersStep { /** * handles vertex consistency after an UPDATE EDGE
 * @ param record the edge record */
private void handleUpdateEdge ( ODocument record ) { } }

implementation:
Object currentOut = record . field ( "out" ) ; Object currentIn = record . field ( "in" ) ; Object prevOut = record . getOriginalValue ( "out" ) ; Object prevIn = record . getOriginalValue ( "in" ) ; // to manage subqueries
if ( currentOut instanceof Collection && ( ( Collection ) currentOut ) . size ( ) == 1 ) { currentOut = ( ( Collection ) currentOut ) . iterator ( ) . next ( ) ; record . setProperty ( "out" , currentOut ) ; } if ( currentIn instanceof Collection && ( ( Collection ) currentIn ) . size ( ) == 1 ) { currentIn = ( ( Collection ) currentIn ) . iterator ( ) . next ( ) ; record . setProperty ( "in" , currentIn ) ; } validateOutInForEdge ( record , currentOut , currentIn ) ; changeVertexEdgePointer ( record , ( OIdentifiable ) prevIn , ( OIdentifiable ) currentIn , "in" ) ; changeVertexEdgePointer ( record , ( OIdentifiable ) prevOut , ( OIdentifiable ) currentOut , "out" ) ;


signature:
public class UpdateEdgePointersStep { /** * updates old and new vertices connected to an edge after out / in update on the edge itself
 * @ param edge the edge
 * @ param prevVertex the previously connected vertex
 * @ param currentVertex the currently connected vertex
 * @ param direction the direction ( " out " or " in " ) */
private void changeVertexEdgePointer ( ODocument edge , OIdentifiable prevVertex , OIdentifiable currentVertex , String direction ) { } }

implementation: if ( prevVertex != null && ! prevVertex . equals ( currentVertex ) ) { String edgeClassName = edge . getClassName ( ) ; if ( edgeClassName . equalsIgnoreCase ( "E" ) ) { edgeClassName = "" ; } String vertexFieldName = direction + "_" + edgeClassName ; ODocument prevOutDoc = ( ( OIdentifiable ) prevVertex ) . getRecord ( ) ; ORidBag prevBag = prevOutDoc . field ( vertexFieldName ) ; if ( prevBag != null ) { prevBag . remove ( edge ) ; prevOutDoc . save ( ) ; } ODocument currentVertexDoc = ( ( OIdentifiable ) currentVertex ) . getRecord ( ) ; ORidBag currentBag = currentVertexDoc . field ( vertexFieldName ) ; if ( currentBag == null ) { currentBag = new ORidBag ( ) ; currentVertexDoc . field ( vertexFieldName , currentBag ) ; } currentBag . add ( edge ) ; }


signature:
public class UpdateEdgePointersStep { /** * checks if an object is an OIdentifiable and an instance of a particular ( schema ) class
 * @ param iRecord The record object
 * @ param orientClass The schema class
 * @ return */
private boolean isRecordInstanceOf ( Object iRecord , String orientClass ) { } }

implementation: if ( iRecord == null ) { return false ; } if ( ! ( iRecord instanceof OIdentifiable ) ) { return false ; } ODocument record = ( ( OIdentifiable ) iRecord ) . getRecord ( ) ; if ( iRecord == null ) { return false ; } return ( record . getSchemaClass ( ) . isSubClassOf ( orientClass ) ) ;


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

implementation: buffer . putChar ( object ) ;


signature:
public class OSchemaProxyObject { /** * 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 generateSchema ( final String iPackageName , final ClassLoader iClassLoader ) { } }

implementation: OLogManager . instance ( ) . debug ( this , "Generating schema inside package: %s" , iPackageName ) ; List < Class < ? > > classes = null ; try { classes = OReflectionHelper . getClassesFor ( iPackageName , iClassLoader ) ; } catch ( ClassNotFoundException e ) { throw OException . wrapException ( new ODatabaseException ( "Classes cannot be loaded during schema generation" ) , e ) ; } for ( Class < ? > c : classes ) { generateSchema ( c ) ; }