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


Input: Collect up the characters as element s characters may be split across multiple calls . Isn t SAX lovely ... [CODESPLIT] @ Override public void characters ( char [ ] ch , int start , int length ) throws SAXException { builder . append ( ch , start , length ) ; }


Input: Converts a string produced by <code > timeToString< / code > or <code > dateToString< / code > back to a time represented as a Date object . [CODESPLIT] public static Date stringToDate ( String dateString ) throws ParseException { try { SimpleDateFormat format = RESOLUTIONS [ dateString . length ( ) ] . format ( ) ; return format . parse ( dateString ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( OLuceneDateTools . class , "Exception is suppressed, original exception is " , e ) ; //noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException throw new ParseException ( "Input is not a valid date string: " + dateString , 0 ) ; } }


Input: Tells if the channel is connected . [CODESPLIT] public boolean isConnected ( ) { final Socket s = socket ; return s != null && ! s . isClosed ( ) && s . isConnected ( ) && ! s . isInputShutdown ( ) && ! s . isOutputShutdown ( ) ; }


Input: Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( name == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; if ( name . isEmpty ( ) ) throw new OCommandExecutionException ( "Syntax Error. You must specify a function name: " + getSyntax ( ) ) ; if ( code == null || code . isEmpty ( ) ) throw new OCommandExecutionException ( "Syntax Error. You must specify the function code: " + getSyntax ( ) ) ; ODatabaseDocument database = getDatabase ( ) ; final OFunction f = database . getMetadata ( ) . getFunctionLibrary ( ) . createFunction ( name ) ; f . setCode ( code ) ; f . setIdempotent ( idempotent ) ; if ( parameters != null ) f . setParameters ( parameters ) ; if ( language != null ) f . setLanguage ( language ) ; f . save ( ) ; return f . getId ( ) ; }


Input: Merge short value from two byte buffer . First byte of short will be extracted from first byte buffer and second from second one . [CODESPLIT] public static short mergeShortFromBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 ) { short result = 0 ; result = ( short ) ( result | ( buffer . get ( ) & MASK ) ) ; result = ( short ) ( result << SIZE_OF_BYTE_IN_BITS ) ; result = ( short ) ( result | ( buffer1 . get ( ) & MASK ) ) ; return result ; }


Input: Merge int value from two byte buffer . First bytes of int will be extracted from first byte buffer and second from second one . How many bytes will be read from first buffer determines based on <code > buffer . remaining () < / code > value [CODESPLIT] public static int mergeIntFromBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 ) { int result = 0 ; final int remaining = buffer . remaining ( ) ; for ( int i = 0 ; i < remaining ; ++ i ) { result = result | ( buffer . get ( ) & MASK ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } for ( int i = 0 ; i < SIZE_OF_INT - remaining - 1 ; ++ i ) { result = result | ( buffer1 . get ( ) & MASK ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } result = result | ( buffer1 . get ( ) & MASK ) ; return result ; }


Input: Merge long value from two byte buffer . First bytes of long will be extracted from first byte buffer and second from second one . How many bytes will be read from first buffer determines based on <code > buffer . remaining () < / code > value [CODESPLIT] public static long mergeLongFromBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 ) { long result = 0 ; final int remaining = buffer . remaining ( ) ; for ( int i = 0 ; i < remaining ; ++ i ) { result = result | ( MASK & buffer . get ( ) ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } for ( int i = 0 ; i < SIZE_OF_LONG - remaining - 1 ; ++ i ) { result = result | ( MASK & buffer1 . get ( ) ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } result = result | ( MASK & buffer1 . get ( ) ) ; return result ; }


Input: Split short value into two byte buffer . First byte of short will be written to first byte buffer and second to second one . [CODESPLIT] public static void splitShortToBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 , final short iValue ) { buffer . put ( ( byte ) ( MASK & ( iValue >>> SIZE_OF_BYTE_IN_BITS ) ) ) ; buffer1 . put ( ( byte ) ( MASK & iValue ) ) ; }


Input: Split int value into two byte buffer . First byte of int will be written to first byte buffer and second to second one . How many bytes will be written to first buffer determines based on <code > buffer . remaining () < / code > value [CODESPLIT] public static void splitIntToBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 , final int iValue ) { final int remaining = buffer . remaining ( ) ; int i ; for ( i = 0 ; i < remaining ; ++ i ) { buffer . put ( ( byte ) ( MASK & ( iValue >>> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_INT - i - 1 ) ) ) ) ; } for ( int j = 0 ; j < SIZE_OF_INT - remaining ; ++ j ) { buffer1 . put ( ( byte ) ( MASK & ( iValue >>> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_INT - i - j - 1 ) ) ) ) ; } }


Input: Split long value into two byte buffer . First byte of long will be written to first byte buffer and second to second one . How many bytes will be written to first buffer determines based on <code > buffer . remaining () < / code > value [CODESPLIT] public static void splitLongToBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 , final long iValue ) { final int remaining = buffer . remaining ( ) ; int i ; for ( i = 0 ; i < remaining ; ++ i ) { buffer . put ( ( byte ) ( iValue >> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_LONG - i - 1 ) ) ) ; } for ( int j = 0 ; j < SIZE_OF_LONG - remaining ; ++ j ) { buffer1 . put ( ( byte ) ( iValue >> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_LONG - i - j - 1 ) ) ) ; } }


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


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


