Input: Average amount of pages which were read from cache for component with given name during single data operation . If null value is passed or data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesPerOperation ( String componentName ) { switchLock . acquireReadLock ( ) ; try { if ( enabled ) { final PerformanceCountersHolder componentCountersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; fetchComponentCounters ( componentName , componentCountersHolder ) ; return componentCountersHolder . getAmountOfPagesPerOperation ( ) ; } else { final ImmutableStatistic post = postMeasurementStatistic ; if ( post == null ) return - 1 ; final PerformanceCountersHolder holder = post . countersByComponents . get ( componentName ) ; if ( holder == null ) return - 1 ; return holder . getAmountOfPagesPerOperation ( ) ; } } finally { switchLock . releaseReadLock ( ) ; } }


Input: Percent of cache hits for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public int getCacheHits ( String componentName ) { switchLock . acquireReadLock ( ) ; try { if ( enabled ) { final PerformanceCountersHolder countersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; fetchComponentCounters ( componentName , countersHolder ) ; return countersHolder . getCacheHits ( ) ; } else { final ImmutableStatistic post = postMeasurementStatistic ; if ( post == null ) return - 1 ; final PerformanceCountersHolder holder = post . countersByComponents . get ( componentName ) ; if ( holder != null ) return holder . getCacheHits ( ) ; return - 1 ; } } finally { switchLock . releaseReadLock ( ) ; } }