Input: Indexes a value and save the index . Splits the value in single words and index each one . Save of the index is responsibility of the caller . [CODESPLIT] @ Override public OIndexFullText put ( Object key , final OIdentifiable singleValue ) { if ( key == null ) { return this ; } key = getCollatingValue ( key ) ; final Set < String > words = splitIntoWords ( key . toString ( ) ) ; // FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT for ( final String word : words ) { acquireSharedLock ( ) ; try { if ( apiVersion == 0 ) { doPutV0 ( singleValue , word ) ; } else if ( apiVersion == 1 ) { doPutV1 ( singleValue , word ) ; } else { throw new IllegalStateException ( "Invalid API version, " + apiVersion ) ; } } finally { releaseSharedLock ( ) ; } } return this ; }


Input: Splits passed in key on several words and remove records with keys equals to any item of split result and values equals to passed in value . [CODESPLIT] @ Override public boolean remove ( Object key , final OIdentifiable value ) { if ( key == null ) { return false ; } key = getCollatingValue ( key ) ; final Set < String > words = splitIntoWords ( key . toString ( ) ) ; final OModifiableBoolean removed = new OModifiableBoolean ( false ) ; for ( final String word : words ) { acquireSharedLock ( ) ; try { if ( apiVersion == 0 ) { removeV0 ( value , removed , word ) ; } else if ( apiVersion == 1 ) { removeV1 ( value , removed , word ) ; } else { throw new IllegalStateException ( "Invalid API version, " + apiVersion ) ; } } finally { releaseSharedLock ( ) ; } } return removed . getValue ( ) ; }


Input: Delegates to the OQueryExecutor the query execution . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public List < T > run ( final Object ... iArgs ) { final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; if ( database == null ) throw new OQueryParsingException ( "No database configured" ) ; ( ( OMetadataInternal ) database . getMetadata ( ) ) . makeThreadLocalSchemaSnapshot ( ) ; try { setParameters ( iArgs ) ; Object o = database . getStorage ( ) . command ( this ) ; if ( o instanceof List ) { return ( List < T > ) o ; } else { return ( List < T > ) Collections . singletonList ( o ) ; } } finally { ( ( OMetadataInternal ) database . getMetadata ( ) ) . clearThreadLocalSchemaSnapshot ( ) ; } }


Input: Returns only the first record if any . [CODESPLIT] public T runFirst ( final Object ... iArgs ) { setLimit ( 1 ) ; final List < T > result = execute ( iArgs ) ; return result != null && ! result . isEmpty ( ) ? result . get ( 0 ) : null ; }


Input: Obtains the value stored under the given entry index in this bucket . [CODESPLIT] public OSBTreeValue < V > getValue ( int entryIndex ) { assert isLeaf ; int entryPosition = getIntValue ( entryIndex * OIntegerSerializer . INT_SIZE + positionsArrayOffset ) ; // skip key if ( encryption == null ) { entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedSize = getIntValue ( entryPosition ) ; entryPosition += OIntegerSerializer . INT_SIZE + encryptedSize ; } boolean isLinkValue = getByteValue ( entryPosition ) > 0 ; long link = - 1 ; V value = null ; if ( isLinkValue ) link = deserializeFromDirectMemory ( OLongSerializer . INSTANCE , entryPosition + OByteSerializer . BYTE_SIZE ) ; else value = deserializeFromDirectMemory ( valueSerializer , entryPosition + OByteSerializer . BYTE_SIZE ) ; return new OSBTreeValue <> ( link >= 0 , link , value ) ; }


Input: Shrink the file content ( filledUpTo attribute only ) [CODESPLIT] public void shrink ( final long size ) throws IOException { int attempts = 0 ; while ( true ) { try { acquireWriteLock ( ) ; try { //noinspection resource channel . truncate ( HEADER_SIZE + size ) ; this . size = size ; assert this . size >= 0 ; break ; } finally { releaseWriteLock ( ) ; attempts ++ ; } } catch ( final IOException e ) { OLogManager . instance ( ) . error ( this , "Error during file shrink for file '" + getName ( ) + "' " + attempts + "-th attempt" , e ) ; reopenFile ( attempts , e ) ; } } }


Input: Creates the file . [CODESPLIT] public void create ( ) throws IOException { acquireWriteLock ( ) ; try { acquireExclusiveAccess ( ) ; openChannel ( ) ; init ( ) ; setVersion ( OFileClassic . CURRENT_VERSION ) ; version = OFileClassic . CURRENT_VERSION ; initAllocationMode ( ) ; } finally { releaseWriteLock ( ) ; } }


Input: ALWAYS ADD THE HEADER SIZE BECAUSE ON THIS TYPE IS ALWAYS NEEDED [CODESPLIT] private long checkRegions ( final long iOffset , final long iLength ) { acquireReadLock ( ) ; try { if ( iOffset < 0 || iOffset + iLength > size ) { throw new OIOException ( "You cannot access outside the file size (" + size + " bytes). You have requested portion " + iOffset + "-" + ( iOffset + iLength ) + " bytes. File: " + this ) ; } return iOffset + HEADER_SIZE ; } finally { releaseReadLock ( ) ; } }


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


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


Input: / * ( non - Javadoc ) [CODESPLIT] public void delete ( ) throws IOException { int attempts = 0 ; while ( true ) { try { acquireWriteLock ( ) ; try { close ( ) ; if ( osFile != null ) { Files . deleteIfExists ( osFile ) ; } } finally { releaseWriteLock ( ) ; attempts ++ ; } break ; } catch ( final IOException ioe ) { OLogManager . instance ( ) . error ( this , "Error during deletion of file '" + getName ( ) + "' " + attempts + "-th attempt" , ioe ) ; reopenFile ( attempts , ioe ) ; } } }


Input: Replaces the file content with the content of the provided file . [CODESPLIT] public void replaceContentWith ( final Path newContentFile ) throws IOException { acquireWriteLock ( ) ; try { close ( ) ; Files . copy ( newContentFile , osFile , StandardCopyOption . REPLACE_EXISTING ) ; open ( ) ; } finally { releaseWriteLock ( ) ; } }


Input: Execute the command remotely and get the results back . [CODESPLIT] public Object command ( final OCommandRequestText iCommand ) { final boolean live = iCommand instanceof OLiveQuery ; final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; final boolean asynch = iCommand instanceof OCommandRequestAsynch && ( ( OCommandRequestAsynch ) iCommand ) . isAsynchronous ( ) ; OCommandRequest request = new OCommandRequest ( database , asynch , iCommand , live ) ; OCommandResponse response = networkOperation ( request , "Error on executing command: " + iCommand ) ; return response . getResult ( ) ; }


Input: Ends the request and unlock the write lock [CODESPLIT] public void endRequest ( final OChannelBinaryAsynchClient iNetwork ) throws IOException { if ( iNetwork == null ) return ; iNetwork . flush ( ) ; iNetwork . releaseWriteLock ( ) ; }


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


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


Input: Acquire a network channel from the pool . Don t lock the write stream since the connection usage is exclusive . [CODESPLIT] public OChannelBinaryAsynchClient beginRequest ( final OChannelBinaryAsynchClient network , final byte iCommand , OStorageRemoteSession session ) throws IOException { network . beginRequest ( iCommand , session ) ; return network ; }


Input: { [CODESPLIT] @ Override public void serializeInByteBufferObject ( Short object , ByteBuffer buffer , Object ... hints ) { buffer . putShort ( object ) ; }


Input: { [CODESPLIT] @ Override public Short deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return walChanges . getShortValue ( buffer , offset ) ; }


Input: Gets the current thread database as a ODatabasePojoAbstract wrapping it where necessary . [CODESPLIT] protected static OObjectDatabaseTx getDatabase ( ) { ODatabaseInternal < ? > databaseOwner = ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getDatabaseOwner ( ) ; if ( databaseOwner instanceof OObjectDatabaseTx ) { return ( OObjectDatabaseTx ) databaseOwner ; } else if ( databaseOwner instanceof ODatabaseDocumentInternal ) { return new OObjectDatabaseTx ( ( ODatabaseDocumentInternal ) databaseOwner ) ; } throw new IllegalStateException ( "Current database not of expected type" ) ; }


Input: { @inheritDoc } [CODESPLIT] public String toCreateIndexDDL ( final String indexName , final String indexType , final String engine ) { return createIndexDDLWithFieldType ( indexName , indexType , engine ) . toString ( ) ; }


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


Input: Create a connection . [CODESPLIT] public OClientConnection connect ( final ONetworkProtocol iProtocol ) { final OClientConnection connection ; connection = new OClientConnection ( connectionSerial . incrementAndGet ( ) , iProtocol ) ; connections . put ( connection . getId ( ) , connection ) ; OLogManager . instance ( ) . config ( this , "Remote client connected from: " + connection ) ; OServerPluginHelper . invokeHandlerCallbackOnClientConnection ( iProtocol . getServer ( ) , connection ) ; return connection ; }


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


Input: Retrieves the connection by id . [CODESPLIT] public OClientConnection getConnection ( final int iChannelId , ONetworkProtocol protocol ) { // SEARCH THE CONNECTION BY ID OClientConnection connection = connections . get ( iChannelId ) ; if ( connection != null ) connection . setProtocol ( protocol ) ; return connection ; }


Input: Retrieves the connection by address / port . [CODESPLIT] public OClientConnection getConnection ( final String iAddress ) { for ( OClientConnection conn : connections . values ( ) ) { if ( iAddress . equals ( conn . getRemoteAddress ( ) ) ) return conn ; } return null ; }


Input: Disconnects and kill the associated network manager . [CODESPLIT] public void kill ( final OClientConnection connection ) { if ( connection != null ) { final ONetworkProtocol protocol = connection . getProtocol ( ) ; try { // INTERRUPT THE NEWTORK MANAGER TOO protocol . interrupt ( ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Error during interruption of binary protocol" , e ) ; } disconnect ( connection ) ; // KILL THE NETWORK MANAGER TOO protocol . sendShutdown ( ) ; } }


Input: Interrupt the associated network manager . [CODESPLIT] public void interrupt ( final int iChannelId ) { final OClientConnection connection = connections . get ( iChannelId ) ; if ( connection != null ) { final ONetworkProtocol protocol = connection . getProtocol ( ) ; if ( protocol != null ) // INTERRUPT THE NEWTORK MANAGER protocol . softShutdown ( ) ; } }


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


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


Input: for internal use only [CODESPLIT] public boolean swap ( int index , OIdentifiable newValue ) { EntriesIterator iter = ( EntriesIterator ) rawIterator ( ) ; int currIndex = 0 ; while ( iter . hasNext ( ) ) { iter . next ( ) ; if ( index == currIndex ) { iter . swapValueOnCurrent ( newValue ) ; return true ; } currIndex ++ ; } return false ; }


Input: Closes the transaction and releases all the acquired locks . [CODESPLIT] @ Override public void close ( ) { for ( Map . Entry < ORID , LockedRecordMetadata > lock : locks . entrySet ( ) ) { try { final LockedRecordMetadata lockedRecordMetadata = lock . getValue ( ) ; if ( lockedRecordMetadata . strategy . equals ( OStorage . LOCKING_STRATEGY . EXCLUSIVE_LOCK ) ) { ( ( OAbstractPaginatedStorage ) getDatabase ( ) . getStorage ( ) . getUnderlying ( ) ) . releaseWriteLock ( lock . getKey ( ) ) ; } else if ( lockedRecordMetadata . strategy . equals ( OStorage . LOCKING_STRATEGY . SHARED_LOCK ) ) { ( ( OAbstractPaginatedStorage ) getDatabase ( ) . getStorage ( ) . getUnderlying ( ) ) . releaseReadLock ( lock . getKey ( ) ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . debug ( this , "Error on releasing lock against record " + lock . getKey ( ) , e ) ; } } locks . clear ( ) ; }


Input: handles vertex consistency after an UPDATE EDGE [CODESPLIT] private void handleUpdateEdge ( ODocument record ) { Object currentOut = record . field ( "out" ) ; Object currentIn = record . field ( "in" ) ; Object prevOut = record . getOriginalValue ( "out" ) ; Object prevIn = record . getOriginalValue ( "in" ) ; // to manage subqueries if ( currentOut instanceof Collection && ( ( Collection ) currentOut ) . size ( ) == 1 ) { currentOut = ( ( Collection ) currentOut ) . iterator ( ) . next ( ) ; record . setProperty ( "out" , currentOut ) ; } if ( currentIn instanceof Collection && ( ( Collection ) currentIn ) . size ( ) == 1 ) { currentIn = ( ( Collection ) currentIn ) . iterator ( ) . next ( ) ; record . setProperty ( "in" , currentIn ) ; } validateOutInForEdge ( record , currentOut , currentIn ) ; changeVertexEdgePointer ( record , ( OIdentifiable ) prevIn , ( OIdentifiable ) currentIn , "in" ) ; changeVertexEdgePointer ( record , ( OIdentifiable ) prevOut , ( OIdentifiable ) currentOut , "out" ) ; }


Input: updates old and new vertices connected to an edge after out / in update on the edge itself [CODESPLIT] private void changeVertexEdgePointer ( ODocument edge , OIdentifiable prevVertex , OIdentifiable currentVertex , String direction ) { if ( prevVertex != null && ! prevVertex . equals ( currentVertex ) ) { String edgeClassName = edge . getClassName ( ) ; if ( edgeClassName . equalsIgnoreCase ( "E" ) ) { edgeClassName = "" ; } String vertexFieldName = direction + "_" + edgeClassName ; ODocument prevOutDoc = ( ( OIdentifiable ) prevVertex ) . getRecord ( ) ; ORidBag prevBag = prevOutDoc . field ( vertexFieldName ) ; if ( prevBag != null ) { prevBag . remove ( edge ) ; prevOutDoc . save ( ) ; } ODocument currentVertexDoc = ( ( OIdentifiable ) currentVertex ) . getRecord ( ) ; ORidBag currentBag = currentVertexDoc . field ( vertexFieldName ) ; if ( currentBag == null ) { currentBag = new ORidBag ( ) ; currentVertexDoc . field ( vertexFieldName , currentBag ) ; } currentBag . add ( edge ) ; } }


Input: checks if an object is an OIdentifiable and an instance of a particular ( schema ) class [CODESPLIT] private boolean isRecordInstanceOf ( Object iRecord , String orientClass ) { if ( iRecord == null ) { return false ; } if ( ! ( iRecord instanceof OIdentifiable ) ) { return false ; } ODocument record = ( ( OIdentifiable ) iRecord ) . getRecord ( ) ; if ( iRecord == null ) { return false ; } return ( record . getSchemaClass ( ) . isSubClassOf ( orientClass ) ) ; }


Input: { [CODESPLIT] @ Override public void serializeInByteBufferObject ( Character object , ByteBuffer buffer , Object ... hints ) { buffer . putChar ( object ) ; }


Input: Scans all classes accessible from the context class loader which belong to the given package and subpackages . [CODESPLIT] public synchronized void generateSchema ( final String iPackageName , final ClassLoader iClassLoader ) { OLogManager . instance ( ) . debug ( this , "Generating schema inside package: %s" , iPackageName ) ; List < Class < ? > > classes = null ; try { classes = OReflectionHelper . getClassesFor ( iPackageName , iClassLoader ) ; } catch ( ClassNotFoundException e ) { throw OException . wrapException ( new ODatabaseException ( "Classes cannot be loaded during schema generation" ) , e ) ; } for ( Class < ? > c : classes ) { generateSchema ( c ) ; } }


Input: Generate / updates the SchemaClass and properties from given Class<? > . [CODESPLIT] public synchronized void generateSchema ( final Class < ? > iClass , ODatabaseDocument database ) { if ( iClass == null || iClass . isInterface ( ) || iClass . isPrimitive ( ) || iClass . isEnum ( ) || iClass . isAnonymousClass ( ) ) return ; OObjectEntitySerializer . registerClass ( iClass ) ; OClass schema = database . getMetadata ( ) . getSchema ( ) . getClass ( iClass ) ; if ( schema == null ) { generateOClass ( iClass , database ) ; } List < String > fields = OObjectEntitySerializer . getClassFields ( iClass ) ; if ( fields != null ) for ( String field : fields ) { if ( schema . existsProperty ( field ) ) continue ; if ( OObjectEntitySerializer . isVersionField ( iClass , field ) || OObjectEntitySerializer . isIdField ( iClass , field ) ) continue ; Field f = OObjectEntitySerializer . getField ( field , iClass ) ; if ( f . getType ( ) . equals ( Object . class ) || f . getType ( ) . equals ( ODocument . class ) || OBlob . class . isAssignableFrom ( f . getType ( ) ) ) { continue ; } OType t = OObjectEntitySerializer . getTypeByClass ( iClass , field , f ) ; if ( t == OType . CUSTOM ) { OEntityManager entityManager = OEntityManager . getEntityManagerByDatabaseURL ( database . getURL ( ) ) ; // if the target type is registered as entity, it should be linked instead of custom/serialized if ( entityManager . getEntityClass ( f . getType ( ) . getSimpleName ( ) ) != null ) { t = OType . LINK ; } } if ( t == null ) { if ( f . getType ( ) . isEnum ( ) ) t = OType . STRING ; else { t = OType . LINK ; } } switch ( t ) { case LINK : Class < ? > linkedClazz = OObjectEntitySerializer . getSpecifiedLinkedType ( f ) ; if ( linkedClazz == null ) linkedClazz = f . getType ( ) ; generateLinkProperty ( database , schema , field , t , linkedClazz ) ; break ; case LINKLIST : case LINKMAP : case LINKSET : linkedClazz = OObjectEntitySerializer . getSpecifiedMultiLinkedType ( f ) ; if ( linkedClazz == null ) linkedClazz = OReflectionHelper . getGenericMultivalueType ( f ) ; if ( linkedClazz != null ) generateLinkProperty ( database , schema , field , t , linkedClazz ) ; break ; case EMBEDDED : linkedClazz = f . getType ( ) ; if ( linkedClazz == null || linkedClazz . equals ( Object . class ) || linkedClazz . equals ( ODocument . class ) || OBlob . class . isAssignableFrom ( f . getType ( ) ) ) { continue ; } else { generateLinkProperty ( database , schema , field , t , linkedClazz ) ; } break ; case EMBEDDEDLIST : case EMBEDDEDSET : case EMBEDDEDMAP : linkedClazz = OReflectionHelper . getGenericMultivalueType ( f ) ; if ( linkedClazz == null || linkedClazz . equals ( Object . class ) || linkedClazz . equals ( ODocument . class ) || OBlob . class . isAssignableFrom ( f . getType ( ) ) ) { continue ; } else { if ( OReflectionHelper . isJavaType ( linkedClazz ) ) { schema . createProperty ( field , t , OType . getTypeByClass ( linkedClazz ) ) ; } else if ( linkedClazz . isEnum ( ) ) { schema . createProperty ( field , t , OType . STRING ) ; } else { generateLinkProperty ( database , schema , field , t , linkedClazz ) ; } } break ; default : schema . createProperty ( field , t ) ; break ; } } }


Input: Checks if all registered entities has schema generated if not it generates it [CODESPLIT] public synchronized void synchronizeSchema ( ) { OObjectDatabaseTx database = ( ( OObjectDatabaseTx ) ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getDatabaseOwner ( ) ) ; Collection < Class < ? > > registeredEntities = database . getEntityManager ( ) . getRegisteredEntities ( ) ; boolean automaticSchemaGeneration = database . isAutomaticSchemaGeneration ( ) ; boolean reloadSchema = false ; for ( Class < ? > iClass : registeredEntities ) { if ( Proxy . class . isAssignableFrom ( iClass ) || iClass . isEnum ( ) || OReflectionHelper . isJavaType ( iClass ) || iClass . isAnonymousClass ( ) ) return ; if ( ! database . getMetadata ( ) . getSchema ( ) . existsClass ( iClass . getSimpleName ( ) ) ) { database . getMetadata ( ) . getSchema ( ) . createClass ( iClass . getSimpleName ( ) ) ; reloadSchema = true ; } for ( Class < ? > currentClass = iClass ; currentClass != Object . class ; ) { if ( automaticSchemaGeneration && ! currentClass . equals ( Object . class ) && ! currentClass . equals ( ODocument . class ) ) { ( ( OSchemaProxyObject ) database . getMetadata ( ) . getSchema ( ) ) . generateSchema ( currentClass , database . getUnderlying ( ) ) ; } String iClassName = currentClass . getSimpleName ( ) ; currentClass = currentClass . getSuperclass ( ) ; if ( currentClass == null || currentClass . equals ( ODocument . class ) ) // POJO EXTENDS ODOCUMENT: SPECIAL CASE: AVOID TO CONSIDER // ODOCUMENT FIELDS currentClass = Object . class ; if ( database != null && ! database . isClosed ( ) && ! currentClass . equals ( Object . class ) ) { OClass oSuperClass ; OClass currentOClass = database . getMetadata ( ) . getSchema ( ) . getClass ( iClassName ) ; if ( ! database . getMetadata ( ) . getSchema ( ) . existsClass ( currentClass . getSimpleName ( ) ) ) { oSuperClass = database . getMetadata ( ) . getSchema ( ) . createClass ( currentClass . getSimpleName ( ) ) ; reloadSchema = true ; } else { oSuperClass = database . getMetadata ( ) . getSchema ( ) . getClass ( currentClass . getSimpleName ( ) ) ; reloadSchema = true ; } if ( ! currentOClass . getSuperClasses ( ) . contains ( oSuperClass ) ) { currentOClass . setSuperClasses ( Arrays . asList ( oSuperClass ) ) ; reloadSchema = true ; } } } } if ( database != null && ! database . isClosed ( ) && reloadSchema ) { database . getMetadata ( ) . getSchema ( ) . reload ( ) ; } }


Input: Updates the metric metadata . [CODESPLIT] protected void updateMetadata ( final String iName , final String iDescription , final METRIC_TYPE iType ) { if ( iDescription != null && dictionary . putIfAbsent ( iName , iDescription ) == null ) types . put ( iName , iType ) ; }


Input:
Return the element at the current position and move forward the cursor to the next position available . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public REC next ( ) { checkDirection ( true ) ; if ( currentRecord != null ) try { // RETURN LAST LOADED RECORD
 return ( REC ) currentRecord ; } finally { currentRecord = null ; } ORecord record ; // MOVE FORWARD IN THE CURRENT CLUSTER
 while ( hasNext ( ) ) { if ( currentRecord != null ) try { // RETURN LAST LOADED RECORD
 return ( REC ) currentRecord ; } finally { currentRecord = null ; } record = getTransactionEntry ( ) ; if ( record == null ) record = readCurrentRecord ( null , + 1 ) ; if ( record != null ) // FOUND
 if ( include ( record ) ) return ( REC ) record ; } record = getTransactionEntry ( ) ; if ( record != null ) return ( REC ) record ; throw new NoSuchElementException ( "Direction: forward, last position was: " + current + ", range: " + beginRange + "-" + endRange ) ; }


Input:
Return the element at the current position and move backward the cursor to the previous position available . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) @ Override public REC previous ( ) { checkDirection ( false ) ; if ( currentRecord != null ) try { // RETURN LAST LOADED RECORD
 return ( REC ) currentRecord ; } finally { currentRecord = null ; } ORecord record = getRecord ( ) ; // MOVE BACKWARD IN THE CURRENT CLUSTER
 while ( hasPrevious ( ) ) { if ( currentRecord != null ) try { // RETURN LAST LOADED RECORD
 return ( REC ) currentRecord ; } finally { currentRecord = null ; } record = getTransactionEntry ( ) ; if ( record == null ) record = readCurrentRecord ( null , - 1 ) ; if ( record != null ) // FOUND
 if ( include ( record ) ) return ( REC ) record ; } record = getTransactionEntry ( ) ; if ( record != null ) return ( REC ) record ; return null ; }


Input: Move the iterator to the begin of the range . If no range was specified move to the first record of the cluster . [CODESPLIT] @ Override public ORecordIteratorClusters < REC > begin ( ) { if ( clusterIds . length == 0 ) return this ; browsedRecords = 0 ; currentClusterIdx = 0 ; current . setClusterId ( clusterIds [ currentClusterIdx ] ) ; updateClusterRange ( ) ; resetCurrentPosition ( ) ; nextPosition ( ) ; final ORecord record = getRecord ( ) ; currentRecord = readCurrentRecord ( record , 0 ) ; if ( currentRecord != null && ! include ( currentRecord ) ) { currentRecord = null ; hasNext ( ) ; } return this ; }


Input: Move the iterator to the end of the range . If no range was specified move to the last record of the cluster . [CODESPLIT] @ Override public ORecordIteratorClusters < REC > last ( ) { if ( clusterIds . length == 0 ) return this ; browsedRecords = 0 ; currentClusterIdx = clusterIds . length - 1 ; updateClusterRange ( ) ; current . setClusterId ( clusterIds [ currentClusterIdx ] ) ; resetCurrentPosition ( ) ; prevPosition ( ) ; final ORecord record = getRecord ( ) ; currentRecord = readCurrentRecord ( record , 0 ) ; if ( currentRecord != null && ! include ( currentRecord ) ) { currentRecord = null ; hasPrevious ( ) ; } return this ; }


Input: Tell to the iterator that the upper limit must be checked at every cycle . Useful when concurrent deletes or additions change the size of the cluster while you re browsing it . Default is false . [CODESPLIT] @ Override public ORecordIteratorClusters < REC > setLiveUpdated ( boolean iLiveUpdated ) { super . setLiveUpdated ( iLiveUpdated ) ; if ( iLiveUpdated ) { firstClusterEntry = 0 ; lastClusterEntry = Long . MAX_VALUE ; } else { updateClusterRange ( ) ; } return this ; }


Input:
Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clazz == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; return OGraphCommandExecutorSQLFactory . runInConfiguredTxMode ( new OGraphCommandExecutorSQLFactory . GraphCallBack < List < Object > > ( ) { @ Override public List < Object > call ( OrientBaseGraph graph ) { final Set < OIdentifiable > fromIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( graph . getRawGraph ( ) , from , context , iArgs ) ; final Set < OIdentifiable > toIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( graph . getRawGraph ( ) , to , context , iArgs ) ; // CREATE EDGES
 final List < Object > edges = new ArrayList < Object > ( ) ; for ( OIdentifiable from : fromIds ) { final OrientVertex fromVertex = graph . getVertex ( from ) ; if ( fromVertex == null ) throw new OCommandExecutionException ( "Source vertex '" + from + "' not exists" ) ; for ( OIdentifiable to : toIds ) { final OrientVertex toVertex ; if ( from . equals ( to ) ) { toVertex = fromVertex ; } else { toVertex = graph . getVertex ( to ) ; } if ( fields != null ) // EVALUATE FIELDS
 for ( final OPair < String , Object > f : fields ) { if ( f . getValue ( ) instanceof OSQLFunctionRuntime ) { f . setValue ( ( ( OSQLFunctionRuntime ) f . getValue ( ) ) . getValue ( to , null , context ) ) ; } else if ( f . getValue ( ) instanceof OSQLFilterItem ) { f . setValue ( ( ( OSQLFilterItem ) f . getValue ( ) ) . getValue ( to , null , context ) ) ; } } OrientEdge edge = null ; if ( content != null ) { if ( fields != null ) // MERGE CONTENT WITH FIELDS
 fields . addAll ( OPair . convertFromMap ( content . toMap ( ) ) ) ; else fields = OPair . convertFromMap ( content . toMap ( ) ) ; } edge = fromVertex . addEdge ( null , toVertex , edgeLabel , clusterName , fields ) ; if ( fields != null && ! fields . isEmpty ( ) ) { if ( edge . isLightweight ( ) ) edge . convertToDocument ( ) ; OSQLHelper . bindParameters ( edge . getRecord ( ) , fields , new OCommandParameters ( iArgs ) , context ) ; } edge . save ( clusterName ) ; edges . add ( edge ) ; if ( batch > 0 && edges . size ( ) % batch == 0 ) { graph . commit ( ) ; graph . begin ( ) ; } } } if ( edges . isEmpty ( ) ) { if ( fromIds . isEmpty ( ) ) throw new OCommandExecutionException ( "No edge has been created because no source vertices" ) ; else if ( toIds . isEmpty ( ) ) throw new OCommandExecutionException ( "No edge has been created because no target vertices" ) ; throw new OCommandExecutionException ( "No edge has been created between " + fromIds + " and " + toIds ) ; } return edges ; } } ) ; }


Input:
Returns the next character from the input stream . Handles Unicode decoding . [CODESPLIT] public int nextChar ( ) throws IOException { if ( missedChar != null ) { // RETURNS THE PREVIOUS PARSED CHAR
 c = missedChar . charValue ( ) ; missedChar = null ; } else { int read = in . read ( ) ; if ( read == - 1 ) return - 1 ; c = ( char ) read ; if ( c == ' ' ) { read = in . read ( ) ; if ( read == - 1 ) return - 1 ; char c2 = ( char ) read ; if ( c2 == ' ' ) { // DECODE UNICODE CHAR
 final StringBuilder buff = new StringBuilder ( 8 ) ; for ( int i = 0 ; i < 4 ; ++ i ) { read = in . read ( ) ; if ( read == - 1 ) return - 1 ; buff . append ( ( char ) read ) ; } cursor += 6 ; return ( char ) Integer . parseInt ( buff . toString ( ) , 16 ) ; } else { // REMEMBER THE CURRENT CHAR TO RETURN NEXT TIME
 missedChar = c2 ; } } } cursor ++ ; if ( c == NEW_LINE ) { ++ lineNumber ; columnNumber = 0 ; } else ++ columnNumber ; return ( char ) c ; }


Input: Execute the FIND REFERENCES . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( recordIds . isEmpty ( ) && subQuery == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; if ( subQuery != null ) { final List < OIdentifiable > result = new OCommandSQL ( subQuery . toString ( ) ) . execute ( ) ; for ( OIdentifiable id : result ) recordIds . ( id . getIdentity ( ) ) ; } return OFindReferenceHelper . findReferences ( recordIds , classList ) ; }


Input: Legacy Protocol < 37 [CODESPLIT] private static OBinaryRequest < ? extends OBinaryResponse > createRequest ( int requestType ) { switch ( requestType ) { case OChannelBinaryProtocol . REQUEST_DB_OPEN : return new OOpenRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONNECT : return new OConnectRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_REOPEN : return new OReopenRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SHUTDOWN : return new OShutdownRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_LIST : return new OListDatabasesRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SERVER_INFO : return new OServerInfoRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_RELOAD : return new OReloadRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_CREATE : return new OCreateDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_CLOSE : return new OCloseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_EXIST : return new OExistsDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_DROP : return new ODropDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_SIZE : return new OGetSizeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_COUNTRECORDS : return new OCountRecordsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER : return new ODistributedStatusRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_COUNT : return new OCountRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_DATARANGE : return new OGetClusterDataRangeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_ADD : return new OAddClusterRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_DROP : return new ODropClusterRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_METADATA : return new OGetRecordMetadataRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_LOAD : return new OReadRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_LOAD_IF_VERSION_NOT_LATEST : return new OReadRecordIfVersionIsNotLatestRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_CREATE : return new OCreateRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_UPDATE : return new OUpdateRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_DELETE : return new ODeleteRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_HIDE : return new OHideRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_HIGHER : return new OHigherPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_CEILING : return new OCeilingPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_LOWER : return new OLowerPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_FLOOR : return new OFloorPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_COMMAND : return new OCommandRequest ( ) ; case OChannelBinaryProtocol . REQUEST_QUERY : return new OQueryRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLOSE_QUERY : return new OCloseQueryRequest ( ) ; case OChannelBinaryProtocol . REQUEST_QUERY_NEXT_PAGE : return new OQueryNextPageRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_COMMIT : return new OCommitRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_GET : return new OGetGlobalConfigurationRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_SET : return new OSetGlobalConfigurationRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_LIST : return new OListGlobalConfigurationsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_FREEZE : return new OFreezeDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_RELEASE : return new OReleaseDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_CLEAN_OUT : return new OCleanOutRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CREATE_SBTREE_BONSAI : return new OSBTCreateTreeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_GET : return new OSBTGetRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_FIRST_KEY : return new OSBTFirstKeyRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_GET_ENTRIES_MAJOR : return new OSBTFetchEntriesMajorRequest <> ( ) ; case OChannelBinaryProtocol . REQUEST_RIDBAG_GET_SIZE : return new OSBTGetRealBagSizeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_INCREMENTAL_BACKUP : return new OIncrementalBackupRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_IMPORT : return new OImportRequest ( ) ; case OChannelBinaryProtocol . DISTRIBUTED_CONNECT : return new ODistributedConnectRequest ( ) ; default : throw new ODatabaseException ( "binary protocol command with code: " + requestType ) ; } }


Input: Protocol 37 [CODESPLIT] public static OBinaryRequest < ? extends OBinaryResponse > createRequest37 ( int requestType ) { switch ( requestType ) { case OChannelBinaryProtocol . SUBSCRIBE_PUSH : return new OSubscribeRequest ( ) ; case OChannelBinaryProtocol . EXPERIMENTAL : return new OExperimentalRequest ( ) ; case OChannelBinaryProtocol . UNSUBSCRIBE_PUSH : return new OUnsubscribeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_FETCH : return new OFetchTransactionRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_REBEGIN : return new ORebeginTransactionRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_BEGIN : return new OBeginTransactionRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_COMMIT : return new OCommit37Request ( ) ; case OChannelBinaryProtocol . REQUEST_TX_ROLLBACK : return new ORollbackTransactionRequest ( ) ; case OChannelBinaryProtocol . REQUEST_BATCH_OPERATIONS : return new OBatchOperationsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_OPEN : return new OOpen37Request ( ) ; case OChannelBinaryProtocol . REQUEST_CONNECT : return new OConnect37Request ( ) ; case OChannelBinaryProtocol . REQUEST_DB_REOPEN : return new OReopenRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SHUTDOWN : return new OShutdownRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_LIST : return new OListDatabasesRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SERVER_INFO : return new OServerInfoRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_RELOAD : return new OReloadRequest37 ( ) ; case OChannelBinaryProtocol . REQUEST_DB_CREATE : return new OCreateDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_CLOSE : return new OCloseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_EXIST : return new OExistsDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_DROP : return new ODropDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_SIZE : return new OGetSizeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_COUNTRECORDS : return new OCountRecordsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER : return new ODistributedStatusRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_COUNT : return new OCountRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_DATARANGE : return new OGetClusterDataRangeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_ADD : return new OAddClusterRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_DROP : return new ODropClusterRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_METADATA : return new OGetRecordMetadataRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_LOAD : return new OReadRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_LOAD_IF_VERSION_NOT_LATEST : return new OReadRecordIfVersionIsNotLatestRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_CREATE : return new OCreateRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_UPDATE : return new OUpdateRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_DELETE : return new ODeleteRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_HIDE : return new OHideRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_HIGHER : return new OHigherPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_CEILING : return new OCeilingPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_LOWER : return new OLowerPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_FLOOR : return new OFloorPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_COMMAND : return new OCommandRequest ( ) ; case OChannelBinaryProtocol . REQUEST_QUERY : return new OQueryRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLOSE_QUERY : return new OCloseQueryRequest ( ) ; case OChannelBinaryProtocol . REQUEST_QUERY_NEXT_PAGE : return new OQueryNextPageRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_GET : return new OGetGlobalConfigurationRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_SET : return new OSetGlobalConfigurationRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_LIST : return new OListGlobalConfigurationsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_FREEZE : return new OFreezeDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_RELEASE : return new OReleaseDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_CLEAN_OUT : return new OCleanOutRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CREATE_SBTREE_BONSAI : return new OSBTCreateTreeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_GET : return new OSBTGetRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_FIRST_KEY : return new OSBTFirstKeyRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_GET_ENTRIES_MAJOR : return new OSBTFetchEntriesMajorRequest <> ( ) ; case OChannelBinaryProtocol . REQUEST_RIDBAG_GET_SIZE : return new OSBTGetRealBagSizeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_INCREMENTAL_BACKUP : return new OIncrementalBackupRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_IMPORT : return new OImportRequest ( ) ; case OChannelBinaryProtocol . DISTRIBUTED_CONNECT : return new ODistributedConnectRequest ( ) ; default : throw new ODatabaseException ( "binary protocol command with code: " + requestType + " for protocol version 37" ) ; } }


Input: Convert fields from text to real value . Supports : String RID Boolean Float Integer and NULL . [CODESPLIT] public static Object parseValue ( String iValue , final OCommandContext iContext ) { return parseValue ( iValue , iContext , false ) ; }


Input: Defines a callback to call in case of error during the asynchronous replication . [CODESPLIT] @ Override public OCommandRequestAbstract onAsyncReplicationError ( final OAsyncReplicationError iCallback ) { if ( iCallback != null ) { onAsyncReplicationError = new OAsyncReplicationError ( ) { int retry = 0 ; @ Override public ACTION onAsyncReplicationError ( Throwable iException , final int iRetry ) { switch ( iCallback . onAsyncReplicationError ( iException , ++ retry ) ) { case RETRY : execute ( ) ; break ; case IGNORE : } return ACTION . IGNORE ; } } ; } else onAsyncReplicationError = null ; return this ; }


Input: Registers a stateless implementations the same instance will be shared on all the storages . [CODESPLIT] public void register ( final Class < ? extends OCompression > compression ) { try { final OCompression tempInstance = compression . newInstance ( ) ; final String name = tempInstance . name ( ) ; if ( compressions . containsKey ( name ) ) throw new IllegalArgumentException ( "Compression with name '" + name + "' was already registered" ) ; if ( compressionClasses . containsKey ( tempInstance . name ( ) ) ) throw new IllegalArgumentException ( "Compression with name '" + name + "' was already registered" ) ; compressionClasses . put ( name , compression ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Cannot register storage compression algorithm '%s'" , e , compression ) ; } }


Input: Detects limit of limit of open files . [CODESPLIT] public int getOpenFilesLimit ( boolean verbose , int recommended , int defLimit ) { if ( Platform . isLinux ( ) ) { final OCLibrary . Rlimit rlimit = new OCLibrary . Rlimit ( ) ; final int result = C_LIBRARY . getrlimit ( OCLibrary . RLIMIT_NOFILE , rlimit ) ; if ( result == 0 && rlimit . rlim_cur > 0 ) { if ( verbose ) { OLogManager . instance ( ) . infoNoDb ( this , "Detected limit of amount of simultaneously open files is %d, " + " limit of open files for disk cache will be set to %d" , rlimit . rlim_cur , rlimit . rlim_cur / 2 - 512 ) ; } if ( rlimit . rlim_cur < recommended ) { OLogManager . instance ( ) . warnNoDb ( this , "Value of limit of simultaneously open files is too small, recommended value is %d" , recommended ) ; } return ( int ) rlimit . rlim_cur / 2 - 512 ; } else { if ( verbose ) { OLogManager . instance ( ) . infoNoDb ( this , "Can not detect value of limit of open files." ) ; } } } else if ( Platform . isWindows ( ) ) { if ( verbose ) { OLogManager . instance ( ) . infoNoDb ( this , "Windows OS is detected, %d limit of open files will be set for the disk cache." , recommended ) ; } return recommended ; } if ( verbose ) { OLogManager . instance ( ) . infoNoDb ( this , "Default limit of open files (%d) will be used." , defLimit ) ; } return defLimit ; }


Input: @param printSteps Print all steps of discovering of memory limit in the log with { @code INFO } level . [CODESPLIT] public MemoryLimitResult getMemoryLimit ( final boolean printSteps ) { //Perform several steps here: //1. Fetch physical size available on machine //2. Fetch soft limit //3. Fetch cgroup soft limit //4. Fetch cgroup hard limit //5. Return the minimal value from the list of results long memoryLimit = getPhysicalMemorySize ( ) ; boolean insideContainer = false ; if ( printSteps ) { OLogManager . instance ( ) . infoNoDb ( this , "%d B/%d MB/%d GB of physical memory were detected on machine" , memoryLimit , convertToMB ( memoryLimit ) , convertToGB ( memoryLimit ) ) ; } if ( Platform . isLinux ( ) ) { final OCLibrary . Rlimit rlimit = new OCLibrary . Rlimit ( ) ; final int result = C_LIBRARY . getrlimit ( OCLibrary . RLIMIT_AS , rlimit ) ; //no errors during the call if ( result == 0 ) { if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , "Soft memory limit for this process is set to %d B/%d MB/%d GB" , rlimit . rlim_cur , convertToMB ( rlimit . rlim_cur ) , convertToGB ( rlimit . rlim_cur ) ) ; memoryLimit = updateMemoryLimit ( memoryLimit , rlimit . rlim_cur ) ; if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , "Hard memory limit for this process is set to %d B/%d MB/%d GB" , rlimit . rlim_max , convertToMB ( rlimit . rlim_max ) , convertToGB ( rlimit . rlim_max ) ) ; memoryLimit = updateMemoryLimit ( memoryLimit , rlimit . rlim_max ) ; } final String memoryCGroupPath = findMemoryGCGroupPath ( ) ; if ( memoryCGroupPath != null ) { if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , "Path to 'memory' cgroup is '%s'" , memoryCGroupPath ) ; final String memoryCGroupRoot = findMemoryGCRoot ( ) ; if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , "Mounting path for memory cgroup controller is '%s'" , memoryCGroupRoot ) ; File memoryCGroup = new File ( memoryCGroupRoot , memoryCGroupPath ) ; if ( ! memoryCGroup . exists ( ) ) { if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , "Can not find '%s' path for memory cgroup, it is supposed that " + "process is running in container, will try to read root '%s' memory cgroup data" , memoryCGroup , memoryCGroupRoot ) ; memoryCGroup = new File ( memoryCGroupRoot ) ; insideContainer = true ; } final long softMemoryLimit = fetchCGroupSoftMemoryLimit ( memoryCGroup , printSteps ) ; memoryLimit = updateMemoryLimit ( memoryLimit , softMemoryLimit ) ; final long hardMemoryLimit = fetchCGroupHardMemoryLimit ( memoryCGroup , printSteps ) ; memoryLimit = updateMemoryLimit ( memoryLimit , hardMemoryLimit ) ; } } if ( printSteps ) { if ( memoryLimit > 0 ) OLogManager . instance ( ) . infoNoDb ( this , "Detected memory limit for current process is %d B/%d MB/%d GB" , memoryLimit , convertToMB ( memoryLimit ) , convertToGB ( memoryLimit ) ) ; else OLogManager . instance ( ) . infoNoDb ( this , "Memory limit for current process is not set" ) ; } if ( memoryLimit <= 0 ) return null ; return new MemoryLimitResult ( memoryLimit , insideContainer ) ; }


Input: Obtains the total size in bytes of the installed physical memory on this machine . Note that on some VMs it s impossible to obtain the physical memory size in this case the return value will { @code - 1 } . [CODESPLIT] private long getPhysicalMemorySize ( ) { long osMemory = - 1 ; try { final MBeanServer mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; final Object attribute = mBeanServer . getAttribute ( new ObjectName ( "java.lang" , "type" , "OperatingSystem" ) , "TotalPhysicalMemorySize" ) ; if ( attribute != null ) { if ( attribute instanceof Long ) { osMemory = ( Long ) attribute ; } else { try { osMemory = Long . parseLong ( attribute . toString ( ) ) ; } catch ( final NumberFormatException e ) { if ( ! OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . warnNoDb ( OMemory . class , "Unable to determine the amount of installed RAM." ) ; else OLogManager . instance ( ) . debugNoDb ( OMemory . class , "Unable to determine the amount of installed RAM." , e ) ; } } } else { if ( ! OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . warnNoDb ( OMemory . class , "Unable to determine the amount of installed RAM." ) ; } } catch ( MalformedObjectNameException | AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException e ) { if ( ! OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . warnNoDb ( OMemory . class , "Unable to determine the amount of installed RAM." ) ; else OLogManager . instance ( ) . debugNoDb ( OMemory . class , "Unable to determine the amount of installed RAM." , e ) ; } catch ( final RuntimeException e ) { OLogManager . instance ( ) . warnNoDb ( OMemory . class , "Unable to determine the amount of installed RAM." , e ) ; } return osMemory ; }


Input: tests if current expression is an indexed function AND that function can be used on this target [CODESPLIT] public boolean allowsIndexedFunctionExecutionOnTarget ( OFromClause target , OCommandContext context , OBinaryCompareOperator operator , Object right ) { if ( this . childExpressions . size ( ) != 1 ) { return false ; } return this . childExpressions . get ( 0 ) . allowsIndexedFunctionExecutionOnTarget ( target , context , operator , right ) ; }


Input:
Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clazz == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; // CREATE VERTEX DOES NOT HAVE TO BE IN TX
 return OGraphCommandExecutorSQLFactory . runWithAnyGraph ( new OGraphCommandExecutorSQLFactory . GraphCallBack < Object > ( ) { @ Override public Object call ( final OrientBaseGraph graph ) { final OrientVertex vertex = graph . addTemporaryVertex ( clazz . getName ( ) ) ; if ( fields != null ) // EVALUATE FIELDS
 for ( final OPair < String , Object > f : fields ) { if ( f . getValue ( ) instanceof OSQLFunctionRuntime ) f . setValue ( ( ( OSQLFunctionRuntime ) f . getValue ( ) ) . getValue ( vertex . getRecord ( ) , null , context ) ) ; } OSQLHelper . bindParameters ( vertex . getRecord ( ) , fields , new OCommandParameters ( iArgs ) , context ) ; if ( content != null ) vertex . getRecord ( ) . merge ( content , true , false ) ; if ( clusterName != null ) vertex . save ( clusterName ) ; else vertex . save ( ) ; return vertex . getRecord ( ) ; } } ) ; }


Input: } [CODESPLIT] public static void writeOType ( BytesContainer bytes , int pos , OType type ) { bytes . bytes [ pos ] = ( byte ) type . getId ( ) ; }


Input: Move bytes left or right of an offset . [CODESPLIT] public void move ( final int iFrom , final int iPosition ) { if ( iPosition == 0 ) return ; final int to = iFrom + iPosition ; final int size = iPosition > 0 ? buffer . length - to : buffer . length - iFrom ; System . arraycopy ( buffer , iFrom , buffer , to , size ) ; }


Input:
Returns the used buffer as byte [] . [CODESPLIT] public final byte [ ] toByteArray ( ) { if ( position == buffer . length - 1 ) // 100% USED, RETURN THE FULL BUFFER
 return buffer ; final int pos = position ; final byte [ ] destinBuffer = new byte [ pos ] ; final byte [ ] sourceBuffer = buffer ; if ( pos < NATIVE_COPY_THRESHOLD ) for ( int i = 0 ; i < pos ; ++ i ) destinBuffer [ i ] = sourceBuffer [ i ] ; else System . arraycopy ( sourceBuffer , 0 , destinBuffer , 0 , pos ) ; return destinBuffer ; }


Input: Append byte [] to the stream . [CODESPLIT] public int set ( final byte [ ] iContent ) { if ( iContent == null ) return - 1 ; final int begin = position ; assureSpaceFor ( OBinaryProtocol . SIZE_INT + iContent . length ) ; OBinaryProtocol . int2bytes ( iContent . length , buffer , position ) ; position += OBinaryProtocol . SIZE_INT ; write ( iContent , 0 , iContent . length ) ; return begin ; }


Input: Fills the stream from current position writing iLength times the iFiller byte [CODESPLIT] public void fill ( final int iLength , final byte iFiller ) { assureSpaceFor ( iLength ) ; Arrays . fill ( buffer , position , position + iLength , iFiller ) ; position += iLength ; }


Input: executes all the script and returns last statement execution step so that it can be executed from outside [CODESPLIT] public OExecutionStepInternal executeUntilReturn ( ) { if ( steps . size ( ) > 0 ) { lastStep = steps . get ( steps . size ( ) - 1 ) ; } for ( int i = 0 ; i < steps . size ( ) - 1 ; i ++ ) { ScriptLineStep step = steps . get ( i ) ; if ( step . containsReturn ( ) ) { OExecutionStepInternal returnStep = step . executeUntilReturn ( ctx ) ; if ( returnStep != null ) { lastStep = returnStep ; return lastStep ; } } OResultSet lastResult = step . syncPull ( ctx , 100 ) ; while ( lastResult . hasNext ( ) ) { while ( lastResult . hasNext ( ) ) { lastResult . next ( ) ; } lastResult = step . syncPull ( ctx , 100 ) ; } } this . lastStep = steps . get ( steps . size ( ) - 1 ) ; return lastStep ; }


Input: executes the whole script and returns last statement ONLY if it s a RETURN otherwise it returns null ; [CODESPLIT] public OExecutionStepInternal executeFull ( ) { for ( int i = 0 ; i < steps . size ( ) ; i ++ ) { ScriptLineStep step = steps . get ( i ) ; if ( step . containsReturn ( ) ) { OExecutionStepInternal returnStep = step . executeUntilReturn ( ctx ) ; if ( returnStep != null ) { return returnStep ; } } OResultSet lastResult = step . syncPull ( ctx , 100 ) ; while ( lastResult . hasNext ( ) ) { while ( lastResult . hasNext ( ) ) { lastResult . next ( ) ; } lastResult = step . syncPull ( ctx , 100 ) ; } } return null ; }


Input:
Serialize the user POJO to a ORecordDocument instance . [CODESPLIT] public static ODocument toStream ( final Object iPojo , final ODocument iRecord , final OEntityManager iEntityManager , final OClass schemaClass , final OUserObject2RecordHandler iObj2RecHandler , final ODatabaseObject db , final boolean iSaveOnlyDirty ) { if ( iSaveOnlyDirty && ! iRecord . isDirty ( ) ) return iRecord ; final long timer = Orient . instance ( ) . getProfiler ( ) . startChrono ( ) ; final Integer identityRecord = System . identityHashCode ( iRecord ) ; if ( OSerializationThreadLocal . INSTANCE . get ( ) . contains ( identityRecord ) ) return iRecord ; OSerializationThreadLocal . INSTANCE . get ( ) . add ( identityRecord ) ; OProperty schemaProperty ; final Class < ? > pojoClass = iPojo . getClass ( ) ; final List < Field > properties = getClassFields ( pojoClass ) ; // CHECK FOR ID BINDING
 final Field idField = fieldIds . get ( pojoClass ) ; if ( idField != null ) { Object id = getFieldValue ( iPojo , idField . getName ( ) ) ; if ( id != null ) { // FOUND
 if ( id instanceof ORecordId ) { ORecordInternal . setIdentity ( iRecord , ( ORecordId ) id ) ; } else if ( id instanceof Number ) { // TREATS AS CLUSTER POSITION
 ( ( ORecordId ) iRecord . getIdentity ( ) ) . setClusterId ( schemaClass . getDefaultClusterId ( ) ) ; ( ( ORecordId ) iRecord . getIdentity ( ) ) . setClusterPosition ( ( ( Number ) id ) . longValue ( ) ) ; } else if ( id instanceof String ) ( ( ORecordId ) iRecord . getIdentity ( ) ) . fromString ( ( String ) id ) ; else if ( id . getClass ( ) . equals ( Object . class ) ) ORecordInternal . setIdentity ( iRecord , ( ORecordId ) id ) ; else OLogManager . instance ( ) . warn ( OObjectSerializerHelper . class , "@Id field has been declared as %s while the supported are: ORID, Number, String, Object" , id . getClass ( ) ) ; } } // CHECK FOR VERSION BINDING
 final Field vField = fieldVersions . get ( pojoClass ) ; boolean versionConfigured = false ; if ( vField != null ) { versionConfigured = true ; Object ver = getFieldValue ( iPojo , vField . getName ( ) ) ; final int version = convertVersion ( ver ) ; ORecordInternal . setVersion ( iRecord , version ) ; } if ( db . isMVCC ( ) && ! versionConfigured && db . getTransaction ( ) instanceof OTransactionOptimistic ) throw new OTransactionException ( "Cannot involve an object of class '" + pojoClass + "' in an Optimistic Transaction commit because it does not define @Version or @OVersion and therefore cannot handle MVCC" ) ; // SET OBJECT CLASS
 iRecord . setClassName ( schemaClass != null ? schemaClass . getName ( ) : null ) ; String fieldName ; Object fieldValue ; // CALL BEFORE MARSHALLING
 invokeCallback ( iPojo , iRecord , OBeforeSerialization . class ) ; for ( Field p : properties ) { fieldName = p . getName ( ) ; if ( idField != null && fieldName . equals ( idField . getName ( ) ) ) continue ; if ( vField != null && fieldName . equals ( vField . getName ( ) ) ) continue ; fieldValue = serializeFieldValue ( getFieldType ( iPojo , fieldName ) , getFieldValue ( iPojo , fieldName ) ) ; schemaProperty = schemaClass != null ? schemaClass . getProperty ( fieldName ) : null ; if ( fieldValue != null ) { if ( isEmbeddedObject ( iPojo . getClass ( ) , fieldValue . getClass ( ) , fieldName , iEntityManager ) ) { // AUTO CREATE SCHEMA PROPERTY
 if ( schemaClass == null ) { db . getMetadata ( ) . getSchema ( ) . createClass ( iPojo . getClass ( ) ) ; iRecord . setClassNameIfExists ( iPojo . getClass ( ) . getSimpleName ( ) ) ; } if ( schemaProperty == null ) { OType t = OType . getTypeByClass ( fieldValue . getClass ( ) ) ; if ( t == null ) t = OType . EMBEDDED ; schemaProperty = iRecord . getSchemaClass ( ) . createProperty ( fieldName , t ) ; } } } fieldValue = typeToStream ( fieldValue , schemaProperty != null ? schemaProperty . getType ( ) : null , iEntityManager , iObj2RecHandler , db , iRecord , iSaveOnlyDirty ) ; iRecord . field ( fieldName , fieldValue ) ; } iObj2RecHandler . registerUserObject ( iPojo , iRecord ) ; // CALL AFTER MARSHALLING
 invokeCallback ( iPojo , iRecord , OAfterSerialization . class ) ; OSerializationThreadLocal . INSTANCE . get ( ) . remove ( identityRecord ) ; Orient . instance ( ) . getProfiler ( ) . stopChrono ( "Object.toStream" , "Serialize object to stream" , timer ) ; return iRecord ; }


Input: Returns the declared generic types of a class . [CODESPLIT] public static Type [ ] getGenericTypes ( final Object iObject ) { if ( iObject instanceof OTrackedMultiValue ) { final Class < ? > cls = ( ( OTrackedMultiValue < ? , ? > ) iObject ) . getGenericClass ( ) ; if ( cls != null ) return new Type [ ] { cls } ; } return OReflectionHelper . getGenericTypes ( iObject . getClass ( ) ) ; }


Input: At run - time the evaluation per record must return always true since the recordset are filtered at the beginning unless an operator can work in both modes . In this case sub - class must extend it . [CODESPLIT] @ Override public Object evaluateRecord ( final OIdentifiable iRecord , ODocument iCurrentResult , final OSQLFilterCondition iCondition , final Object iLeft , final Object iRight , OCommandContext iContext , final ODocumentSerializer serializer ) { return true ; }


Input: Executes the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { ODatabaseDocumentInternal db = getDatabase ( ) ; db . begin ( ) ; if ( className == null && clusterName == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; OModifiableBoolean shutdownGraph = new OModifiableBoolean ( ) ; final boolean txAlreadyBegun = getDatabase ( ) . getTransaction ( ) . isActive ( ) ; try { final Set < OIdentifiable > sourceRIDs = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , source , context , iArgs ) ; // CREATE EDGES final List < ODocument > result = new ArrayList < ODocument > ( sourceRIDs . size ( ) ) ; for ( OIdentifiable from : sourceRIDs ) { final OVertex fromVertex = toVertex ( from ) ; if ( fromVertex == null ) continue ; final ORID oldVertex = fromVertex . getIdentity ( ) . copy ( ) ; final ORID newVertex = fromVertex . moveTo ( className , clusterName ) ; final ODocument newVertexDoc = newVertex . getRecord ( ) ; if ( fields != null ) { // EVALUATE FIELDS for ( final OPair < String , Object > f : fields ) { if ( f . getValue ( ) instanceof OSQLFunctionRuntime ) f . setValue ( ( ( OSQLFunctionRuntime ) f . getValue ( ) ) . getValue ( newVertex . getRecord ( ) , null , context ) ) ; } OSQLHelper . bindParameters ( newVertexDoc , fields , new OCommandParameters ( iArgs ) , context ) ; } if ( merge != null ) newVertexDoc . merge ( merge , true , false ) ; // SAVE CHANGES newVertexDoc . save ( ) ; // PUT THE MOVE INTO THE RESULT result . add ( new ODocument ( ) . setTrackingChanges ( false ) . field ( "old" , oldVertex , OType . LINK ) . field ( "new" , newVertex , OType . LINK ) ) ; if ( batch > 0 && result . size ( ) % batch == 0 ) { db . commit ( ) ; db . begin ( ) ; } } db . commit ( ) ; return result ; } finally { //      if (!txAlreadyBegun) //        db.commit(); } }


Input: { [CODESPLIT] @ Override public void serializeInByteBufferObject ( String object , ByteBuffer buffer , Object ... hints ) { int length = object . length ( ) ; buffer . putInt ( length ) ; byte [ ] binaryData = new byte [ length * 2 ] ; char [ ] stringContent = new char [ length ] ; object . getChars ( 0 , length , stringContent , 0 ) ; int counter = 0 ; for ( char character : stringContent ) { binaryData [ counter ] = ( byte ) character ; counter ++ ; binaryData [ counter ] = ( byte ) ( character >>> 8 ) ; counter ++ ; } buffer . put ( binaryData ) ; }


Input:
{ [CODESPLIT] @ Override public String deserializeFromByteBufferObject ( ByteBuffer buffer ) { int len = buffer . getInt ( ) ; final char [ ] chars = new char [ len ] ; final byte [ ] binaryData = new byte [ 2 * len ] ; buffer . get ( binaryData ) ; for ( int i = 0 ; i < len ; i ++ ) chars [ i ] = ( char ) ( ( 0xFF & binaryData [ i << 1 ] ) | ( ( 0xFF & binaryData [ ( i << 1 ) + 1 ] ) << 8 ) ) ; return new String ( chars ) ; } /**
   * {@inheritDoc}
   */ @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer ) { return buffer . getInt ( ) * 2 + OIntegerSerializer . INT_SIZE ; } /**
   * {@inheritDoc}
   */ @ Override public String deserializeFromByteBufferObject  ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { int len = walChanges . getIntValue ( buffer , offset ) ; final char [ ] chars = new char [ len ] ; offset += OIntegerSerializer . INT_SIZE ; byte [ ] binaryData = walChanges . getBinaryValue ( buffer , offset , 2 * len ) ; for ( int i = 0 ; i < len ; i ++ ) chars [ i ] = ( char ) ( ( 0xFF & binaryData [ i << 1 ] ) | ( ( 0xFF & binaryData [ ( i << 1 ) + 1 ] ) << 8 ) ) ; return new String ( chars ) ; } /**
   * {@inheritDoc}
   */ @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return walChanges . getIntValue ( buffer , offset ) * 2 + OIntegerSerializer . INT_SIZE ; } }


Input:
Write a OIdentifiable instance using this format :
 - 2 bytes : class id [ - 2 = no record - 3 = rid - 1 = no class id > - 1 = valid ]
 - 1 byte : record type [ d b f ]
 - 2 bytes : cluster id
 - 8 bytes : position in cluster
 - 4 bytes : record version
 - x bytes : record content
 [CODESPLIT] public static void writeIdentifiable ( OChannelBinary channel , OClientConnection connection , final OIdentifiable o ) throws IOException { if ( o == null ) channel . writeShort ( OChannelBinaryProtocol . RECORD_NULL ) ; else if ( o instanceof ORecordId ) { channel . writeShort ( OChannelBinaryProtocol . RECORD_RID ) ; channel . writeRID ( ( ORID ) o ) ; } else { writeRecord ( channel , connection , o . getRecord ( ) ) ; } }


Input: This method load the record information by the internal cluster segment . It s for compatibility with older database than 0 . 9 . 25 . [CODESPLIT] public OStorageConfigurationImpl load ( final OContextConfiguration configuration ) throws OSerializationException { lock . acquireWriteLock ( ) ; try { initConfiguration ( configuration ) ; final byte [ ] record = storage . readRecord ( CONFIG_RID , null , false , false , null ) . getResult ( ) . buffer ; if ( record == null ) throw new OStorageException ( "Cannot load database configuration. The database seems corrupted" ) ; fromStream ( record , 0 , record . length , streamCharset ) ; } finally { lock . releaseWriteLock ( ) ; } return this ; }


Input: Added version used for managed Network Versioning . [CODESPLIT] public byte [ ] toStream ( final int iNetworkVersion , Charset charset ) throws OSerializationException { lock . acquireReadLock ( ) ; try { final StringBuilder buffer = new StringBuilder ( 8192 ) ; write ( buffer , CURRENT_VERSION ) ; write ( buffer , name ) ; write ( buffer , schemaRecordId ) ; write ( buffer , dictionaryRecordId ) ; write ( buffer , indexMgrRecordId ) ; write ( buffer , localeLanguage ) ; write ( buffer , localeCountry ) ; write ( buffer , dateFormat ) ; write ( buffer , dateTimeFormat ) ; write ( buffer , timeZone . getID ( ) ) ; write ( buffer , charset ) ; if ( iNetworkVersion > 24 ) write ( buffer , conflictStrategy ) ; phySegmentToStream ( buffer , fileTemplate ) ; write ( buffer , clusters . size ( ) ) ; for ( OStorageClusterConfiguration c : clusters ) { if ( c == null ) { write ( buffer , - 1 ) ; continue ; } write ( buffer , c . getId ( ) ) ; write ( buffer , c . getName ( ) ) ; write ( buffer , c . getDataSegmentId ( ) ) ; if ( c instanceof OStoragePaginatedClusterConfiguration ) { write ( buffer , "d" ) ; final OStoragePaginatedClusterConfiguration paginatedClusterConfiguration = ( OStoragePaginatedClusterConfiguration ) c ; write ( buffer , paginatedClusterConfiguration . useWal ) ; write ( buffer , paginatedClusterConfiguration . recordOverflowGrowFactor ) ; write ( buffer , paginatedClusterConfiguration . recordGrowFactor ) ; write ( buffer , paginatedClusterConfiguration . compression ) ; if ( iNetworkVersion >= 31 ) write ( buffer , paginatedClusterConfiguration . encryption ) ; if ( iNetworkVersion > 24 ) write ( buffer , paginatedClusterConfiguration . conflictStrategy ) ; if ( iNetworkVersion > 25 ) write ( buffer , paginatedClusterConfiguration . getStatus ( ) . name ( ) ) ; if ( iNetworkVersion >= Integer . MAX_VALUE ) { write ( buffer , paginatedClusterConfiguration . getBinaryVersion ( ) ) ; } } } if ( iNetworkVersion <= 25 ) { // dataSegment array write ( buffer , 0 ) ; // tx Segment File write ( buffer , "" ) ; write ( buffer , "" ) ; write ( buffer , 0 ) ; // tx segment flags write ( buffer , false ) ; write ( buffer , false ) ; } synchronized ( properties ) { write ( buffer , properties . size ( ) ) ; for ( OStorageEntryConfiguration e : properties ) entryToStream ( buffer , e ) ; } write ( buffer , binaryFormatVersion ) ; write ( buffer , clusterSelection ) ; write ( buffer , getMinimumClusters ( ) ) ; if ( iNetworkVersion > 24 ) { write ( buffer , recordSerializer ) ; write ( buffer , recordSerializerVersion ) ; // WRITE CONFIGURATION write ( buffer , configuration . getContextSize ( ) ) ; for ( String k : configuration . getContextKeys ( ) ) { final OGlobalConfiguration cfg = OGlobalConfiguration . findByKey ( k ) ; write ( buffer , k ) ; if ( cfg != null ) { write ( buffer , cfg . isHidden ( ) ? null : configuration . getValueAsString ( cfg ) ) ; } else { write ( buffer , null ) ; OLogManager . instance ( ) . warn ( this , "Storing configuration for property:'" + k + "' not existing in current version" ) ; } } } write ( buffer , indexEngines . size ( ) ) ; for ( IndexEngineData engineData : indexEngines . values ( ) ) { write ( buffer , engineData . getName ( ) ) ; write ( buffer , engineData . getAlgorithm ( ) ) ; write ( buffer , engineData . getIndexType ( ) == null ? "" : engineData . getIndexType ( ) ) ; write ( buffer , engineData . getValueSerializerId ( ) ) ; write ( buffer , engineData . getKeySerializedId ( ) ) ; write ( buffer , engineData . isAutomatic ( ) ) ; write ( buffer , engineData . getDurableInNonTxMode ( ) ) ; write ( buffer , engineData . getVersion ( ) ) ; write ( buffer , engineData . isNullValuesSupport ( ) ) ; write ( buffer , engineData . getKeySize ( ) ) ; write ( buffer , engineData . getEncryption ( ) ) ; write ( buffer , engineData . getEncryptionOptions ( ) ) ; if ( engineData . getKeyTypes ( ) != null ) { write ( buffer , engineData . getKeyTypes ( ) . length ) ; for ( OType type : engineData . getKeyTypes ( ) ) { write ( buffer , type . name ( ) ) ; } } else { write ( buffer , 0 ) ; } if ( engineData . getEngineProperties ( ) == null ) { write ( buffer , 0 ) ; } else { write ( buffer , engineData . getEngineProperties ( ) . size ( ) ) ; for ( Map . Entry < String , String > property : engineData . getEngineProperties ( ) . entrySet ( ) ) { write ( buffer , property . getKey ( ) ) ; write ( buffer , property . getValue ( ) ) ; } } write ( buffer , engineData . getApiVersion ( ) ) ; write ( buffer , engineData . isMultivalue ( ) ) ; } write ( buffer , createdAtVersion ) ; write ( buffer , pageSize ) ; write ( buffer , freeListBoundary ) ; write ( buffer , maxKeySize ) ; // PLAIN: ALLOCATE ENOUGH SPACE TO REUSE IT EVERY TIME buffer . append ( "|" ) ; return buffer . toString ( ) . getBytes ( charset ) ; } finally  { lock . releaseReadLock ( ) ; } } public void create ( ) throws IOException { lock . acquireWriteLock ( ) ; try { storage . createRecord ( CONFIG_RID , new byte [ ] { 0 , 0 , 0 , 0 } , 0 , OBlob . RECORD_TYPE , null ) ; } finally { lock . releaseWriteLock ( ) ; } }


Input: Returns true if an arrays contains a value otherwise false [CODESPLIT] public static boolean contains ( final int [ ] iArray , final int iToFind ) { if ( iArray == null || iArray . length == 0 ) return false ; for ( int e : iArray ) if ( e == iToFind ) return true ; return false ; }


Input: Returns true if an arrays contains a value otherwise false [CODESPLIT] public static < T > boolean contains ( final T [ ] iArray , final T iToFind ) { if ( iArray == null || iArray . length == 0 ) return false ; for ( T e : iArray ) if ( e != null && e . equals ( iToFind ) ) return true ; return false ; }


Input: this method parses the statement [CODESPLIT] @ Override public < RET extends OCommandExecutor > RET parse ( OCommandRequest iRequest ) { final OCommandRequestText textRequest = ( OCommandRequestText ) iRequest ; if ( iRequest instanceof OSQLSynchQuery ) { request = ( OSQLSynchQuery < ODocument > ) iRequest ; } else if ( iRequest instanceof OSQLAsynchQuery ) { request = ( OSQLAsynchQuery < ODocument > ) iRequest ; } else { // BUILD A QUERY OBJECT FROM THE COMMAND REQUEST request = new OSQLSynchQuery < ODocument > ( textRequest . getText ( ) ) ; if ( textRequest . getResultListener ( ) != null ) { request . setResultListener ( textRequest . getResultListener ( ) ) ; } } String queryText = textRequest . getText ( ) ; // please, do not look at this... refactor this ASAP with new executor structure final InputStream is = new ByteArrayInputStream ( queryText . getBytes ( ) ) ; OrientSql osql = null ; try { ODatabaseDocumentInternal db = getDatabase ( ) ; if ( db == null ) { osql = new OrientSql ( is ) ; } else { osql = new OrientSql ( is , db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; } } catch ( UnsupportedEncodingException e ) { OLogManager . instance ( ) . warn ( this , "Invalid charset for database " + getDatabase ( ) + " " + getDatabase ( ) . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; osql = new OrientSql ( is ) ; } try { OMatchStatement result = ( OMatchStatement ) osql . parse ( ) ; this . matchExpressions = result . matchExpressions ; this . notMatchExpressions = result . notMatchExpressions ; this . returnItems = result . returnItems ; this . returnAliases = result . returnAliases ; this . limit = result . limit ; } catch ( ParseException e ) { OCommandSQLParsingException ex = new OCommandSQLParsingException ( e , queryText ) ; OErrorCode . QUERY_PARSE_ERROR . throwException ( ex . getMessage ( ) , ex ) ; } buildPatterns ( ) ; pattern . validate ( ) ; return ( RET ) this ; }


Input: rebinds filter ( where ) conditions to alias nodes after optimization [CODESPLIT] private void rebindFilters ( Map < String , OWhereClause > aliasFilters ) { for ( OMatchExpression expression : matchExpressions ) { OWhereClause newFilter = aliasFilters . get ( expression . origin . getAlias ( ) ) ; expression . origin . setFilter ( newFilter ) ; for ( OMatchPathItem item : expression . items ) { newFilter = aliasFilters . get ( item . filter . getAlias ( ) ) ; item . filter . setFilter ( newFilter ) ; } } }