Input: Iterates over all live threads and accumulates write performance statics gathered form threads also accumulates statistic from dead threads which were alive when when gathering of performance measurements is started . [CODESPLIT] private WritCacheCountersHolder fetchWriteCacheCounters ( ) { //go through all threads and accumulate statistic only for live threads //all dead threads will be removed and statistics from them will be //later accumulated in #deadThreadsStatistic field, then result statistic from this field //will be aggregated to countersHolder //To decrease inter thread communication delay we fetch snapshots first //and only after that we aggregate data from immutable snapshots final Collection < ORawPair < Thread , PerformanceSnapshot > > snapshots = new ArrayList <> ( statistics . size ( ) ) ; final Collection < Thread > threadsToRemove = new ArrayList <> ( ) ; for ( Map . Entry < Thread , OSessionStoragePerformanceStatistic > entry : statistics . entrySet ( ) ) { final Thread thread = entry . getKey ( ) ; final OSessionStoragePerformanceStatistic statistic = entry . getValue ( ) ; snapshots . add ( new ORawPair <> ( thread , statistic . getSnapshot ( ) ) ) ; } WritCacheCountersHolder holder = null ; for ( ORawPair < Thread , PerformanceSnapshot > pair : snapshots ) { final Thread thread = pair . getFirst ( ) ; if ( thread . isAlive ( ) ) { final PerformanceSnapshot snapshot = pair . getSecond ( ) ; if ( snapshot . writCacheCountersHolder != null ) { if ( holder == null ) holder = new WritCacheCountersHolder ( ) ; snapshot . writCacheCountersHolder . pushData ( holder ) ; } } else { threadsToRemove . add ( thread ) ; } } if ( ! threadsToRemove . isEmpty ( ) ) { updateDeadThreadsStatistic ( threadsToRemove ) ; } final ImmutableStatistic ds = deadThreadsStatistic ; if ( ds != null ) { final WritCacheCountersHolder wch = ds . writCacheCountersHolder ; if ( wch != null ) { if ( holder == null ) holder = new WritCacheCountersHolder ( ) ; wch . pushData ( holder ) ; } } return holder ; }


Input: Iterates over all live threads and accumulates performance statics gathered form threads on system level also accumulates statistic from dead threads which were alive when when gathering of performance measurements is started . [CODESPLIT] private void fetchSystemCounters ( PerformanceCountersHolder countersHolder ) { //go through all threads and accumulate statistic only for live threads //all dead threads will be removed and statistics from them will be //later accumulated in #deadThreadsStatistic field, then result statistic from this field //will be aggregated to countersHolder //To decrease inter thread communication delay we fetch snapshots first //and only after that we aggregate data from immutable snapshots final Collection < ORawPair < Thread , PerformanceSnapshot > > snapshots = new ArrayList <> ( statistics . size ( ) ) ; final Collection < Thread > threadsToRemove = new ArrayList <> ( ) ; for ( Map . Entry < Thread , OSessionStoragePerformanceStatistic > entry : statistics . entrySet ( ) ) { final Thread thread = entry . getKey ( ) ; final OSessionStoragePerformanceStatistic statistic = entry . getValue ( ) ; snapshots . add ( new ORawPair <> ( thread , statistic . getSnapshot ( ) ) ) ; } for ( ORawPair < Thread , PerformanceSnapshot > pair : snapshots ) { final Thread thread = pair . getFirst ( ) ; if ( thread . isAlive ( ) ) { final PerformanceSnapshot snapshot = pair . getSecond ( ) ; snapshot . performanceCountersHolder . pushData ( countersHolder ) ; } else { threadsToRemove . add ( thread ) ; } } if ( ! threadsToRemove . isEmpty ( ) ) { updateDeadThreadsStatistic ( threadsToRemove ) ; } final ImmutableStatistic ds = deadThreadsStatistic ; if ( ds != null ) { final PerformanceCountersHolder dch = ds . countersHolder ; dch . pushData ( countersHolder ) ; } }


Input: Iterates over all live threads and accumulates performance statics gathered form threads for provided component also accumulates statistic from dead threads which were alive when when gathering of performance measurements is started . [CODESPLIT] private void fetchComponentCounters ( String componentName , PerformanceCountersHolder componentCountersHolder ) { //go through all threads and accumulate statistic only for live threads //all dead threads will be removed and statistics from them will be //later accumulated in #deadThreadsStatistic field, then result statistic from this field //will be aggregated to componentCountersHolder //To decrease inter thread communication delay we fetch snapshots first //and only after that we aggregate data from immutable snapshots final Collection < ORawPair < Thread , PerformanceSnapshot > > snapshots = new ArrayList <> ( statistics . size ( ) ) ; final List < Thread > threadsToRemove = new ArrayList <> ( ) ; for ( Map . Entry < Thread , OSessionStoragePerformanceStatistic > entry : statistics . entrySet ( ) ) { final Thread thread = entry . getKey ( ) ; final OSessionStoragePerformanceStatistic statistic = entry . getValue ( ) ; snapshots . add ( new ORawPair <> ( thread , statistic . getSnapshot ( ) ) ) ; } for ( ORawPair < Thread , PerformanceSnapshot > pair : snapshots ) { final Thread thread = pair . getFirst ( ) ; if ( thread . isAlive ( ) ) { final PerformanceSnapshot snapshot = pair . getSecond ( ) ; final PerformanceCountersHolder holder = snapshot . countersByComponent . get ( componentName ) ; if ( holder != null ) holder . pushData ( componentCountersHolder ) ; } else { threadsToRemove . add ( thread ) ; } } if ( ! threadsToRemove . isEmpty ( ) ) { updateDeadThreadsStatistic ( threadsToRemove ) ; } final ImmutableStatistic ds = deadThreadsStatistic ; if ( ds != null ) { final PerformanceCountersHolder dch = ds . countersByComponents . get ( componentName ) ; if ( dch != null ) { dch . pushData ( componentCountersHolder ) ; } } }


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


Input: Obtains the value stored under the given entry index in this bucket . [CODESPLIT] public ORID getValue ( final int entryIndex ) { assert isLeaf ; int entryPosition = getIntValue ( entryIndex * OIntegerSerializer . INT_SIZE + POSITIONS_ARRAY_OFFSET ) ; // skip key if ( encryption == null ) { entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedSize = getIntValue ( entryPosition ) ; entryPosition += OIntegerSerializer . INT_SIZE + encryptedSize ; } final int clusterId = getShortValue ( entryPosition ) ; final long clusterPosition = getLongValue ( entryPosition + OShortSerializer . SHORT_SIZE ) ; return new ORecordId ( clusterId , clusterPosition ) ; }


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


Input: Returns the property value configured if any . [CODESPLIT] public String getProperty ( final String iName , final String iDefaultValue ) { if ( properties == null ) return null ; for ( OServerEntryConfiguration p : properties ) { if ( p . name . equals ( iName ) ) return p . value ; } return null ; }


Input: Create a new POJO by its class name . Assure to have called the registerEntityClasses () declaring the packages that are part of entity classes . [CODESPLIT] public < RET extends Object > RET newInstance ( final String iClassName , final Object iEnclosingClass , Object ... iArgs ) { underlying . checkIfActive ( ) ; checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_CREATE , iClassName ) ; try { Class < ? > entityClass = entityManager . getEntityClass ( iClassName ) ; if ( entityClass != null ) { RET enhanced = ( RET ) OObjectEntityEnhancer . getInstance ( ) . getProxiedInstance ( entityManager . getEntityClass ( iClassName ) , iEnclosingClass , underlying . newInstance ( iClassName ) , null , iArgs ) ; return ( RET ) enhanced ; } else { throw new OSerializationException ( "Type " + iClassName + " cannot be serialized because is not part of registered entities. To fix this error register this class" ) ; } } catch ( Exception e ) { final String message = "Error on creating object of class " + iClassName ; OLogManager . instance ( ) . error ( this , message , e ) ; throw OException . wrapException ( new ODatabaseException ( message ) , e ) ; } }


Input: Method that detaches all fields contained in the document to the given object . [CODESPLIT] public < RET > RET detach ( final Object iPojo , boolean returnNonProxiedInstance ) { return ( RET ) OObjectEntitySerializer . detach ( iPojo , this , returnNonProxiedInstance ) ; }


Input: Method that detaches all fields contained in the document to the given object and recursively all object tree . This may throw a { @link StackOverflowError } with big objects tree . To avoid it set the stack size with - Xss java option [CODESPLIT] public < RET > RET detachAll ( final Object iPojo , boolean returnNonProxiedInstance ) { return detachAll ( iPojo , returnNonProxiedInstance , new HashMap < Object , Object > ( ) , new HashMap < Object , Object > ( ) ) ; }


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


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


Input:
Saves an object to the database forcing a record cluster where to store it . First checks if the object is new or not . In case it s new a new ODocument is created and bound to the object otherwise the ODocument is retrieved and updated . The object is introspected using the Java Reflection to extract the field values . <br > If a multi value ( array collection or map of objects ) is passed then each single object is stored separately . <p > Before to use the specified cluster a check is made to know if is allowed and figures in the configured and the record is valid following the constraints declared in the schema . [CODESPLIT] public < RET > RET save ( final Object iPojo , final String iClusterName , OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { checkOpenness ( ) ; if ( iPojo == null ) return ( RET ) iPojo ; else if ( OMultiValue . isMultiValue ( iPojo ) ) { // MULTI VALUE OBJECT: STORE SINGLE POJOS
 for ( Object pojo : OMultiValue . getMultiValueIterable ( iPojo ) ) { save ( pojo , iClusterName ) ; } return ( RET ) iPojo ; } else { OSerializationThreadLocal . INSTANCE . get ( ) . clear ( ) ; // GET THE ASSOCIATED DOCUMENT
 final Object proxiedObject = OObjectEntitySerializer . serializeObject ( iPojo , this ) ; final ODocument record = getRecordByUserObject ( proxiedObject , true ) ; try { record . setInternalStatus ( ORecordElement . STATUS . MARSHALLING ) ; if ( ! saveOnlyDirty || record . isDirty ( ) ) { // REGISTER BEFORE TO SERIALIZE TO AVOID PROBLEMS WITH CIRCULAR DEPENDENCY
 // registerUserObject(iPojo, record);
 deleteOrphans ( ( ( ( OObjectProxyMethodHandler ) ( ( ProxyObject ) proxiedObject ) . getHandler ( ) ) ) ) ; ODocument savedRecord = underlying . save ( record , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; ( ( OObjectProxyMethodHandler ) ( ( ProxyObject ) proxiedObject ) . getHandler ( ) ) . setDoc ( savedRecord ) ; ( ( OObjectProxyMethodHandler ) ( ( ProxyObject ) proxiedObject ) . getHandler ( ) ) . updateLoadedFieldMap ( proxiedObject , false ) ; // RE-REGISTER FOR NEW RECORDS SINCE THE ID HAS CHANGED
 registerUserObject ( proxiedObject , record ) ; } } finally { record . setInternalStatus ( ORecordElement . STATUS . LOADED ) ; } return ( RET ) proxiedObject ; } }


Input: Returns the version number of the object . Version starts from 0 assigned on creation . [CODESPLIT] public int getVersion ( final Object iPojo ) { checkOpenness ( ) ; final ODocument record = getRecordByUserObject ( iPojo , false ) ; if ( record != null ) return record . getVersion ( ) ; return OObjectSerializerHelper . getObjectVersion ( iPojo ) ; }


Input: Register the static document binary mapping mode in the database context ( only if it s not already set ) [CODESPLIT] private void registerFieldMappingStrategy ( ) { if ( ! this . getConfiguration ( ) . getContextKeys ( ) . contains ( OGlobalConfiguration . DOCUMENT_BINARY_MAPPING . getKey ( ) ) ) { this . getConfiguration ( ) . setValue ( OGlobalConfiguration . DOCUMENT_BINARY_MAPPING , OGlobalConfiguration . DOCUMENT_BINARY_MAPPING . getValueAsInteger ( ) ) ; } }


Input: Returns a wrapped OCommandRequest instance to catch the result - set by converting it before to return to the user application . [CODESPLIT] public < RET extends OCommandRequest > RET command ( final OCommandRequest iCommand ) { return ( RET ) new OCommandSQLPojoWrapper ( this , underlying . command ( iCommand ) ) ; }


Input:
Converts an array of parameters : if a POJO is used then replace it with its record id . [CODESPLIT] protected void convertParameters ( final Object ... iArgs ) { if ( iArgs == null ) return ; // FILTER PARAMETERS
 for ( int i = 0 ; i < iArgs . length ; ++ i ) iArgs [ i ] = convertParameter ( iArgs [ i ] ) ; }


Input: Sets as dirty a POJO . This is useful when you change the object and need to tell to the engine to treat as dirty . [CODESPLIT] public void setDirty ( final Object iPojo ) { if ( iPojo == null ) return ; final ODocument record = getRecordByUserObject ( iPojo , false ) ; if ( record == null ) throw new OObjectNotManagedException ( "The object " + iPojo + " is not managed by current database" ) ; record . setDirty ( ) ; }


Input: Sets as not dirty a POJO . This is useful when you change some other object and need to tell to the engine to treat this one as not dirty . [CODESPLIT] public void unsetDirty ( final Object iPojo ) { if ( iPojo == null ) return ; final ODocument record = getRecordByUserObject ( iPojo , false ) ; if ( record == null ) return ; ORecordInternal . unsetDirty ( record ) ; }


Input:
Convert a parameter : if a POJO is used then replace it with its record id . [CODESPLIT] protected Object convertParameter ( final Object iParameter ) { if ( iParameter != null ) // FILTER PARAMETERS
 if ( iParameter instanceof Map < ? , ? > ) { Map < String , Object > map = ( Map < String , Object > ) iParameter ; for ( Map . Entry < String , Object > e : map . entrySet ( ) ) { map . put ( e . getKey ( ) , convertParameter ( e . getValue ( ) ) ) ; } return map ; } else if ( iParameter instanceof Collection < ? > ) { List < Object > result = new ArrayList < Object > ( ) ; for ( Object object : ( Collection < Object > ) iParameter ) { result . add ( convertParameter ( object ) ) ; } return result ; } else if ( iParameter . getClass ( ) . isEnum ( ) ) { return ( ( Enum < ? > ) iParameter ) . name ( ) ; } else if ( ! OType . isSimpleType ( iParameter ) ) { final ORID rid = getIdentity ( iParameter ) ; if ( rid != null && rid . isValid ( ) ) // REPLACE OBJECT INSTANCE WITH ITS RECORD ID
 return rid ; } return iParameter ; }


Input: Iterates on all factories and append all index types . [CODESPLIT] private static Set < String > getIndexTypes ( ) { final Set < String > types = new HashSet <> ( ) ; final Iterator < OIndexFactory > ite = getAllFactories ( ) ; while ( ite . hasNext ( ) ) { types . addAll ( ite . next ( ) . getTypes ( ) ) ; } return types ; }


Input: Iterates on all factories and append all index engines . [CODESPLIT] public static Set < String > getIndexEngines ( ) { final Set < String > engines = new HashSet <> ( ) ; final Iterator < OIndexFactory > ite = getAllFactories ( ) ; while ( ite . hasNext ( ) ) { engines . addAll ( ite . next ( ) . getAlgorithms ( ) ) ; } return engines ; }


Input: @param storage TODO @param indexType index type [CODESPLIT] public static OIndexInternal < ? > createIndex ( OStorage storage , String name , String indexType , String algorithm , String valueContainerAlgorithm , ODocument metadata , int version ) throws OConfigurationException , OIndexException { if ( indexType . equalsIgnoreCase ( OClass . INDEX_TYPE . UNIQUE_HASH_INDEX . name ( ) ) || indexType . equalsIgnoreCase ( OClass . INDEX_TYPE . NOTUNIQUE_HASH_INDEX . name ( ) ) || indexType . equalsIgnoreCase ( OClass . INDEX_TYPE . DICTIONARY_HASH_INDEX . name ( ) ) ) { if ( ! algorithm . equalsIgnoreCase ( "autosharding" ) ) { algorithm = OHashIndexFactory . HASH_INDEX_ALGORITHM ; } } return findFactoryByAlgorithmAndType ( algorithm , indexType ) . createIndex ( name , storage , indexType , algorithm , valueContainerAlgorithm , metadata , version ) ; }


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


Input: @param localNodeName @param localResult [CODESPLIT] public boolean setLocalResult ( final String localNodeName , final Object localResult ) { localResponse = new ODistributedResponse ( this , request . getId ( ) , localNodeName , localNodeName , localResult ) ; receivedCurrentNode = true ; return collectResponse ( localResponse ) ; }


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


Input: Returns the list of node names that didn t provide a response . [CODESPLIT] public List < String > getMissingNodes ( ) { synchronousResponsesLock . lock ( ) ; try { final List < String > missingNodes = new ArrayList < String > ( ) ; for ( Map . Entry < String , Object > entry : responses . entrySet ( ) ) if ( entry . getValue ( ) == NO_RESPONSE ) missingNodes . add ( entry . getKey ( ) ) ; return missingNodes ; } finally { synchronousResponsesLock . unlock ( ) ; } }


Input: Returns all the responses in conflict . [CODESPLIT] protected List < ODistributedResponse > getConflictResponses ( ) { final List < ODistributedResponse > servers = new ArrayList < ODistributedResponse > ( ) ; int bestGroupSoFar = getBestResponsesGroup ( ) ; for ( int i = 0 ; i < responseGroups . size ( ) ; ++ i ) { if ( i != bestGroupSoFar ) { for ( ODistributedResponse r : responseGroups . get ( i ) ) servers . ( r ) ; } } return servers ; }


Input: Returns the biggest response group . [CODESPLIT] protected int getBestResponsesGroup ( ) { int maxCoherentResponses = 0 ; int bestGroupSoFar = 0 ; for ( int i = 0 ; i < responseGroups . size ( ) ; ++ i ) { final int currentGroupSize = responseGroups . get ( i ) . size ( ) ; if ( currentGroupSize > maxCoherentResponses ) { maxCoherentResponses = currentGroupSize ; bestGroupSoFar = i ; } } return bestGroupSoFar ; }


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


Input: Returns the received response objects . [CODESPLIT] protected List < ODistributedResponse > getReceivedResponses ( ) { final List < ODistributedResponse > parsed = new ArrayList < ODistributedResponse > ( ) ; for ( Object r : responses . values ( ) ) if ( r != NO_RESPONSE ) parsed . add ( ( ODistributedResponse ) r ) ; return parsed ; }


Input: returns an already prepared SQL execution plan taking it from the cache if it exists or creating a new one if it doesn t [CODESPLIT] public static OExecutionPlan get ( String statement , OCommandContext ctx , ODatabaseDocumentInternal db ) { if ( db == null ) { throw new IllegalArgumentException ( "DB cannot be null" ) ; } if ( statement == null ) { return null ; } OExecutionPlanCache resource = db . getSharedContext ( ) . getExecutionPlanCache ( ) ; OExecutionPlan result = resource . getInternal ( statement , ctx , db ) ; return result ; }


Input: @param statement an SQL statement @param ctx [CODESPLIT] public OExecutionPlan getInternal ( String statement , OCommandContext ctx , ODatabaseDocumentInternal db ) { OInternalExecutionPlan result ; if ( statement == null ) { return null ; } synchronized ( map ) { //LRU result = map . remove ( statement ) ; if ( result != null ) { map . put ( statement , result ) ; result = result . copy ( ctx ) ; } } return result ; }


Input: if the condition involved the current pattern ( MATCH statement eg . $matched . something = foo ) returns the name of involved pattern aliases ( something in this case ) [CODESPLIT] List < String > getMatchPatternInvolvedAliases ( ) { if ( mathExpression != null ) return mathExpression . getMatchPatternInvolvedAliases ( ) ; if ( arrayConcatExpression != null ) return arrayConcatExpression . getMatchPatternInvolvedAliases ( ) ; return null ; }


Input: tests if current expression involves an indexed function AND that function can be used on this target [CODESPLIT] public boolean allowsIndexedFunctionExecutionOnTarget ( OFromClause target , OCommandContext context ) { return left . allowsIndexedFunctionExecutionOnTarget ( target , context , operator , right . execute ( ( OResult ) null , context ) ) ; }


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


Input:
Acquires a database engine from the pool . Once finished using it the instance MUST be returned in the pool by calling the method #releaseDatabaseEngine ( String ScriptEngine ) . [CODESPLIT] public OPartitionedObjectPool . PoolEntry < ScriptEngine > acquireDatabaseEngine ( final String databaseName , final String language ) { ODatabaseScriptManager dbManager = dbManagers . get ( databaseName ) ; if ( dbManager == null ) { // CREATE A NEW DATABASE SCRIPT MANAGER
 dbManager = new ODatabaseScriptManager ( this , databaseName ) ; final ODatabaseScriptManager prev = dbManagers . putIfAbsent ( databaseName , dbManager ) ; if ( prev != null ) { dbManager . close ( ) ; // GET PREVIOUS ONE
 dbManager = prev ; } } return dbManager . acquireEngine ( language ) ; }


Input:
Acquires a database engine from the pool . Once finished using it the instance MUST be returned in the pool by calling the method [CODESPLIT] public void releaseDatabaseEngine ( final String iLanguage , final String iDatabaseName , final OPartitionedObjectPool . PoolEntry < ScriptEngine > poolEntry ) { final ODatabaseScriptManager dbManager = dbManagers . get ( iDatabaseName ) ; // We check if there is still a valid pool because it could be removed by the function reload
 if ( dbManager != null ) { dbManager . releaseEngine ( iLanguage , poolEntry ) ; } }


Input:
Unbinds variables [CODESPLIT] public void unbind ( ScriptEngine scriptEngine , final Bindings binding , final OCommandContext iContext , final Map < Object , Object > iArgs ) { for ( OScriptInjection i : injections ) i . unbind ( scriptEngine , binding ) ; binding . put ( "db" , null ) ; binding . put ( "orient" , null ) ; binding . put ( "util" , null ) ; binding . put ( "ctx" , null ) ; if ( iContext != null ) { for ( Entry < String , Object > a : iContext . getVariables ( ) . entrySet ( ) ) binding . put ( a . getKey ( ) , null ) ; } if ( iArgs != null ) { for ( Entry < Object , Object > a : iArgs . entrySet ( ) ) binding . put ( a . getKey ( ) . toString ( ) , null ) ; } binding . put ( "params" , null ) ; } public void registerInjection ( final OScriptInjection iInj ) { if ( ! injections . contains ( iInj ) ) injections . add ( iInj ) ; } public void unregisterInjection  ( final OScriptInjection iInj ) { injections . remove ( iInj ) ; } public List < OScriptInjection > getInjections  ( ) { return injections ; } public OScriptManager registerEngine  ( final String iLanguage , final ScriptEngineFactory iEngine ) { engines . put ( iLanguage , iEngine ) ; return this ; } public OScriptManager registerFormatter  ( final String iLanguage , final OScriptFormatter iFormatterImpl ) { formatters . put ( iLanguage . toLowerCase ( Locale . ENGLISH ) , iFormatterImpl ) ; return this ; } public OScriptManager registerResultHandler  ( final String iLanguage , final OScriptResultHandler resultHandler ) { handlers . put ( iLanguage . toLowerCase ( Locale . ENGLISH ) , resultHandler ) ; return this ; } public Object handleResult  ( String language , Object result , ScriptEngine engine , Bindings binding , ODatabaseDocument database ) { OScriptResultHandler handler = handlers . get ( language ) ; if ( handler != null ) { return handler . handle ( result , engine , binding , database ) ; } else { return result ; } } /**
   * Ask to the Script engine all the formatters
   *
   * @return Map containing all the formatters
   */ public Map < String , OScriptFormatter > getFormatters  ( ) { return formatters ; } /**
   * Closes the pool for a database. This is called at Orient shutdown and in case a function has been updated.
   *
   * @param iDatabaseName
   */ public void close  ( final String iDatabaseName ) { final ODatabaseScriptManager dbPool = dbManagers . remove ( iDatabaseName ) ; if ( dbPool != null ) dbPool . close ( ) ; } }


Input: Returns the next position available . [CODESPLIT] long getNextPosition ( final OAtomicOperation atomicOperation ) throws IOException { final long filledUpTo = getFilledUpTo ( atomicOperation , fileId ) ; final long pageIndex = filledUpTo - 1 ; final OCacheEntry cacheEntry = loadPageForRead ( atomicOperation , fileId , pageIndex , false , 1 ) ; try { final OClusterPositionMapBucket bucket = new OClusterPositionMapBucket ( cacheEntry , false ) ; final int bucketSize = bucket . getSize ( ) ; return pageIndex * OClusterPositionMapBucket . MAX_ENTRIES + bucketSize ; } finally { releasePageFromRead ( atomicOperation , cacheEntry ) ; } }


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


Input: Removes entry with given key from { @link #newEntries } . [CODESPLIT] private boolean removeFromNewEntries ( final OIdentifiable identifiable ) { OModifiableInteger counter = newEntries . get ( identifiable ) ; if ( counter == null ) { return false ; } else { if ( counter . getValue ( ) == 1 ) { newEntries . remove ( identifiable ) ; } else { counter . decrement ( ) ; } return true ; } }


Input: it s not key = [ ... ] but a real condition on field names already ordered ( field names will be ignored ) [CODESPLIT] private void processAndBlock ( ) { OCollection fromKey = indexKeyFrom ( ( OAndBlock ) condition , additionalRangeCondition ) ; OCollection toKey = indexKeyTo ( ( OAndBlock ) condition , additionalRangeCondition ) ; boolean fromKeyIncluded = indexKeyFromIncluded ( ( OAndBlock ) condition , additionalRangeCondition ) ; boolean toKeyIncluded = indexKeyToIncluded ( ( OAndBlock ) condition , additionalRangeCondition ) ; init ( fromKey , fromKeyIncluded , toKey , toKeyIncluded ) ; }


Input: this is for subqueries when a OResult is found <ul > <li > if it s a projection with a single column the value is returned< / li > <li > if it s a document the RID is returned< / li > < / ul > [CODESPLIT] private Object unboxOResult ( Object value ) { if ( value instanceof List ) { return ( ( List ) value ) . stream ( ) . map ( x -> unboxOResult ( x ) ) . collect ( Collectors . toList ( ) ) ; } if ( value instanceof OResult ) { if ( ( ( OResult ) value ) . isElement ( ) ) { return ( ( OResult ) value ) . getIdentity ( ) . orElse ( null ) ; } Set < String > props = ( ( OResult ) value ) . getPropertyNames ( ) ; if ( props . size ( ) == 1 ) { return ( ( OResult ) value ) . getProperty ( props . iterator ( ) . next ( ) ) ; } } return value ; }


Input: Obtains the value stored under the given index in this bucket . [CODESPLIT] public V getValue ( int index ) { int entryPosition = getIntValue ( POSITIONS_ARRAY_OFFSET + index * OIntegerSerializer . INT_SIZE ) ; // skip hash code entryPosition += OLongSerializer . LONG_SIZE ; if ( encryption == null ) { // skip key entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedLength = getIntValue ( entryPosition ) ; entryPosition += encryptedLength + OIntegerSerializer . INT_SIZE ; } return deserializeFromDirectMemory ( valueSerializer , entryPosition ) ; }


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


Input: Finds a character inside a string specyfing the limits and direction . If iFrom is minor than iTo then it moves forward otherwise backward . [CODESPLIT] public static int indexOfOutsideStrings ( final String iText , final char iToFind , int iFrom , int iTo ) { if ( iTo == - 1 ) iTo = iText . length ( ) - 1 ; if ( iFrom == - 1 ) iFrom = iText . length ( ) - 1 ; char c ; char stringChar = ' ' ; boolean escape = false ; final StringBuilder buffer = new StringBuilder ( 1024 ) ; int i = iFrom ; while ( true ) { c = iText . charAt ( i ) ; if ( ! escape && c == ' ' && ( ( i + 1 ) < iText . length ( ) ) ) { if ( iText . charAt ( i + 1 ) == ' ' ) { i = readUnicode ( iText , i + 2 , buffer ) ; } else escape = true ; } else { if ( c == ' ' || c == ' ' ) { // BEGIN/END STRING if ( stringChar == ' ' ) { // BEGIN stringChar = c ; } else { // END if ( ! escape && c == stringChar ) stringChar = ' ' ; } } if ( c == iToFind && stringChar == ' ' ) return i ; if ( escape ) escape = false ; } if ( iFrom < iTo ) { // MOVE FORWARD if ( ++ i > iTo ) break ; } else { // MOVE BACKWARD if ( -- i < iFrom ) break ; } } return - 1 ; }


Input: Jump white spaces . [CODESPLIT] public static int jumpWhiteSpaces ( final CharSequence iText , final int iCurrentPosition , final int iMaxPosition ) { return jump ( iText , iCurrentPosition , iMaxPosition , COMMON_JUMP ) ; }


Input: Jump some characters reading from an offset of a String . [CODESPLIT] public static int jump ( final CharSequence iText , int iCurrentPosition , final int iMaxPosition , final String iJumpChars ) { if ( iCurrentPosition < 0 ) return - 1 ; final int size = iMaxPosition > - 1 ? Math . min ( iMaxPosition , iText . length ( ) ) : iText . length ( ) ; final int jumpCharSize = iJumpChars . length ( ) ; boolean found = true ; char c ; for ( ; iCurrentPosition < size ; ++ iCurrentPosition ) { found = false ; c = iText . charAt ( iCurrentPosition ) ; for ( int jumpIndex = 0 ; jumpIndex < jumpCharSize ; ++ jumpIndex ) { if ( iJumpChars . charAt ( jumpIndex ) == c ) { found = true ; break ; } } if ( ! found ) break ; } return iCurrentPosition >= size ? - 1 : iCurrentPosition ; }


Input: Like String . startsWith () but ignoring case [CODESPLIT] public static boolean startsWithIgnoreCase ( final String iText , final String iToFind ) { if ( iText . length ( ) < iToFind . length ( ) ) return false ; return iText . substring ( 0 , iToFind . length ( ) ) . equalsIgnoreCase ( iToFind ) ; }


Input: Sets the fetch plan to use . [CODESPLIT] public OQueryAbstract setFetchPlan ( final String fetchPlan ) { OFetchHelper . checkFetchPlanValid ( fetchPlan ) ; if ( fetchPlan != null && fetchPlan . length ( ) == 0 ) this . fetchPlan = null ; else this . fetchPlan = fetchPlan ; return this ; }


Input: Adds the record to repair int the map of records and cluster . The decision about repairing is taken by the timer task . [CODESPLIT] @ Override public void enqueueRepairRecord ( final ORecordId rid ) { if ( ! active ) return ; if ( rid == null || ! rid . isPersistent ( ) ) return ; if ( rid . getClusterPosition ( ) < - 1 ) // SKIP TRANSACTIONAL RIDS return ; recordProcessed . incrementAndGet ( ) ; // ADD RECORD TO REPAIR records . put ( rid , Boolean . TRUE ) ; }


Input: Cancel the repair against a record because the update succeed . [CODESPLIT] @ Override public void cancelRepairRecord ( final ORecordId rid ) { if ( ! active ) return ; if ( rid . getClusterPosition ( ) < - 1 ) // SKIP TRANSACTIONAL RIDS return ; // REMOVE THE RECORD TO REPAIR if ( records . remove ( rid ) != null ) // REMOVED recordCanceled . incrementAndGet ( ) ; }


Input: Enqueues the request to repair a cluster . The decision about repairing is taken by the timer task . [CODESPLIT] @ Override public void enqueueRepairCluster ( final int clusterId ) { if ( ! active ) return ; if ( clusterId < - 1 ) // SKIP TRANSACTIONAL RIDS return ; recordProcessed . incrementAndGet ( ) ; // ADD CLUSTER TO REPAIR clusters . put ( clusterId , Boolean . TRUE ) ; }


Input: Execute the command . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . SERVER , "status" , ORole . PERMISSION_READ ) ; if ( ! ( database instanceof ODatabaseDocumentDistributed ) ) { throw new OCommandExecutionException ( "OrientDB is not started in distributed mode" ) ; } final OHazelcastPlugin dManager = ( OHazelcastPlugin ) ( ( ODatabaseDocumentDistributed ) database ) . getDistributedManager ( ) ; if ( dManager == null || ! dManager . isEnabled ( ) ) throw new OCommandExecutionException ( "OrientDB is not started in distributed mode" ) ; final String databaseName = database . getName ( ) ; final ODistributedConfiguration cfg = dManager . getDatabaseConfiguration ( databaseName ) ; if ( parsedStatement . outputText ) { final StringBuilder output = new StringBuilder ( ) ; if ( parsedStatement . servers ) output . append ( ODistributedOutput . formatServerStatus ( dManager , dManager . getClusterConfiguration ( ) ) ) ; if ( parsedStatement . db ) output . append ( ODistributedOutput . formatClusterTable ( dManager , databaseName , cfg , dManager . getTotalNodes ( databaseName ) ) ) ; if ( parsedStatement . latency ) output . append ( ODistributedOutput . formatLatency ( dManager , dManager . getClusterConfiguration ( ) ) ) ; if ( parsedStatement . messages ) output . append ( ODistributedOutput . formatMessages ( dManager , dManager . getClusterConfiguration ( ) ) ) ; return output . toString ( ) ; } final ODocument output = new ODocument ( ) ; if ( parsedStatement . servers ) output . field ( "servers" , dManager . getClusterConfiguration ( ) , OType . EMBEDDED ) ; if ( parsedStatement . db ) output . field ( "database" , cfg . getDocument ( ) , OType . EMBEDDED ) ; return output ; }


Input: Calculate the set of dependency aliases for each alias in the pattern . [CODESPLIT] private Map < String , Set < String > > getDependencies ( Pattern pattern ) { Map < String , Set < String > > result = new HashMap < String , Set < String > > ( ) ; for ( PatternNode node : pattern . aliasToNode . values ( ) ) { Set < String > currentDependencies = new HashSet < String > ( ) ; OWhereClause filter = aliasFilters . get ( node . alias ) ; if ( filter != null && filter . getBaseExpression ( ) != null ) { List < String > involvedAliases = filter . getBaseExpression ( ) . getMatchPatternInvolvedAliases ( ) ; if ( involvedAliases != null ) { currentDependencies . addAll ( involvedAliases ) ; } } result . put ( node . alias , currentDependencies ) ; } return result ; }


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


Input: assigns default aliases to pattern nodes that do not have an explicit alias [CODESPLIT] private void assignDefaultAliases ( List < OMatchExpression > matchExpressions ) { int counter = 0 ; for ( OMatchExpression expression : matchExpressions ) { if ( expression . getOrigin ( ) . getAlias ( ) == null ) { expression . getOrigin ( ) . setAlias ( DEFAULT_ALIAS_PREFIX + ( counter ++ ) ) ; } for ( OMatchPathItem item : expression . getItems ( ) ) { if ( item . getFilter ( ) == null ) { item . setFilter ( new OMatchFilter ( - 1 ) ) ; } if ( item . getFilter ( ) . getAlias ( ) == null ) { item . getFilter ( ) . setAlias ( DEFAULT_ALIAS_PREFIX + ( counter ++ ) ) ; } } } }


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


Input: Scans all classes accessible from the context class loader which belong to the given package and subpackages . [CODESPLIT] public synchronized void deregisterEntityClasses ( final String iPackageName , final ClassLoader iClassLoader ) { OLogManager . instance ( ) . debug ( this , "Discovering entity classes inside package: %s" , iPackageName ) ; List < Class < ? > > classes = null ; try { classes = OReflectionHelper . getClassesFor ( iPackageName , iClassLoader ) ; } catch ( ClassNotFoundException e ) { throw OException . wrapException ( new ODatabaseException ( "Class cannot be found in package " + iPackageName ) , e ) ; } for ( Class < ? > c : classes ) { deregisterEntityClass ( c ) ; } if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) { for ( Entry < String , Class < ? > > entry : classHandler . getClassesEntrySet ( ) ) { OLogManager . instance ( ) . debug ( this , "Unloaded entity class '%s' from: %s" , entry . getKey ( ) , entry . getValue ( ) ) ; } } }


Input: Registers provided classes [CODESPLIT] public synchronized void registerEntityClasses ( final Collection < String > iClassNames , final ClassLoader iClassLoader ) { OLogManager . instance ( ) . debug ( this , "Discovering entity classes for class names: %s" , iClassNames ) ; try { registerEntityClasses ( OReflectionHelper . getClassesFor ( iClassNames , iClassLoader ) ) ; } catch ( ClassNotFoundException e ) { throw OException . wrapException ( new ODatabaseException ( "Entity class cannot be found" ) , e ) ; } }


Input: Scans all classes accessible from the context class loader which belong to the given class and all it s attributes - classes . [CODESPLIT] public synchronized void registerEntityClasses ( Class < ? > aClass , boolean recursive ) { if ( recursive ) { classHandler . registerEntityClass ( aClass ) ; Field [ ] declaredFields = aClass . getDeclaredFields ( ) ; for ( Field declaredField : declaredFields ) { Class < ? > declaredFieldType = declaredField . getType ( ) ; if ( ! classHandler . containsEntityClass ( declaredFieldType ) ) { registerEntityClasses ( declaredFieldType , recursive ) ; } } } else { classHandler . registerEntityClass ( aClass ) ; } }


Input: Sets the received handler as default and merges the classes all together . [CODESPLIT] public synchronized void setClassHandler ( final OEntityManagerClassHandler iClassHandler ) { Iterator < Entry < String , Class < ? > > > iterator = classHandler . getClassesEntrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Entry < String , Class < ? > > entry = iterator . next ( ) ; boolean forceSchemaReload = ! iterator . hasNext ( ) ; iClassHandler . registerEntityClass ( entry . getValue ( ) , forceSchemaReload ) ; } this . classHandler = iClassHandler ; }


Input: Acquires a connection from the pool . If the pool is empty then the caller thread will wait for it . [CODESPLIT] public DB acquire ( final String iName , final String iUserName , final String iUserPassword ) { setup ( ) ; return dbPool . acquire ( iName , iUserName , iUserPassword ) ; }


Input: Returns amount of available connections which you can acquire for given source and user name . Source id is consist of source name and source user name . [CODESPLIT] public int getAvailableConnections ( final String name , final String userName ) { setup ( ) ; return dbPool . getAvailableConnections ( name , userName ) ; }


Input: Acquires a connection from the pool specifying options . If the pool is empty then the caller thread will wait for it . [CODESPLIT] public DB acquire ( final String iName , final String iUserName , final String iUserPassword , final Map < String , Object > iOptionalParams ) { setup ( ) ; return dbPool . acquire ( iName , iUserName , iUserPassword , iOptionalParams ) ; }


Input: Execute the SYNC CLUSTER . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . CLUSTER , "sync" , ORole . PERMISSION_UPDATE ) ; if ( ! ( database instanceof ODatabaseDocumentDistributed ) ) { throw new OCommandExecutionException ( "OrientDB is not started in distributed mode" ) ; } final OHazelcastPlugin dManager = ( OHazelcastPlugin ) ( ( ODatabaseDocumentDistributed ) database ) . getDistributedManager ( ) ; if ( dManager == null || ! dManager . isEnabled ( ) ) throw new OCommandExecutionException ( "OrientDB is not started in distributed mode" ) ; final String databaseName = database . getName ( ) ; try { if ( this . parsedStatement . modeFull ) { return replaceCluster ( dManager , database , dManager . getServerInstance ( ) , databaseName , this . parsedStatement . clusterName . getStringValue ( ) ) ; } // else { // int merged = 0; // return String.format("Merged %d records", merged); // } } catch ( Exception e ) { throw OException . wrapException ( new OCommandExecutionException ( "Cannot execute synchronization of cluster" ) , e ) ; } return "Mode not supported" ; }


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


Input: Switch to the OrientDb classloader before lookups on ServiceRegistry for implementation of the given Class . Useful under OSGI and generally under applications where jars are loaded by another class loader [CODESPLIT] public static synchronized < T extends Object > Iterator < T > lookupProviderWithOrientClassLoader ( Class < T > clazz ) { return lookupProviderWithOrientClassLoader ( clazz , OClassLoaderHelper . class . getClassLoader ( ) ) ; }


Input: @param unlimitedCap the upper limit on reported memory if JVM reports unlimited memory . [CODESPLIT] public static long getCappedRuntimeMaxMemory ( long unlimitedCap ) { final long jvmMaxMemory = Runtime . getRuntime ( ) . maxMemory ( ) ; return jvmMaxMemory == Long . MAX_VALUE ? unlimitedCap : jvmMaxMemory ; }


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


Input: Tries to fix some common cache / memory configuration problems : <ul > <li > Cache size is larger than direct memory size . < / li > <li > Memory chunk size is larger than cache size . < / li > <ul / > [CODESPLIT] public static void fixCommonConfigurationProblems ( ) { long diskCacheSize = OGlobalConfiguration . DISK_CACHE_SIZE . getValueAsLong ( ) ; final int max32BitCacheSize = 512 ; if ( getJavaBitWidth ( ) == 32 && diskCacheSize > max32BitCacheSize ) { OLogManager . instance ( ) . infoNoDb ( OGlobalConfiguration . class , "32 bit JVM is detected. Lowering disk cache size from %,dMB to %,dMB." , diskCacheSize , max32BitCacheSize ) ; OGlobalConfiguration . DISK_CACHE_SIZE . setValue ( max32BitCacheSize ) ; } }


Input: Creates a vertex from GraphSON using settings supplied in the constructor . [CODESPLIT] public Vertex vertexFromJson ( final InputStream json ) throws IOException { final JsonParser jp = jsonFactory . createParser ( json ) ; final JsonNode node = jp . readValueAsTree ( ) ; return this . vertexFromJson ( node ) ; }


Input: Creates a vertex from GraphSON using settings supplied in the constructor . [CODESPLIT] public Vertex vertexFromJson ( final JsonNode json ) throws IOException { final Map < String , Object > props = readProperties ( json , true , this . hasEmbeddedTypes ) ; final Object vertexId = getTypedValueFromJsonNode ( json . get ( GraphSONTokens . _ID ) ) ; final Vertex v = factory . createVertex ( vertexId ) ; for ( Map . Entry < String , Object > entry : props . entrySet ( ) ) { // if (this.vertexPropertyKeys == null || vertexPropertyKeys.contains(entry.getKey())) { if ( includeKey ( entry . getKey ( ) , vertexPropertyKeys , this . vertexPropertiesRule ) ) { v . setProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return v ; }


Input: Creates an edge from GraphSON using settings supplied in the constructor . [CODESPLIT] public Edge edgeFromJson ( final JSONObject json , final Vertex out , final Vertex in ) throws IOException { return this . edgeFromJson ( json . toString ( ) , out , in ) ; }


Input: Creates an edge from GraphSON using settings supplied in the constructor . [CODESPLIT] public Edge edgeFromJson ( final String json , final Vertex out , final Vertex in ) throws IOException { final JsonParser jp = jsonFactory . createParser ( json ) ; final JsonNode node = jp . readValueAsTree ( ) ; return this . edgeFromJson ( node , out , in ) ; }


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


Input: Creates GraphSON for a single graph element . [CODESPLIT] public JSONObject jsonFromElement ( final Element element ) throws JSONException { final ObjectNode objectNode = this . objectNodeFromElement ( element ) ; try { return new JSONObject ( new JSONTokener ( mapper . writeValueAsString ( objectNode ) ) ) ; } catch ( IOException ioe ) { // repackage this as a JSONException...seems sensible as the caller will only know about // the jettison object not being created throw new JSONException ( ioe ) ; } }


Input: Creates GraphSON for a single graph element . [CODESPLIT] public ObjectNode objectNodeFromElement ( final Element element ) { final boolean isEdge = element instanceof Edge ; final boolean showTypes = mode == GraphSONMode . EXTENDED ; final List < String > propertyKeys = isEdge ? this . edgePropertyKeys : this . vertexPropertyKeys ; final ElementPropertiesRule elementPropertyConfig = isEdge ? this . edgePropertiesRule : this . vertexPropertiesRule ; final ObjectNode jsonElement = createJSONMap ( createPropertyMap ( element , propertyKeys , elementPropertyConfig , normalized ) , propertyKeys , showTypes ) ; if ( ( isEdge && this . includeReservedEdgeId ) || ( ! isEdge && this . includeReservedVertexId ) ) { putObject ( jsonElement , GraphSONTokens . _ID , element . getId ( ) ) ; } // it's important to keep the order of these straight. check Edge first and then Vertex because there // are graph implementations that have Edge extend from Vertex if ( element instanceof Edge ) { final Edge edge = ( Edge ) element ; if ( this . includeReservedEdgeId ) { putObject ( jsonElement , GraphSONTokens . _ID , element . getId ( ) ) ; } if ( this . includeReservedEdgeType ) { jsonElement . put ( GraphSONTokens . _TYPE , GraphSONTokens . EDGE ) ; } if ( this . includeReservedEdgeOutV ) { putObject ( jsonElement , GraphSONTokens . _OUT_V , edge . getVertex ( Direction . OUT ) . getId ( ) ) ; } if ( this . includeReservedEdgeInV ) { putObject ( jsonElement , GraphSONTokens . _IN_V , edge . getVertex ( Direction . IN ) . getId ( ) ) ; } if ( this . includeReservedEdgeLabel ) { jsonElement . put ( GraphSONTokens . _LABEL , edge . getLabel ( ) ) ; } } else if ( element instanceof Vertex ) { if ( this . includeReservedVertexId ) { putObject ( jsonElement , GraphSONTokens . _ID , element . getId ( ) ) ; } if ( this . includeReservedVertexType ) { jsonElement . put ( GraphSONTokens . _TYPE , GraphSONTokens . VERTEX ) ; } } return jsonElement ; }


Input: Reads an individual Vertex from JSON . The vertex must match the accepted GraphSON format . [CODESPLIT] public static Vertex vertexFromJson ( final JSONObject json , final ElementFactory factory , final GraphSONMode mode , final Set < String > propertyKeys ) throws IOException { final OGraphSONUtility graphson = new OGraphSONUtility ( mode , factory , propertyKeys , null ) ; return graphson . vertexFromJson ( json ) ; }


Input: Reads an individual Edge from JSON . The edge must match the accepted GraphSON format . [CODESPLIT] public static Edge edgeFromJson ( final JSONObject json , final Vertex out , final Vertex in , final ElementFactory factory , final GraphSONMode mode , final Set < String > propertyKeys ) throws IOException { final OGraphSONUtility graphson = new OGraphSONUtility ( mode , factory , null , propertyKeys ) ; return graphson . edgeFromJson ( json , out , in ) ; }


Input: Creates a Jettison JSONObject from a graph element . [CODESPLIT] public static JSONObject jsonFromElement ( final Element element , final Set < String > propertyKeys , final GraphSONMode mode ) throws JSONException { final OGraphSONUtility graphson = element instanceof Edge ? new OGraphSONUtility ( mode , null , null , propertyKeys ) : new OGraphSONUtility ( mode , null , propertyKeys , null ) ; return graphson . jsonFromElement ( element ) ; }


Input: Creates a Jackson ObjectNode from a graph element . [CODESPLIT] public static ObjectNode objectNodeFromElement ( final Element element , final Set < String > propertyKeys , final GraphSONMode mode ) { final OGraphSONUtility graphson = element instanceof Edge ? new OGraphSONUtility ( mode , null , null , propertyKeys ) : new OGraphSONUtility ( mode , null , propertyKeys , null ) ; return graphson . objectNodeFromElement ( element ) ; }


Input: Executes import with configuration ; [CODESPLIT] public void executeImport ( ODocument cfg , OServer server ) { OETLJob job = new OETLJob ( cfg , server , new OETLListener ( ) { @ Override public void onEnd ( OETLJob etlJob ) { currentJob = null ; } } ) ; job . validate ( ) ; currentJob = job ; pool . execute ( job ) ; }


Input: Status of the Running Jobs [CODESPLIT] public ODocument status ( ) { ODocument status = new ODocument ( ) ; Collection < ODocument > jobs = new ArrayList < ODocument > ( ) ; if ( currentJob != null ) { jobs . add ( currentJob . status ( ) ) ; } status . field ( "jobs" , jobs ) ; return status ; }


Input:
{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( OIdentifiable object , ByteBuffer buffer , Object ... hints ) { final ORID r = object . getIdentity ( ) ; buffer . putShort ( ( short ) r . getClusterId ( ) ) ; // Wrong implementation but needed for binary compatibility
 byte [ ] stream = new byte [ OLongSerializer . LONG_SIZE ] ; OLongSerializer . INSTANCE . serialize ( r . getClusterPosition ( ) , stream , 0 ) ; buffer . put ( stream ) ; }


Input:
{ [CODESPLIT] @ Override public OIdentifiable deserializeFromByteBufferObject ( ByteBuffer buffer ) { final int clusterId = buffer . getShort ( ) ; final byte [ ] stream = new byte [ OLongSerializer . LONG_SIZE ] ; buffer . get ( stream ) ; // Wrong implementation but needed for binary compatibility
 final long clusterPosition = OLongSerializer . INSTANCE . deserialize ( stream , 0 ) ; return new ORecordId ( clusterId , clusterPosition ) ; }


Input:
{ [CODESPLIT] @ Override public OIdentifiable deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final int clusterId = walChanges . getShortValue ( buffer , offset ) ; // Wrong implementation but needed for binary compatibility
 final long clusterPosition = OLongSerializer . INSTANCE . deserialize ( walChanges . getBinaryValue ( buffer , offset + OShortSerializer . SHORT_SIZE , OLongSerializer . LONG_SIZE ) , 0 ) ; // final long clusterPosition = OLongSerializer.INSTANCE
 // .deserializeFromDirectMemory(pointer, offset + OShortSerializer.SHORT_SIZE);
 return new ORecordId ( clusterId , clusterPosition ) ; }


Input: Returns { @link Comparator } instance if applicable one exist or <code > null< / code > otherwise . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < T > Comparator < T > getComparator ( Class < T > clazz ) { boolean useUnsafe = OGlobalConfiguration . MEMORY_USE_UNSAFE . getValueAsBoolean ( ) ; if ( clazz . equals ( byte [ ] . class ) ) { if ( useUnsafe && unsafeWasDetected ) return ( Comparator < T > ) OUnsafeByteArrayComparator . INSTANCE ; return ( Comparator < T > ) OByteArrayComparator . INSTANCE ; } return null ; }


Input: returns the cluster map for current deploy . The keys of the map are node names the values contain names of clusters ( data files ) available on the single node . [CODESPLIT] public Map < String , Set < String > > getActiveClusterMap ( ) { if ( distributedManager . isOffline ( ) || ! distributedManager . isNodeOnline ( distributedManager . getLocalNodeName ( ) , getName ( ) ) || OScenarioThreadLocal . INSTANCE . isRunModeDistributed ( ) ) { return super . getActiveClusterMap ( ) ; } Map < String , Set < String > > result = new HashMap <> ( ) ; ODistributedConfiguration cfg = getDistributedConfiguration ( ) ; for ( String server : distributedManager . getActiveServers ( ) ) { if ( getClustersOnServer ( cfg , server ) . contains ( "*" ) ) { //TODO check this!!! result . put ( server , getStorage ( ) . getClusterNames ( ) ) ; } else { result . put ( server , getClustersOnServer ( cfg , server ) ) ; } } return result ; }


Input: returns the data center map for current deploy . The keys are data center names the values are node names per data center [CODESPLIT] public Map < String , Set < String > > getActiveDataCenterMap ( ) { Map < String , Set < String > > result = new HashMap <> ( ) ; ODistributedConfiguration cfg = getDistributedConfiguration ( ) ; Set < String > servers = cfg . getRegisteredServers ( ) ; for ( String server : servers ) { String dc = cfg . getDataCenterOfServer ( server ) ; Set < String > dcConfig = result . get ( dc ) ; if ( dcConfig == null ) { dcConfig = new HashSet <> ( ) ; result . put ( dc , dcConfig ) ; } dcConfig . add ( server ) ; } return result ; }


Input: @param transactionId [CODESPLIT] public boolean commit2pc ( ODistributedRequestId transactionId , boolean local ) { getStorageDistributed ( ) . resetLastValidBackup ( ) ; ODistributedDatabase localDistributedDatabase = getStorageDistributed ( ) . getLocalDistributedDatabase ( ) ; ONewDistributedTxContextImpl txContext = ( ONewDistributedTxContextImpl ) localDistributedDatabase . getTxContext ( transactionId ) ; if ( txContext != null ) { if ( SUCCESS . equals ( txContext . getStatus ( ) ) ) { try { txContext . commit ( this ) ; localDistributedDatabase . popTxContext ( transactionId ) ; OLiveQueryHook . notifyForTxChanges ( this ) ; OLiveQueryHookV2 . notifyForTxChanges ( this ) ; } finally { OLiveQueryHook . removePendingDatabaseOps ( this ) ; OLiveQueryHookV2 . removePendingDatabaseOps ( this ) ; } return true ; } else if ( TIMEDOUT . equals ( txContext . getStatus ( ) ) ) { int nretry = getConfiguration ( ) . getValueAsInteger ( DISTRIBUTED_CONCURRENT_TX_MAX_AUTORETRY ) ; int delay = getConfiguration ( ) . getValueAsInteger ( DISTRIBUTED_CONCURRENT_TX_AUTORETRY_DELAY ) ; for ( int i = 0 ; i < nretry ; i ++ ) { try { if ( i > 0 ) { try { Thread . sleep ( new Random ( ) . nextInt ( delay ) ) ; } catch ( InterruptedException e ) { OException . wrapException ( new OInterruptedException ( e . getMessage ( ) ) , e ) ; } } internalBegin2pc ( txContext , local ) ; txContext . setStatus ( SUCCESS ) ; break ; } catch ( ODistributedRecordLockedException | ODistributedKeyLockedException ex ) { // Just retry } catch ( Exception ex ) { OLogManager . instance ( ) . warn ( ODatabaseDocumentDistributed . this , "Error beginning timed out transaction: %s " , ex , transactionId ) ; break ; } } if ( ! SUCCESS . equals ( txContext . getStatus ( ) ) ) { txContext . destroy ( ) ; localDistributedDatabase . popTxContext ( transactionId ) ; Orient . instance ( ) . submit ( ( ) -> { OLogManager . instance ( ) . warn ( ODatabaseDocumentDistributed . this , "Reached limit of retry for commit tx:%s forcing database re-install" , transactionId ) ; distributedManager . installDatabase ( false , ODatabaseDocumentDistributed . this . getName ( ) , true , true ) ; } ) ; return true ; } try { txContext . commit ( this ) ; localDistributedDatabase . popTxContext ( transactionId ) ; OLiveQueryHook . notifyForTxChanges ( this ) ; OLiveQueryHookV2 . notifyForTxChanges ( this ) ; return true ; } finally { OLiveQueryHook . removePendingDatabaseOps ( this ) ; OLiveQueryHookV2 . removePendingDatabaseOps ( this ) ; } } else { txContext . destroy ( ) ; localDistributedDatabase . popTxContext ( transactionId ) ; Orient . instance ( ) . submit ( ( ) -> { OLogManager . instance ( ) . warn ( ODatabaseDocumentDistributed . this , "Reached limit of retry for commit tx:%s forcing database re-install" , transactionId ) ; distributedManager . installDatabase ( false , ODatabaseDocumentDistributed . this . getName ( ) , true , true ) ; } ) ; return true ; } } return false ; }


Input: { [CODESPLIT] public String toCreateIndexDDL ( final String indexName , final String indexType , String engine ) { return "create index `" + indexName + "` " + indexType + ' ' + "runtime " + serializer . getId ( ) ; }


Input: Returns the secret key algorithm portion of the cipher transformation . [CODESPLIT] protected static String separateAlgorithm ( final String cipherTransform ) { String [ ] array = cipherTransform . split ( "/" ) ; if ( array . length > 1 ) return array [ 0 ] ; return null ; }


Input: Creates an OSymmetricKey from an OSymmetricKeyConfig interface . [CODESPLIT] public static OSymmetricKey fromConfig ( final OSymmetricKeyConfig keyConfig ) { if ( keyConfig . usesKeyString ( ) ) { return fromString ( keyConfig . getKeyAlgorithm ( ) , keyConfig . getKeyString ( ) ) ; } else if ( keyConfig . usesKeyFile ( ) ) { return fromFile ( keyConfig . getKeyAlgorithm ( ) , keyConfig . getKeyFile ( ) ) ; } else if ( keyConfig . usesKeystore ( ) ) { return fromKeystore ( keyConfig . getKeystoreFile ( ) , keyConfig . getKeystorePassword ( ) , keyConfig . getKeystoreKeyAlias ( ) , keyConfig . getKeystoreKeyPassword ( ) ) ; } else { throw new OSecurityException ( "OSymmetricKey(OSymmetricKeyConfig) Invalid configuration" ) ; } }


Input: Creates an OSymmetricKey from a file containing a Base64 key . [CODESPLIT] public static OSymmetricKey fromFile ( final String algorithm , final String path ) { String base64Key = null ; try { java . io . FileInputStream fis = null ; try { fis = new java . io . FileInputStream ( OSystemVariableResolver . resolveSystemVariables ( path ) ) ; return fromStream ( algorithm , fis ) ; } finally { if ( fis != null ) fis . close ( ) ; } } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.fromFile() Exception: " + ex . getMessage ( ) ) , ex ) ; } }


Input: Creates an OSymmetricKey from an InputStream containing a Base64 key . [CODESPLIT] public static OSymmetricKey fromStream ( final String algorithm , final InputStream is ) { String base64Key = null ; try { base64Key = OIOUtils . readStreamAsString ( is ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.fromStream() Exception: " + ex . getMessage ( ) ) , ex ) ; } return new OSymmetricKey ( algorithm , base64Key ) ; }


Input: Creates an OSymmetricKey from a Java JCEKS KeyStore . [CODESPLIT] public static OSymmetricKey fromKeystore ( final String path , final String password , final String keyAlias , final String keyPassword ) { OSymmetricKey sk = null ; try { KeyStore ks = KeyStore . getInstance ( "JCEKS" ) ; // JCEKS is required to hold SecretKey entries. java . io . FileInputStream fis = null ; try { fis = new java . io . FileInputStream ( OSystemVariableResolver . resolveSystemVariables ( path ) ) ; return fromKeystore ( fis , password , keyAlias , keyPassword ) ; } finally { if ( fis != null ) fis . close ( ) ; } } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.fromKeystore() Exception: " + ex . getMessage ( ) ) , ex ) ; } }


Input: Creates an OSymmetricKey from a Java JCEKS KeyStore . [CODESPLIT] public static OSymmetricKey fromKeystore ( final InputStream is , final String password , final String keyAlias , final String keyPassword ) { OSymmetricKey sk = null ; try { KeyStore ks = KeyStore . getInstance ( "JCEKS" ) ; // JCEKS is required to hold SecretKey entries. char [ ] ksPasswdChars = null ; if ( password != null ) ksPasswdChars = password . toCharArray ( ) ; ks . load ( is , ksPasswdChars ) ; // ksPasswdChars may be null. char [ ] ksKeyPasswdChars = null ; if ( keyPassword != null ) ksKeyPasswdChars = keyPassword . toCharArray ( ) ; KeyStore . ProtectionParameter protParam = new KeyStore . PasswordProtection ( ksKeyPasswdChars ) ; // ksKeyPasswdChars may be null. KeyStore . SecretKeyEntry skEntry = ( KeyStore . SecretKeyEntry ) ks . getEntry ( keyAlias , protParam ) ; if ( skEntry == null ) throw new OSecurityException ( "SecretKeyEntry is null for key alias: " + keyAlias ) ; SecretKey secretKey = skEntry . getSecretKey ( ) ; sk = new OSymmetricKey ( secretKey ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.fromKeystore() Exception: " + ex . getMessage ( ) ) , ex ) ; } return sk ; }


Input: This is a convenience method that takes a String argument encodes it as Base64 then calls encrypt ( byte [] ) . [CODESPLIT] public String encrypt ( final String value ) { try { return encrypt ( value . getBytes ( "UTF8" ) ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.encrypt() Exception: " + ex . getMessage ( ) ) , ex ) ; } }


Input: This method encrypts an array of bytes . [CODESPLIT] public String encrypt ( final String transform , final byte [ ] bytes ) { String encodedJSON = null ; if ( secretKey == null ) throw new OSecurityException ( "OSymmetricKey.encrypt() SecretKey is null" ) ; if ( transform == null ) throw new OSecurityException ( "OSymmetricKey.encrypt() Cannot determine cipher transformation" ) ; try { // Throws NoSuchAlgorithmException and NoSuchPaddingException. Cipher cipher = Cipher . getInstance ( transform ) ; // If the cipher transformation requires an initialization vector then init() will create a random one. // (Use cipher.getIV() to retrieve the IV, if it exists.) cipher . init ( Cipher . ENCRYPT_MODE , secretKey ) ; // If the cipher does not use an IV, this will be null. byte [ ] initVector = cipher . getIV ( ) ; //      byte[] initVector = encCipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); byte [ ] encrypted = cipher . doFinal ( bytes ) ; encodedJSON = encodeJSON ( encrypted , initVector ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.encrypt() Exception: " + ex . getMessage ( ) ) , ex ) ; } return encodedJSON ; }


Input: This method decrypts the Base64 - encoded JSON document using the specified algorithm and cipher transformation . [CODESPLIT] public String decryptAsString ( final String encodedJSON ) { try { byte [ ] decrypted = decrypt ( encodedJSON ) ; return new String ( decrypted , "UTF8" ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.decryptAsString() Exception: " + ex . getMessage ( ) ) , ex ) ; } }


Input: This method decrypts the Base64 - encoded JSON document using the specified algorithm and cipher transformation . [CODESPLIT] public byte [ ] decrypt ( final String encodedJSON ) { byte [ ] result = null ; if ( encodedJSON == null ) throw new OSecurityException ( "OSymmetricKey.decrypt(String) encodedJSON is null" ) ; try { byte [ ] decoded = convertFromBase64 ( encodedJSON ) ; if ( decoded == null ) throw new OSecurityException ( "OSymmetricKey.decrypt(String) encodedJSON could not be decoded" ) ; String json = new String ( decoded , "UTF8" ) ; // Convert the JSON content to an ODocument to make parsing it easier. final ODocument doc = new ODocument ( ) . fromJSON ( json , "noMap" ) ; // Set a default in case the JSON document does not contain an "algorithm" property. String algorithm = secretKeyAlgorithm ; if ( doc . containsField ( "algorithm" ) ) algorithm = doc . field ( "algorithm" ) ; // Set a default in case the JSON document does not contain a "transform" property. String transform = defaultCipherTransformation ; if ( doc . containsField ( "transform" ) ) transform = doc . field ( "transform" ) ; String payloadBase64 = doc . field ( "payload" ) ; String ivBase64 = doc . field ( "iv" ) ; byte [ ] payload = null ; byte [ ] iv = null ; if ( payloadBase64 != null ) payload = convertFromBase64 ( payloadBase64 ) ; if ( ivBase64 != null ) iv = convertFromBase64 ( ivBase64 ) ; // Throws NoSuchAlgorithmException and NoSuchPaddingException. Cipher cipher = Cipher . getInstance ( transform ) ; if ( iv != null ) cipher . init ( Cipher . DECRYPT_MODE , secretKey , new IvParameterSpec ( iv ) ) ; else cipher . init ( Cipher . DECRYPT_MODE , secretKey ) ; result = cipher . doFinal ( payload ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.decrypt(String) Exception: " + ex . getMessage ( ) ) , ex ) ; } return result ; }


Input: Saves the internal SecretKey to the specified OutputStream as a Base64 String . [CODESPLIT] public void saveToStream ( final OutputStream os ) { if ( os == null ) throw new OSecurityException ( "OSymmetricKey.saveToStream() OutputStream is null" ) ; try { final OutputStreamWriter osw = new OutputStreamWriter ( os ) ; try { final BufferedWriter writer = new BufferedWriter ( osw ) ; try { writer . write ( getBase64Key ( ) ) ; } finally { writer . close ( ) ; } } finally { os . close ( ) ; } } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.saveToStream() Exception: " + ex . getMessage ( ) ) , ex ) ; } }


Input: Saves the internal SecretKey as a KeyStore . [CODESPLIT] public void saveToKeystore ( final OutputStream os , final String ksPasswd , final String keyAlias , final String keyPasswd ) { if ( os == null ) throw new OSecurityException ( "OSymmetricKey.saveToKeystore() OutputStream is null" ) ; if ( ksPasswd == null ) throw new OSecurityException ( "OSymmetricKey.saveToKeystore() Keystore Password is required" ) ; if ( keyAlias == null ) throw new OSecurityException ( "OSymmetricKey.saveToKeystore() Key Alias is required" ) ; if ( keyPasswd == null ) throw new OSecurityException ( "OSymmetricKey.saveToKeystore() Key Password is required" ) ; try { KeyStore ks = KeyStore . getInstance ( "JCEKS" ) ; char [ ] ksPasswdCA = ksPasswd . toCharArray ( ) ; char [ ] keyPasswdCA = keyPasswd . toCharArray ( ) ; // Create a new KeyStore by passing null. ks . load ( null , ksPasswdCA ) ; KeyStore . ProtectionParameter protParam = new KeyStore . PasswordProtection ( keyPasswdCA ) ; KeyStore . SecretKeyEntry skEntry = new KeyStore . SecretKeyEntry ( secretKey ) ; ks . setEntry ( keyAlias , skEntry , protParam ) ; // Save the KeyStore ks . store ( os , ksPasswdCA ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.saveToKeystore() Exception: " + ex . getMessage ( ) ) , ex ) ; } }


Input: { [CODESPLIT] @ Override public void serializeInByteBufferObject ( UUID object , ByteBuffer buffer , Object ... hints ) { buffer . putLong ( object . getMostSignificantBits ( ) ) ; buffer . putLong ( object . getLeastSignificantBits ( ) ) ; }


Input: { [CODESPLIT] @ Override public UUID deserializeFromByteBufferObject ( ByteBuffer buffer ) { final long mostSignificantBits = buffer . getLong ( ) ; final long leastSignificantBits = buffer . getLong ( ) ; return new UUID ( mostSignificantBits , leastSignificantBits ) ; }


Input: { [CODESPLIT] @ Override public UUID deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final long mostSignificantBits = walChanges . getLongValue ( buffer , offset ) ; final long leastSignificantBits = walChanges . getLongValue ( buffer , offset + OLongSerializer . LONG_SIZE ) ; return new UUID ( mostSignificantBits , leastSignificantBits ) ; }


Input:
Set the inherited context avoiding to copy all the values every time . [CODESPLIT] public OCommandContext setChild ( final OCommandContext iContext ) { if ( iContext == null ) { if ( child != null ) { // REMOVE IT
 child . setParent ( null ) ; child = null ; } } else if ( child != iContext ) { // ADD IT
 child = iContext ; iContext . setParent ( this ) ; } return this ; }


Input: adds an item to the unique result set [CODESPLIT] public synchronized boolean addToUniqueResult ( Object o ) { Object toAdd = o ; if ( o instanceof ODocument && ( ( ODocument ) o ) . getIdentity ( ) . isNew ( ) ) { toAdd = new ODocumentEqualityWrapper ( ( ODocument ) o ) ; } return this . uniqueResult . add ( toAdd ) ; }


Input: { [CODESPLIT] @ Override public void serializeInByteBufferObject ( BigDecimal object , ByteBuffer buffer , Object ... hints ) { buffer . putInt ( object . scale ( ) ) ; OBinaryTypeSerializer . INSTANCE . serializeInByteBufferObject ( object . unscaledValue ( ) . toByteArray ( ) , buffer ) ; }


Input: { [CODESPLIT] @ Override public BigDecimal deserializeFromByteBufferObject ( ByteBuffer buffer ) { final int scale = buffer . getInt ( ) ; final byte [ ] unscaledValue = OBinaryTypeSerializer . INSTANCE . deserializeFromByteBufferObject ( buffer ) ; return new BigDecimal ( new BigInteger ( unscaledValue ) , scale ) ; }


Input: { [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer ) { buffer . position ( buffer . position ( ) + OIntegerSerializer . INT_SIZE ) ; return OIntegerSerializer . INT_SIZE + OBinaryTypeSerializer . INSTANCE . getObjectSizeInByteBuffer ( buffer ) ; }


Input: { [CODESPLIT] @ Override public BigDecimal deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final int scale = walChanges . getIntValue ( buffer , offset ) ; offset += OIntegerSerializer . INT_SIZE ; final byte [ ] unscaledValue = OBinaryTypeSerializer . INSTANCE . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ; return new BigDecimal ( new BigInteger ( unscaledValue ) , scale ) ; }


Input: { [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return OIntegerSerializer . INT_SIZE + OBinaryTypeSerializer . INSTANCE . getObjectSizeInByteBuffer ( buffer , walChanges , offset + OIntegerSerializer . INT_SIZE ) ; }


Input: OBJECT OR MAP . CHECK THE TYPE ATTRIBUTE TO KNOW IT . [CODESPLIT] private Object getValueAsObjectOrMap ( ODocument iRecord , String iFieldValue , OType iType , OType iLinkedType , Map < String , Character > iFieldTypes , boolean iNoMap , String iOptions ) { final String [ ] fields = OStringParser . getWords ( iFieldValue . substring ( 1 , iFieldValue . length ( ) - 1 ) , ":," , true ) ; if ( fields == null || fields . length == 0 ) if ( iNoMap ) { ODocument res = new ODocument ( ) ; ODocumentInternal . addOwner ( res , iRecord ) ; return res ; } else return new HashMap < String , Object > ( ) ; if ( iNoMap || hasTypeField ( fields ) ) { return getValueAsRecord ( iRecord , iFieldValue , iType , iOptions , fields ) ; } else { return getValueAsMap ( iRecord , iFieldValue , iLinkedType , iFieldTypes , false , iOptions , fields ) ; } }


Input: null is returned in all other cases and means authentication was unsuccessful . [CODESPLIT] protected String authenticate ( final String username , final String password , final String iDatabaseName ) throws IOException { ODatabaseDocument db = null ; String userRid = null ; try { db = ( ODatabaseDocument ) server . openDatabase ( iDatabaseName , username , password ) ; userRid = ( db . getUser ( ) == null ? "<server user>" : db . getUser ( ) . getDocument ( ) . getIdentity ( ) . toString ( ) ) ; } catch ( OSecurityAccessException e ) { // WRONG USER/PASSWD } catch ( OLockException e ) { OLogManager . instance ( ) . error ( this , "Cannot access to the database '" + iDatabaseName + "'" , e ) ; } finally { if ( db != null ) { db . close ( ) ; } } return userRid ; }


Input: Retrieves the value crossing the map with the dotted notation [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static Object getMapEntry ( final Map < String , ? > iMap , final Object iKey ) { if ( iMap == null || iKey == null ) return null ; if ( iKey instanceof String ) { String iName = ( String ) iKey ; int pos = iName . indexOf ( ' ' ) ; if ( pos > - 1 ) iName = iName . substring ( 0 , pos ) ; final Object value = iMap . get ( iName ) ; if ( value == null ) return null ; if ( pos > - 1 ) { final String restFieldName = iName . substring ( pos + 1 ) ; if ( value instanceof ODocument ) return getFieldValue ( value , restFieldName ) ; else if ( value instanceof Map < ? , ? > ) return getMapEntry ( ( Map < String , ? > ) value , restFieldName ) ; } return value ; } else return iMap . get ( iKey ) ; }


Input: Makes a deep comparison field by field to check if the passed ODocument instance is identical as identity and content to the current one . Instead equals () just checks if the RID are the same . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static boolean hasSameContentOf ( final ODocument iCurrent , final ODatabaseDocumentInternal iMyDb , final ODocument iOther , final ODatabaseDocumentInternal iOtherDb , RIDMapper ridMapper ) { return hasSameContentOf ( iCurrent , iMyDb , iOther , iOtherDb , ridMapper , true ) ; }