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


Input: Delete the current edge . [CODESPLIT] public boolean result ( final Object iRecord ) { final OIdentifiable id = ( OIdentifiable ) iRecord ; if ( compiledFilter != null ) { // ADDITIONAL FILTERING if ( ! ( Boolean ) compiledFilter . evaluate ( id . getRecord ( ) , null , context ) ) return true ; } if ( id . getIdentity ( ) . isValid ( ) ) { final OEdge e = toEdge ( id ) ; if ( e != null ) { e . delete ( ) ; if ( ! txAlreadyBegun && batch > 0 && ( removed + 1 ) % batch == 0 ) { getDatabase ( ) . commit ( ) ; getDatabase ( ) . begin ( ) ; } removed ++ ; } } return true ; }


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


Input: Check if the current instance extends specified schema class . [CODESPLIT] public boolean isSubClassOf ( final String iClassName ) { acquireSchemaReadLock ( ) ; try { if ( iClassName == null ) return false ; if ( iClassName . equalsIgnoreCase ( getName ( ) ) || iClassName . equalsIgnoreCase ( getShortName ( ) ) ) return true ; for ( OClassImpl superClass : superClasses ) { if ( superClass . isSubClassOf ( iClassName ) ) return true ; } return false ; } finally { releaseSchemaReadLock ( ) ; } }


Input: Check if the current instance extends specified schema class . [CODESPLIT] public boolean isSubClassOf ( final OClass clazz ) { acquireSchemaReadLock ( ) ; try { if ( clazz == null ) return false ; if ( equals ( clazz ) ) return true ; for ( OClassImpl superClass : superClasses ) { if ( superClass . isSubClassOf ( clazz ) ) return true ; } return false ; } finally { releaseSchemaReadLock ( ) ; } }


Input: Adds a base class to the current one . It adds also the base class cluster ids to the polymorphic cluster ids array . [CODESPLIT] protected OClass addBaseClass ( final OClassImpl iBaseClass ) { checkRecursion ( iBaseClass ) ; if ( subclasses == null ) subclasses = new ArrayList < OClass > ( ) ; if ( subclasses . contains ( iBaseClass ) ) return this ; subclasses . add ( iBaseClass ) ; addPolymorphicClusterIdsWithInheritance ( iBaseClass ) ; return this ; }


Input: Add different cluster id to the polymorphic cluster ids array . [CODESPLIT] protected void addPolymorphicClusterIds ( final OClassImpl iBaseClass ) { Set < Integer > clusters = new TreeSet < Integer > ( ) ; for ( int clusterId : polymorphicClusterIds ) { clusters . add ( clusterId ) ; } for ( int clusterId : iBaseClass . polymorphicClusterIds ) { if ( clusters . add ( clusterId ) ) { try { addClusterIdToIndexes ( clusterId ) ; } catch ( RuntimeException e ) { OLogManager . instance ( ) . warn ( this , "Error adding clusterId '%d' to index of class '%s'" , e , clusterId , getName ( ) ) ; clusters . remove ( clusterId ) ; } } } polymorphicClusterIds = new int [ clusters . size ( ) ] ; int i = 0 ; for ( Integer cluster : clusters ) { polymorphicClusterIds [ i ] = cluster ; i ++ ; } }


Input: TODO HANDLE EVALUATE RECORD [CODESPLIT] @ Override public Object evaluateRecord ( OIdentifiable iRecord , ODocument iCurrentResult , OSQLFilterCondition iCondition , Object iLeft , Object iRight , OCommandContext iContext , final ODocumentSerializer serializer ) { OSQLFunction function = OSQLEngine . getInstance ( ) . getFunction ( keyword ) ; return function . execute ( this , iRecord , iCurrentResult , new Object [ ] { iLeft , iCondition . getRight ( ) } , iContext ) ; }


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


Input: Builds a { @link SortField } from a configuration map . The map can contains up to three fields : field ( name ) reverse ( true / false ) and type { @link SortField . Type } . [CODESPLIT] public static SortField buildSortField ( Map < String , Object > conf ) { final String field = Optional . ofNullable ( ( String ) conf . get ( "field" ) ) . orElse ( null ) ; final String type = Optional . ofNullable ( ( ( String ) conf . get ( "type" ) ) . toUpperCase ( ) ) . orElse ( SortField . Type . STRING . name ( ) ) ; final Boolean reverse = Optional . ofNullable ( ( Boolean ) conf . get ( "reverse" ) ) . orElse ( false ) ; SortField sortField = new SortField ( field , SortField . Type . valueOf ( type ) , reverse ) ; return sortField ; }


Input: Reads the input stream in memory . This is less efficient than { @link #fromInputStream ( InputStream int ) } because allocation is made multiple times . If you already know the input size use { @link #fromInputStream ( InputStream int ) } . [CODESPLIT] public int fromInputStream ( final InputStream in ) throws IOException { final OMemoryStream out = new OMemoryStream ( ) ; try { final byte [ ] buffer = new byte [ OMemoryStream . DEF_SIZE ] ; int readBytesCount ; while ( true ) { readBytesCount = in . read ( buffer , 0 , buffer . length ) ; if ( readBytesCount == - 1 ) { break ; } out . write ( buffer , 0 , readBytesCount ) ; } out . flush ( ) ; _source = out . toByteArray ( ) ; } finally { out . close ( ) ; } _size = _source . length ; return _size ; }


Input: Reads the input stream in memory specifying the maximum bytes to read . This is more efficient than { @link #fromInputStream ( InputStream ) } because allocation is made only once . [CODESPLIT] public int fromInputStream ( final InputStream in , final int maxSize ) throws IOException { final byte [ ] buffer = new byte [ maxSize ] ; int totalBytesCount = 0 ; int readBytesCount ; while ( totalBytesCount < maxSize ) { readBytesCount = in . read ( buffer , totalBytesCount , buffer . length - totalBytesCount ) ; if ( readBytesCount == - 1 ) { break ; } totalBytesCount += readBytesCount ; } if ( totalBytesCount == 0 ) { _source = EMPTY_SOURCE ; _size = 0 ; } else if ( totalBytesCount == maxSize ) { _source = buffer ; _size = maxSize ; } else { _source = Arrays . copyOf ( buffer , totalBytesCount ) ; _size = totalBytesCount ; } return _size ; }


Input: Acquires direct memory buffer with native byte order . If there is free ( already released ) direct memory page we reuse it otherwise new memory chunk is allocated from direct memory . [CODESPLIT] public final OPointer acquireDirect ( boolean clear ) { OPointer pointer ; pointer = pointersPool . poll ( ) ; if ( pointer != null ) { pointersPoolSize . decrementAndGet ( ) ; } else { pointer = allocator . allocate ( pageSize , - 1 ) ; } if ( clear ) { pointer . clear ( ) ; } final ByteBuffer buffer = pointer . getNativeByteBuffer ( ) ; buffer . position ( 0 ) ; if ( TRACK ) { pointerMapping . put ( pointer , generatePointer ( ) ) ; } return pointer ; }


Input: Put buffer which is not used any more back to the pool or frees direct memory if pool is full . [CODESPLIT] public final void release ( OPointer pointer ) { if ( TRACK ) { pointerMapping . remove ( pointer ) ; } long poolSize = pointersPoolSize . incrementAndGet ( ) ; if ( poolSize > this . poolSize ) { pointersPoolSize . decrementAndGet ( ) ; allocator . deallocate ( pointer ) ; } else { pointersPool . add ( pointer ) ; } }


Input: Checks whether there are not released buffers in the pool [CODESPLIT] public void checkMemoryLeaks ( ) { boolean detected = false ; if ( TRACK ) { for ( Map . Entry < OPointer , PointerTracker > entry : pointerMapping . entrySet ( ) ) { OLogManager . instance ( ) . errorNoDb ( this , "DIRECT-TRACK: unreleased direct memory pointer `%X` detected." , entry . getValue ( ) . allocation , System . identityHashCode ( entry . getKey ( ) ) ) ; detected = true ; } } assert ! detected ; }


Input: Clears pool and dealocates memory . [CODESPLIT] public void clear ( ) { for ( OPointer pointer : pointersPool ) { allocator . deallocate ( pointer ) ; } pointersPool . clear ( ) ; pointersPoolSize . set ( 0 ) ; for ( OPointer pointer : pointerMapping . keySet ( ) ) { allocator . deallocate ( pointer ) ; } pointerMapping . clear ( ) ; }


Input: Convert the byte array to an int starting from the given offset . [CODESPLIT] public static int bytes2int ( final byte [ ] b , final int offset ) { return ( b [ offset ] ) << 24 | ( 0xff & b [ offset + 1 ] ) << 16 | ( 0xff & b [ offset + 2 ] ) << 8 | ( ( 0xff & b [ offset + 3 ] ) ) ; }


Input: Parse the persistence . xml files referenced by the URLs in the collection [CODESPLIT] public static PersistenceUnitInfo findPersistenceUnit ( String unitName , Collection < ? extends PersistenceUnitInfo > units ) { if ( units == null || unitName == null ) { return null ; } for ( PersistenceUnitInfo unit : units ) { if ( unitName . equals ( unit . getPersistenceUnitName ( ) ) ) { return unit ; } } return null ; }


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


Input: Fist tag of persistence . xml ( <persistence > ) have to have version attribute [CODESPLIT] @ Override public void startElement ( String uri , String localName , String name , Attributes attributes ) throws SAXException { PersistenceXml element = PersistenceXml . parse ( ( localName == null || localName . isEmpty ( ) ) ? name : localName ) ; schemaVersion = PersistenceXmlUtil . parseSchemaVersion ( uri , element , attributes ) ; // found, stop parsing if ( schemaVersion != null ) { throw new StopSAXParser ( ) ; } // This should never occurs, however check if contain known tag other than TAG_PERSISTENCE if ( TAG_PERSISTENCE != element && EnumSet . allOf ( PersistenceXml . class ) . contains ( element ) ) { throw new PersistenceException ( "Cannot find schema version attribute in <persistence> tag" ) ; } }


Input: Encodes a value using the variable - length encoding from <a href = http : // code . google . com / apis / protocolbuffers / docs / encoding . html > Google Protocol Buffers< / a > . Zig - zag is not used so input must not be negative . [CODESPLIT] public static void writeUnsignedVarLong ( long value , final BytesContainer bos ) { int pos ; while ( ( value & 0xFFFFFFFFFFFFFF80 L ) != 0L ) { // out.writeByte(((int) value & 0x7F) | 0x80); pos = bos . alloc ( ( short ) 1 ) ; bos . bytes [ pos ] = ( byte ) ( value & 0x7F | 0x80 ) ; value >>>= 7 ; } // out.writeByte((int) value & 0x7F); pos = bos . alloc ( ( short ) 1 ) ; bos . bytes [ pos ] = ( byte ) ( value & 0x7F ) ; }


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


Input: @param bytes to read bytes from [CODESPLIT] public static long readUnsignedVarLong ( final BytesContainer bytes ) { long value = 0L ; int i = 0 ; long b ; while ( ( ( b = bytes . bytes [ bytes . offset ++ ] ) & 0x80 L ) != 0 ) { value |= ( b & 0x7F ) << i ; i += 7 ; if ( i > 63 ) throw new IllegalArgumentException ( "Variable length quantity is too long (must be <= 63)" ) ; } return value | ( b << i ) ; }


Input: Auto register myself as hook . [CODESPLIT] @ Override public void onOpen ( final ODatabaseInternal iDatabase ) { if ( ! isRelatedToLocalServer ( iDatabase ) ) return ; if ( isOffline ( ) && status != NODE_STATUS . STARTING ) return ; final ODatabaseDocumentInternal currDb = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { final String dbName = iDatabase . getName ( ) ; final ODistributedConfiguration cfg = getDatabaseConfiguration ( dbName ) ; if ( cfg == null ) return ; } catch ( HazelcastException e ) { throw OException . wrapException ( new OOfflineNodeException ( "Hazelcast instance is not available" ) , e ) ; } catch ( HazelcastInstanceNotActiveException e ) { throw OException . wrapException ( new OOfflineNodeException ( "Hazelcast instance is not available" ) , e ) ; } finally { // RESTORE ORIGINAL DATABASE INSTANCE IN TL ODatabaseRecordThreadLocal . instance ( ) . set ( currDb ) ; } }


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


Input: Guarantees that each class has own master cluster . [CODESPLIT] public boolean installClustersOfClass ( final ODatabaseInternal iDatabase , final OClass iClass , OModifiableDistributedConfiguration cfg ) { final String databaseName = iDatabase . getName ( ) ; if ( iClass . isAbstract ( ) ) return false ; // INIT THE DATABASE IF NEEDED getMessageService ( ) . registerDatabase ( databaseName , cfg ) ; return executeInDistributedDatabaseLock ( databaseName , 20000 , cfg , new OCallable < Boolean , OModifiableDistributedConfiguration > ( ) { @ Override public Boolean call ( final OModifiableDistributedConfiguration lastCfg ) { final Set < String > availableNodes = getAvailableNodeNames ( iDatabase . getName ( ) ) ; final List < String > cluster2Create = clusterAssignmentStrategy . assignClusterOwnershipOfClass ( iDatabase , lastCfg , iClass , availableNodes , true ) ; final Map < OClass , List < String > > cluster2CreateMap = new HashMap < OClass , List < String > > ( 1 ) ; cluster2CreateMap . put ( iClass , cluster2Create ) ; createClusters ( iDatabase , cluster2CreateMap , lastCfg ) ; return true ; } } ) ; }


Input: Executes an operation protected by a distributed lock ( one per database ) . [CODESPLIT] public < T > T executeInDistributedDatabaseLock ( final String databaseName , final long timeoutLocking , OModifiableDistributedConfiguration lastCfg , final OCallable < T , OModifiableDistributedConfiguration > iCallback ) { boolean updated ; T result ; lockManagerRequester . acquireExclusiveLock ( databaseName , nodeName , timeoutLocking ) ; try { if ( lastCfg == null ) // ACQUIRE CFG INSIDE THE LOCK lastCfg = getDatabaseConfiguration ( databaseName ) . modify ( ) ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , nodeName , null , DIRECTION . NONE , "Current distributed configuration for database '%s': %s" , databaseName , lastCfg . getDocument ( ) . toJSON ( ) ) ; try { result = iCallback . call ( lastCfg ) ; } finally { if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , nodeName , null , DIRECTION . NONE , "New distributed configuration for database '%s': %s" , databaseName , lastCfg . getDocument ( ) . toJSON ( ) ) ; // CONFIGURATION CHANGED, UPDATE IT ON THE CLUSTER AND DISK updated = updateCachedDatabaseConfiguration ( databaseName , lastCfg , true ) ; } } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { lockManagerRequester . releaseExclusiveLock ( databaseName , nodeName ) ; } if ( updated ) { // SEND NEW CFG TO ALL THE CONNECTED CLIENTS notifyClients ( databaseName ) ; serverInstance . getClientConnectionManager ( ) . pushDistribCfg2Clients ( getClusterConfiguration ( ) ) ; } return result ; }


Input: Avoids to dump the same configuration twice if it s unchanged since the last time . [CODESPLIT] protected void dumpServersStatus ( ) { final ODocument cfg = getClusterConfiguration ( ) ; final String compactStatus = ODistributedOutput . getCompactServerStatus ( this , cfg ) ; if ( ! lastServerDump . equals ( compactStatus ) ) { lastServerDump = compactStatus ; ODistributedServerLog . info ( this , getLocalNodeName ( ) , null , DIRECTION . NONE , "Distributed servers status (*=current @=lockmgr[%s]):\n%s" , getLockManagerServer ( ) , ODistributedOutput . formatServerStatus ( this , cfg ) ) ; } }


Input: This method is used to find item in collection using passed in comparator . Only 0 value ( requested object is found ) returned by comparator is taken into account the rest is ignored . [CODESPLIT] public static < T > int indexOf ( final List < T > list , final T object , final Comparator < T > comparator ) { int i = 0 ; for ( final T item : list ) { if ( comparator . compare ( item , object ) == 0 ) return i ; i ++ ; } return - 1 ; }


Input: This method is used to find an item in an array . [CODESPLIT] public static int indexOf ( final Object [ ] array , final Comparable object ) { for ( int i = 0 ; i < array . length ; ++ i ) { if ( object . compareTo ( array [ i ] ) == 0 ) // FOUND return i ; } return - 1 ; }


Input: This method is used to find a number in an array . [CODESPLIT] public static int indexOf ( final int [ ] array , final int object ) { for ( int i = 0 ; i < array . length ; ++ i ) { if ( array [ i ] == object ) // FOUND return i ; } return - 1 ; }


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


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


Input: Handles the record in result . [CODESPLIT] @ Override protected boolean handleResult ( final OIdentifiable iRecord , final OCommandContext iContext ) { lastRecord = iRecord ; if ( ( orderedFields . isEmpty ( ) || fullySortedByIndex || isRidOnlySort ( ) ) && skip > 0 && this . unwindFields == null && this . expandTarget == null ) { lastRecord = null ; skip -- ; return true ; } if ( ! addResult ( lastRecord , iContext ) ) { return false ; } return continueSearching ( ) ; }


Input: Returns the temporary RID counter assuring it s unique per query tree . [CODESPLIT] public int getTemporaryRIDCounter ( final OCommandContext iContext ) { final OTemporaryRidGenerator parentQuery = ( OTemporaryRidGenerator ) iContext . getVariable ( "parentQuery" ) ; return parentQuery != null && parentQuery != this ? parentQuery . getTemporaryRIDCounter ( iContext ) : serialTempRID . getAndIncrement ( ) ; }


Input: in case of ORDER BY + SKIP + LIMIT this method applies ORDER BY operation on partial result and discards overflowing results ( results > skip + limit ) [CODESPLIT] private void applyPartialOrderBy ( ) { if ( expandTarget != null || ( unwindFields != null && unwindFields . size ( ) > 0 ) || orderedFields . isEmpty ( ) || fullySortedByIndex || isRidOnlySort ( ) ) { return ; } if ( limit > 0 ) { int sortBufferSize = limit + 1 ; if ( skip > 0 ) { sortBufferSize += skip ; } if ( tempResult instanceof List && ( ( List ) tempResult ) . size ( ) >= sortBufferSize + PARTIAL_SORT_BUFFER_THRESHOLD ) { applyOrderBy ( false ) ; tempResult = new ArrayList ( ( ( List ) tempResult ) . subList ( 0 , sortBufferSize ) ) ; } } }


Input: Report the tip to the profiler and collect it in context to be reported by tools like Studio [CODESPLIT] protected void reportTip ( final String iMessage ) { Orient . instance ( ) . getProfiler ( ) . reportTip ( iMessage ) ; List < String > tips = ( List < String > ) context . getVariable ( "tips" ) ; if ( tips == null ) { tips = new ArrayList < String > ( 3 ) ; context . setVariable ( "tips" , tips ) ; } tips . add ( iMessage ) ; }


Input: Parses the fetchplan keyword if found . [CODESPLIT] protected boolean parseFetchplan ( final String w ) throws OCommandSQLParsingException { if ( ! w . equals ( KEYWORD_FETCHPLAN ) ) { return false ; } parserSkipWhiteSpaces ( ) ; int start = parserGetCurrentPosition ( ) ; parserNextWord ( true ) ; int end = parserGetCurrentPosition ( ) ; parserSkipWhiteSpaces ( ) ; int position = parserGetCurrentPosition ( ) ; while ( ! parserIsEnded ( ) ) { final String word = OIOUtils . getStringContent ( parserNextWord ( true ) ) ; if ( ! OPatternConst . PATTERN_FETCH_PLAN . matcher ( word ) . matches ( ) ) { break ; } end = parserGetCurrentPosition ( ) ; parserSkipWhiteSpaces ( ) ; position = parserGetCurrentPosition ( ) ; } parserSetCurrentPosition ( position ) ; if ( end < 0 ) { fetchPlan = OIOUtils . getStringContent ( parserText . substring ( start ) ) ; } else { fetchPlan = OIOUtils . getStringContent ( parserText . substring ( start , end ) ) ; } request . setFetchPlan ( fetchPlan ) ; return true ; }


Input: Parses the NOCACHE keyword if found . [CODESPLIT] protected boolean parseNoCache ( final String w ) throws OCommandSQLParsingException { if ( ! w . equals ( KEYWORD_NOCACHE ) ) return false ; noCache = true ; return true ; }


Input: Use index to order documents by provided fields . [CODESPLIT] private boolean optimizeSort ( OClass iSchemaClass ) { OIndexCursor cursor = getOptimizedSortCursor ( iSchemaClass ) ; if ( cursor != null ) { fetchValuesFromIndexCursor ( cursor ) ; return true ; } return false ; }


Input:
Extract the content of collections and / or links and put it as result [CODESPLIT] private void applyExpand ( ) { if ( expandTarget == null ) { return ; } final long startExpand = System . currentTimeMillis ( ) ; try { if ( tempResult == null ) { tempResult = new ArrayList < OIdentifiable > ( ) ; if ( expandTarget instanceof OSQLFilterItemVariable ) { Object r = ( ( OSQLFilterItemVariable ) expandTarget ) . getValue ( null , null , context ) ; if ( r != null ) { if ( r instanceof OIdentifiable ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) r ) ; } else if ( r instanceof Iterator || OMultiValue . isMultiValue ( r ) ) { for ( Object o : OMultiValue . getMultiValueIterable ( r ) ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) o ) ; } } } } else if ( expandTarget instanceof OSQLFunctionRuntime && ! hasFieldItemParams ( ( OSQLFunctionRuntime ) expandTarget ) ) { if ( ( ( OSQLFunctionRuntime ) expandTarget ) . aggregateResults ( ) ) { throw new OCommandExecutionException ( "Unsupported operation: aggregate function in expand(" + expandTarget + ")" ) ; } else { Object r = ( ( OSQLFunctionRuntime ) expandTarget ) . execute ( null , null , null , context ) ; if ( r instanceof OIdentifiable ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) r ) ; } else if ( r instanceof Iterator || OMultiValue . isMultiValue ( r ) ) { for ( Object o : OMultiValue . getMultiValueIterable ( r ) ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) o ) ; } } } } } else { if ( tempResult == null ) { tempResult = new ArrayList < OIdentifiable > ( ) ; } final OMultiCollectionIterator < OIdentifiable > finalResult = new OMultiCollectionIterator < OIdentifiable > ( ) ; if ( orderedFields == null || orderedFields . size ( ) == 0 ) { // expand is applied before sorting, so limiting the result set here would give wrong results
 int iteratorLimit = 0 ; if ( limit < 0 ) { iteratorLimit = - 1 ; } else { iteratorLimit += limit ; } finalResult . setLimit ( iteratorLimit ) ; finalResult . setSkip ( skip ) ; } for ( OIdentifiable id : tempResult ) { Object fieldValue ; if ( expandTarget instanceof OSQLFilterItem ) { fieldValue = ( ( OSQLFilterItem ) expandTarget ) . getValue ( id . getRecord ( ) , null , context ) ; } else if ( expandTarget instanceof OSQLFunctionRuntime ) { fieldValue = ( ( OSQLFunctionRuntime ) expandTarget ) . getResult ( ) ; } else { fieldValue = expandTarget . toString ( ) ; } if ( fieldValue != null ) { if ( fieldValue instanceof Iterable && ! ( fieldValue instanceof OIdentifiable ) ) { fieldValue = ( ( Iterable ) fieldValue ) . iterator ( ) ; } if ( fieldValue instanceof ODocument ) { ArrayList < ODocument > partial = new ArrayList < ODocument > ( ) ; partial . add ( ( ODocument ) fieldValue ) ; finalResult . add ( partial ) ; } else if ( fieldValue instanceof Collection < ? > || fieldValue . getClass ( ) . isArray ( ) || fieldValue instanceof Iterator < ? > || fieldValue instanceof OIdentifiable || fieldValue instanceof ORidBag ) { finalResult . add ( fieldValue ) ; } else if ( fieldValue instanceof Map < ? , ? > ) { finalResult . add ( ( ( Map < ? , OIdentifiable > ) fieldValue ) . values ( ) ) ; } } } tempResult = finalResult ; } } finally { context . setVariable ( "expandElapsed" , ( System . currentTimeMillis ( ) - startExpand ) ) ; } }


Input: Single Job Status [CODESPLIT] public ODocument status ( ) { synchronized ( listener ) { ODocument status = new ODocument ( ) ; status . field ( "cfg" , cfg ) ; status . field ( "status" , this . status ) ; String lastBatchLog = "" ; if ( this . messageHandler != null ) { lastBatchLog = extractBatchLog ( ) ; } status . field ( "log" , lastBatchLog ) ; if ( this . status == Status . FINISHED ) { listener . notifyAll ( ) ; } return status ; } }


Input: Delegates the execution to the configured command executor . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < RET > RET execute ( final Object ... iArgs ) { setParameters ( iArgs ) ; OExecutionThreadLocal . INSTANCE . get ( ) . onAsyncReplicationOk = onAsyncReplicationOk ; OExecutionThreadLocal . INSTANCE . get ( ) . onAsyncReplicationError = onAsyncReplicationError ; return ( RET ) ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getStorage ( ) . command ( this ) ; }


Input: ( Internal only ) Creates a link between a vertices and a Graph Element . [CODESPLIT] public static Object createLink ( final ODocument iFromVertex , final OIdentifiable iTo , final String iFieldName ) { final Object out ; OType outType = iFromVertex . fieldType ( iFieldName ) ; Object found = iFromVertex . field ( iFieldName ) ; final OClass linkClass = ODocumentInternal . getImmutableSchemaClass ( iFromVertex ) ; if ( linkClass == null ) throw new IllegalArgumentException ( "Class not found in source vertex: " + iFromVertex ) ; final OProperty prop = linkClass . getProperty ( iFieldName ) ; final OType propType = prop != null && prop . getType ( ) != OType . ANY ? prop . getType ( ) : null ; if ( found == null ) { if ( propType == OType . LINKLIST || ( prop != null && "true" . equalsIgnoreCase ( prop . getCustom ( "ordered" ) ) ) ) { //TODO constant final Collection coll = new ORecordLazyList ( iFromVertex ) ; coll . add ( iTo ) ; out = coll ; outType = OType . LINKLIST ; } else if ( propType == null || propType == OType . LINKBAG ) { final ORidBag bag = new ORidBag ( ) ; bag . add ( iTo ) ; out = bag ; outType = OType . LINKBAG ; } else if ( propType == OType . LINK ) { out = iTo ; outType = OType . LINK ; } else throw new ODatabaseException ( "Type of field provided in schema '" + prop . getType ( ) + "' cannot be used for link creation." ) ; } else if ( found instanceof OIdentifiable ) { if ( prop != null && propType == OType . LINK ) throw new ODatabaseException ( "Type of field provided in schema '" + prop . getType ( ) + "' cannot be used for creation to hold several links." ) ; if ( prop != null && "true" . equalsIgnoreCase ( prop . getCustom ( "ordered" ) ) ) { //TODO constant final Collection coll = new ORecordLazyList ( iFromVertex ) ; coll . add ( found ) ; coll . add ( iTo ) ; out = coll ; outType = OType . LINKLIST ; } else { final ORidBag bag = new ORidBag ( ) ; bag . add ( ( OIdentifiable ) found ) ; bag . add ( iTo ) ; out = bag ; outType = OType . LINKBAG ; } } else if ( found instanceof ORidBag ) { // ADD THE LINK TO THE COLLECTION out = null ; ( ( ORidBag ) found ) . add ( iTo . getRecord ( ) ) ; } else if ( found instanceof Collection < ? > ) { // USE THE FOUND COLLECTION out = null ; ( ( Collection < Object > ) found ) . add ( iTo ) ; } else throw new ODatabaseException ( "Relationship content is invalid on field " + iFieldName + ". Found: " + found ) ; if ( out != null ) // OVERWRITE IT iFromVertex . field ( iFieldName , out , outType ) ; return out ; }


Input: That is internal method which is called once we encounter any error inside of JVM . In such case we need to restart JVM to avoid any data corruption . Till JVM is not restarted storage will be put in read - only state . [CODESPLIT] public final void handleJVMError ( final Error e ) { if ( jvmError . compareAndSet ( null , e ) ) { OLogManager . instance ( ) . errorNoDb ( this , "JVM error was thrown" , e ) ; } }


Input: This method finds all the records which were updated starting from ( but not including ) current LSN and write result in provided output stream . In output stream will be included all thw records which were updated / deleted / created since passed in LSN till the current moment . Deleted records are written in output stream first then created / updated records . All records are sorted by record id . Data format : <ol > <li > Amount of records ( single entry ) - 8 bytes< / li > <li > Record s cluster id - 4 bytes< / li > <li > Record s cluster position - 8 bytes< / li > <li > Delete flag 1 if record is deleted - 1 byte< / li > <li > Record version only if record is not deleted - 4 bytes< / li > <li > Record type only if record is not deleted - 1 byte< / li > <li > Length of binary presentation of record only if record is not deleted - 4 bytes< / li > <li > Binary presentation of the record only if record is not deleted - length of content is provided in above entity< / li > < / ol > [CODESPLIT] public OBackgroundDelta recordsChangedAfterLSN ( final OLogSequenceNumber lsn , final OCommandOutputListener outputListener ) { final OLogSequenceNumber endLsn ; // container of rids of changed records final SortedSet < ORID > sortedRids = new TreeSet <> ( ) ; try { if ( ! configuration . getContextConfiguration ( ) . getValueAsBoolean ( OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL ) ) { throw new IllegalStateException ( "Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, " + "to switch it on please set property " + OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL . getKey ( ) + " to the true value, please note that only records" + " which are stored after this property was set will be retrieved" ) ; } stateLock . acquireReadLock ( ) ; try { if ( writeAheadLog == null ) { return null ; } // we iterate till the last record is contained in wal at the moment when we call this method endLsn = writeAheadLog . end ( ) ; if ( endLsn == null || lsn . compareTo ( endLsn ) > 0 ) { OLogManager . instance ( ) . warn ( this , "Cannot find requested LSN=%s for database sync operation. Last available LSN is %s" , lsn , endLsn ) ; return null ; } if ( lsn . equals ( endLsn ) ) { // nothing has changed return new OBackgroundDelta ( endLsn ) ; } List < OWriteableWALRecord > records = writeAheadLog . next ( lsn , 1 ) ; if ( records . isEmpty ( ) ) { OLogManager . instance ( ) . info ( this , "Cannot find requested LSN=%s for database sync operation (last available LSN is %s)" , lsn , endLsn ) ; return null ; } final OLogSequenceNumber freezeLsn = records . get ( 0 ) . getLsn ( ) ; writeAheadLog . addCutTillLimit ( freezeLsn ) ; try { records = writeAheadLog . next ( lsn , 1_000 ) ; if ( records . isEmpty ( ) ) { OLogManager . instance ( ) . info ( this , "Cannot find requested LSN=%s for database sync operation (last available LSN is %s)" , lsn , endLsn ) ; return null ; } // all information about changed records is contained in atomic operation metadata long read = 0 ; readLoop : while ( ! records . isEmpty ( ) ) { for ( final OWALRecord record : records ) { final OLogSequenceNumber recordLSN = record . getLsn ( ) ; if ( endLsn . compareTo ( recordLSN ) >= 0 ) { if ( record instanceof OFileCreatedWALRecord ) { throw new ODatabaseException ( "Cannot execute delta-sync because a new file has been added. Filename: '" + ( ( OFileCreatedWALRecord ) record ) . getFileName ( ) + "' (id=" + ( ( OFileCreatedWALRecord ) record ) . getFileId ( ) + ")" ) ; } if ( record instanceof OFileDeletedWALRecord ) { throw new ODatabaseException ( "Cannot execute delta-sync because a file has been deleted. File id: " + ( ( OFileDeletedWALRecord ) record ) . getFileId ( ) ) ; } if ( record instanceof OAtomicUnitEndRecord ) { final OAtomicUnitEndRecord atomicUnitEndRecord = ( OAtomicUnitEndRecord ) record ; if ( atomicUnitEndRecord . getAtomicOperationMetadata ( ) . containsKey ( ORecordOperationMetadata . RID_METADATA_KEY ) ) { final ORecordOperationMetadata recordOperationMetadata = ( ORecordOperationMetadata ) atomicUnitEndRecord . getAtomicOperationMetadata ( ) . get ( ORecordOperationMetadata . RID_METADATA_KEY ) ; final Set < ORID > rids = recordOperationMetadata . getValue ( ) ; sortedRids . addAll ( rids ) ; } } read ++ ; if ( outputListener != null ) { outputListener . onMessage ( "read " + read + " records from WAL and collected " + sortedRids . size ( ) + " records" ) ; } } else { break readLoop ; } } records = writeAheadLog . next ( records . get ( records . size ( ) - 1 ) . getLsn ( ) , 1_000 ) ; } } finally { writeAheadLog . removeCutTillLimit ( freezeLsn ) ; } } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( "Error of reading of records changed after LSN " + lsn ) , e ) ; } finally { stateLock . releaseReadLock ( ) ; } OBackgroundDelta b = new OBackgroundDelta ( this , outputListener , sortedRids , lsn , endLsn ) ; return b ; } catch ( final RuntimeException e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Error e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: This method finds all the records changed in the last X transactions . [CODESPLIT] public Set < ORecordId > recordsChangedRecently ( final int maxEntries ) { final SortedSet < ORecordId > result = new TreeSet <> ( ) ; try { if ( ! OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL . getValueAsBoolean ( ) ) { throw new IllegalStateException ( "Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, " + "to switch it on please set property " + OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL . getKey ( ) + " to the true value, please note that only records" + " which are stored after this property was set will be retrieved" ) ; } stateLock . acquireReadLock ( ) ; try { if ( writeAheadLog == null ) { OLogManager . instance ( ) . warn ( this , "No WAL found for database '%s'" , name ) ; return null ; } OLogSequenceNumber startLsn = writeAheadLog . begin ( ) ; if ( startLsn == null ) { OLogManager . instance ( ) . warn ( this , "The WAL is empty for database '%s'" , name ) ; return result ; } final OLogSequenceNumber freezeLSN = startLsn ; writeAheadLog . addCutTillLimit ( freezeLSN ) ; try { //reread because log may be already truncated startLsn = writeAheadLog . begin ( ) ; if ( startLsn == null ) { OLogManager . instance ( ) . warn ( this , "The WAL is empty for database '%s'" , name ) ; return result ; } final OLogSequenceNumber endLsn = writeAheadLog . end ( ) ; if ( endLsn == null ) { OLogManager . instance ( ) . warn ( this , "The WAL is empty for database '%s'" , name ) ; return result ; } List < OWriteableWALRecord > walRecords = writeAheadLog . read ( startLsn , 1_000 ) ; if ( walRecords . isEmpty ( ) ) { OLogManager . instance ( ) . info ( this , "Cannot find requested LSN=%s for database sync operation (record in WAL is absent)" , startLsn ) ; return null ; } // KEEP LAST MAX-ENTRIES TRANSACTIONS' LSN final List < OAtomicUnitEndRecord > lastTx = new ArrayList <> ( 1024 ) ; readLoop : while ( ! walRecords . isEmpty ( ) ) { for ( final OWriteableWALRecord walRecord : walRecords ) { final OLogSequenceNumber recordLSN = walRecord . getLsn ( ) ; if ( endLsn . compareTo ( recordLSN ) >= 0 ) { if ( walRecord instanceof OAtomicUnitEndRecord ) { if ( lastTx . size ( ) >= maxEntries ) { lastTx . remove ( 0 ) ; } lastTx . add ( ( OAtomicUnitEndRecord ) walRecord ) ; } } else { break readLoop ; } } walRecords = writeAheadLog . next ( walRecords . get ( walRecords . size ( ) - 1 ) . getLsn ( ) , 1_000 ) ; } // COLLECT ALL THE MODIFIED RECORDS for ( final OAtomicUnitEndRecord atomicUnitEndRecord : lastTx ) { if ( atomicUnitEndRecord . getAtomicOperationMetadata ( ) . containsKey ( ORecordOperationMetadata . RID_METADATA_KEY ) ) { final ORecordOperationMetadata recordOperationMetadata = ( ORecordOperationMetadata ) atomicUnitEndRecord . getAtomicOperationMetadata ( ) . get ( ORecordOperationMetadata . RID_METADATA_KEY ) ; final Set < ORID > rids = recordOperationMetadata . getValue ( ) ; for ( final ORID rid : rids ) { result . add ( ( ORecordId ) rid ) ; } } } OLogManager . instance ( ) . info ( this , "Found %d records changed in last %d operations" , result . size ( ) , lastTx . size ( ) ) ; return result ; } finally { writeAheadLog . removeCutTillLimit ( freezeLSN ) ; } } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( "Error on reading last changed records" ) , e ) ; } finally { stateLock . releaseReadLock ( ) ; } } catch ( final RuntimeException e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Error e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: Starts to gather information about storage performance for current thread . Details which performance characteristics are gathered can be found at { @link OSessionStoragePerformanceStatistic } . [CODESPLIT] public void startGatheringPerformanceStatisticForCurrentThread ( ) { try { performanceStatisticManager . startThreadMonitoring ( ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: Completes gathering performance characteristics for current thread initiated by call of { @link #startGatheringPerformanceStatisticForCurrentThread () } [CODESPLIT] public OSessionStoragePerformanceStatistic completeGatheringPerformanceStatisticForCurrentThread ( ) { try { return performanceStatisticManager . stopThreadMonitoring ( ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: Scan the given transaction for new record and allocate a record id for them the relative record id is inserted inside the transaction for future use . [CODESPLIT] public void preallocateRids ( final OTransactionInternal clientTx ) { try { checkOpenness ( ) ; checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) ; final Iterable < ORecordOperation > entries = clientTx . getRecordOperations ( ) ; final TreeMap < Integer , OCluster > clustersToLock = new TreeMap <> ( ) ; final Set < ORecordOperation > newRecords = new TreeSet <> ( COMMIT_RECORD_OPERATION_COMPARATOR ) ; for ( final ORecordOperation txEntry : entries ) { if ( txEntry . type == ORecordOperation . CREATED ) { newRecords . add ( txEntry ) ; final int clusterId = txEntry . getRID ( ) . getClusterId ( ) ; clustersToLock . put ( clusterId , getClusterById ( clusterId ) ) ; } } stateLock . acquireReadLock ( ) ; try { checkOpenness ( ) ; makeStorageDirty ( ) ; boolean rollback = false ; atomicOperationsManager . startAtomicOperation ( ( String ) null , true ) ; try { lockClusters ( clustersToLock ) ; for ( final ORecordOperation txEntry : newRecords ) { final ORecord rec = txEntry . getRecord ( ) ; if ( ! rec . getIdentity ( ) . isPersistent ( ) ) { if ( rec . isDirty ( ) ) { //This allocate a position for a new record final ORecordId rid = ( ORecordId ) rec . getIdentity ( ) . copy ( ) ; final ORecordId oldRID = rid . copy ( ) ; final OCluster cluster = getClusterById ( rid . getClusterId ( ) ) ; final OPhysicalPosition ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; rid . setClusterPosition ( ppos . clusterPosition ) ; clientTx . updateIdentityAfterCommit ( oldRID , rid ) ; } } else { //This allocate position starting from a valid rid, used in distributed for allocate the same position on other nodes final ORecordId rid = ( ORecordId ) rec . getIdentity ( ) ; final OPaginatedCluster cluster = ( OPaginatedCluster ) getClusterById ( rid . getClusterId ( ) ) ; OPaginatedCluster . RECORD_STATUS recordStatus = cluster . getRecordStatus ( rid . getClusterPosition ( ) ) ; if ( recordStatus == OPaginatedCluster . RECORD_STATUS . NOT_EXISTENT ) { OPhysicalPosition ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; while ( ppos . clusterPosition < rid . getClusterPosition ( ) ) { ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; } if ( ppos . clusterPosition != rid . getClusterPosition ( ) ) { throw new OConcurrentCreateException ( rid , new ORecordId ( rid . getClusterId ( ) , ppos . clusterPosition ) ) ; } } else if ( recordStatus == OPaginatedCluster . RECORD_STATUS . PRESENT || recordStatus == OPaginatedCluster . RECORD_STATUS . REMOVED ) { final OPhysicalPosition ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; throw new OConcurrentCreateException ( rid , new ORecordId ( rid . getClusterId ( ) , ppos . clusterPosition ) ) ; } } } } catch ( final Exception e ) { rollback = true ; throw e ; } finally { atomicOperationsManager . endAtomicOperation ( rollback ) ; } } catch ( final IOException | RuntimeException ioe ) { throw OException . wrapException ( new OStorageException ( "Could not preallocate RIDs" ) , ioe ) ; } finally { stateLock . releaseReadLock ( ) ; } } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: The commit operation can be run in 3 different conditions embedded commit pre - allocated commit other node commit . <bold > Embedded commit< / bold > is the basic commit where the operation is run in embedded or server side the transaction arrive with invalid rids that get allocated and committed . <bold > pre - allocated commit< / bold > is the commit that happen after an preAllocateRids call is done this is usually run by the coordinator of a tx in distributed . <bold > other node commit< / bold > is the commit that happen when a node execute a transaction of another node where all the rids are already allocated in the other node . [CODESPLIT] private List < ORecordOperation > commit ( final OTransactionInternal transaction , final boolean allocated ) { // XXX: At this moment, there are two implementations of the commit method. One for regular client transactions and one for // implicit micro-transactions. The implementations are quite identical, but operate on slightly different data. If you change // this method don't forget to change its counterpart: // //  OAbstractPaginatedStorage.commit(com.orientechnologies.orient.core.storage.impl.local.OMicroTransaction) try { checkOpenness ( ) ; checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) ; txBegun . incrementAndGet ( ) ; final ODatabaseDocumentInternal database = transaction . getDatabase ( ) ; final OIndexManager indexManager = database . getMetadata ( ) . getIndexManager ( ) ; final TreeMap < String , OTransactionIndexChanges > indexOperations = getSortedIndexOperations ( transaction ) ; database . getMetadata ( ) . makeThreadLocalSchemaSnapshot ( ) ; final Collection < ORecordOperation > recordOperations = transaction . getRecordOperations ( ) ; final TreeMap < Integer , OCluster > clustersToLock = new TreeMap <> ( ) ; final Map < ORecordOperation , Integer > clusterOverrides = new IdentityHashMap <> ( 8 ) ; final Set < ORecordOperation > newRecords = new TreeSet <> ( COMMIT_RECORD_OPERATION_COMPARATOR ) ; for ( final ORecordOperation recordOperation : recordOperations ) { if ( recordOperation . type == ORecordOperation . CREATED || recordOperation . type == ORecordOperation . UPDATED ) { final ORecord record = recordOperation . getRecord ( ) ; if ( record instanceof ODocument ) { ( ( ODocument ) record ) . validate ( ) ; } } if ( recordOperation . type == ORecordOperation . UPDATED || recordOperation . type == ORecordOperation . DELETED ) { final int clusterId = recordOperation . getRecord ( ) . getIdentity ( ) . getClusterId ( ) ; clustersToLock . put ( clusterId , getClusterById ( clusterId ) ) ; } else if ( recordOperation . type == ORecordOperation . CREATED ) { newRecords . add ( recordOperation ) ; final ORecord record = recordOperation . getRecord ( ) ; final ORID rid = record . getIdentity ( ) ; int clusterId = rid . getClusterId ( ) ; if ( record . isDirty ( ) && clusterId == ORID . CLUSTER_ID_INVALID && record instanceof ODocument ) { // TRY TO FIX CLUSTER ID TO THE DEFAULT CLUSTER ID DEFINED IN SCHEMA CLASS final OImmutableClass class_ = ODocumentInternal . getImmutableSchemaClass ( ( ( ODocument ) record ) ) ; if ( class_ != null ) { clusterId = class_ . getClusterForNewInstance ( ( ODocument ) record ) ; clusterOverrides . put ( recordOperation , clusterId ) ; } } clustersToLock . put ( clusterId , getClusterById ( clusterId ) ) ; } } final List < ORecordOperation > result = new ArrayList <> ( 8 ) ; stateLock . acquireReadLock ( ) ; try { if ( modificationLock ) { final List < ORID > recordLocks = new ArrayList <> ( ) ; for ( final ORecordOperation recordOperation : recordOperations ) { if ( recordOperation . type == ORecordOperation . UPDATED || recordOperation . type == ORecordOperation . DELETED ) { recordLocks . add ( recordOperation . getRID ( ) ) ; } } final Set < ORID > locked = transaction . getLockedRecords ( ) ; if ( locked != null ) { recordLocks . removeAll ( locked ) ; } Collections . sort ( recordLocks ) ; for ( final ORID rid : recordLocks ) { acquireWriteLock ( rid ) ; } } try { checkOpenness ( ) ; makeStorageDirty ( ) ; boolean rollback = false ; startStorageTx ( transaction ) ; try { final OAtomicOperation atomicOperation = OAtomicOperationsManager . getCurrentOperation ( ) ; lockClusters ( clustersToLock ) ; checkReadOnlyConditions ( ) ; final Map < ORecordOperation , OPhysicalPosition > positions = new IdentityHashMap <> ( 8 ) ; for ( final ORecordOperation recordOperation : newRecords ) { final ORecord rec = recordOperation . getRecord ( ) ; if ( allocated ) { if ( rec . getIdentity ( ) . isPersistent ( ) ) { positions . put ( recordOperation , new OPhysicalPosition ( rec . getIdentity ( ) . getClusterPosition ( ) ) ) ; } else { throw new OStorageException ( "Impossible to commit a transaction with not valid rid in pre-allocated commit" ) ; } } else if ( rec . isDirty ( ) && ! rec . getIdentity ( ) . isPersistent ( ) ) { final ORecordId rid = ( ORecordId ) rec . getIdentity ( ) . copy ( ) ; final ORecordId oldRID = rid . copy ( ) ; final Integer clusterOverride = clusterOverrides . get ( recordOperation ) ; final int clusterId = clusterOverride == null ? rid . getClusterId ( ) : clusterOverride ; final OCluster cluster = getClusterById ( clusterId ) ; assert atomicOperation . getCounter ( ) == 1 ; OPhysicalPosition physicalPosition = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; assert atomicOperation . getCounter ( ) == 1 ; rid . setClusterId ( cluster . getId ( ) ) ; if ( rid . getClusterPosition ( ) > - 1 ) { // CREATE EMPTY RECORDS UNTIL THE POSITION IS REACHED. THIS IS THE CASE WHEN A SERVER IS OUT OF SYNC // BECAUSE A TRANSACTION HAS BEEN ROLLED BACK BEFORE TO SEND THE REMOTE CREATES. SO THE OWNER NODE DELETED // RECORD HAVING A HIGHER CLUSTER POSITION while ( rid . getClusterPosition ( ) > physicalPosition . clusterPosition ) { assert atomicOperation . getCounter ( ) == 1 ; physicalPosition = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; assert atomicOperation . getCounter ( ) == 1 ; } if ( rid . getClusterPosition ( ) != physicalPosition . clusterPosition ) { throw new OConcurrentCreateException ( rid , new ORecordId ( rid . getClusterId ( ) , physicalPosition . clusterPosition ) ) ; } } positions . put ( recordOperation , physicalPosition ) ; rid . setClusterPosition ( physicalPosition . clusterPosition ) ; transaction . updateIdentityAfterCommit ( oldRID , rid ) ; } } lockRidBags ( clustersToLock , indexOperations , indexManager ) ; checkReadOnlyConditions ( ) ; for ( final ORecordOperation recordOperation : recordOperations ) { assert atomicOperation . getCounter ( ) == 1 ; commitEntry ( recordOperation , positions . get ( recordOperation ) , database . getSerializer ( ) ) ; assert atomicOperation . getCounter ( ) == 1 ; result . add ( recordOperation ) ; } lockIndexes ( indexOperations ) ; checkReadOnlyConditions ( ) ; commitIndexes ( indexOperations , atomicOperation ) ; } catch ( final IOException | RuntimeException e ) { rollback = true ; if ( e instanceof RuntimeException ) { throw ( ( RuntimeException ) e ) ; } else { throw OException . wrapException ( new OStorageException ( "Error during transaction commit" ) , e ) ; } } finally { if ( rollback ) { rollback ( transaction ) ; } else { endStorageTx ( transaction , recordOperations ) ; } this . transaction . set ( null ) ; } } finally { atomicOperationsManager . ensureThatComponentsUnlocked ( ) ; database . getMetadata ( ) . clearThreadLocalSchemaSnapshot ( ) ; } } finally { try { if ( modificationLock ) { final List < ORID > recordLocks = new ArrayList <> ( ) ; for ( final ORecordOperation recordOperation : recordOperations ) { if ( recordOperation . type == ORecordOperation . UPDATED || recordOperation . type == ORecordOperation . DELETED ) { recordLocks . add ( recordOperation . getRID ( ) ) ; } } final Set < ORID > locked = transaction . getLockedRecords ( ) ; if ( locked != null ) { recordLocks . removeAll ( locked ) ; } for ( final ORID rid : recordLocks ) { releaseWriteLock ( rid ) ; } } } finally { stateLock . releaseReadLock ( ) ; } } if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) { OLogManager . instance ( ) . debug ( this , "%d Committed transaction %d on database '%s' (result=%s)" , Thread . currentThread ( ) . getId ( ) , transaction . getId ( ) , database . getName ( ) , result ) ; } return result ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { handleJVMError ( ee ) ; OAtomicOperationsManager . alarmClearOfAtomicOperation ( ) ; throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: Puts the given value under the given key into this storage for the index with the given index id . Validates the operation using the provided validator . [CODESPLIT] @ SuppressWarnings ( "UnusedReturnValue" ) public boolean validatedPutIndexValue ( int indexId , final Object key , final ORID value , final OBaseIndexEngine . Validator < Object , ORID > validator ) throws OInvalidIndexEngineIdException { indexId = extractInternalId ( indexId ) ; try { if ( transaction . get ( ) != null ) { return doValidatedPutIndexValue ( indexId , key , value , validator ) ; } checkOpenness ( ) ; stateLock . acquireReadLock ( ) ; try { checkOpenness ( ) ; checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) ; return doValidatedPutIndexValue ( indexId , key , value , validator ) ; } finally { stateLock . releaseReadLock ( ) ; } } catch ( final OInvalidIndexEngineIdException ie ) { throw logAndPrepareForRethrow ( ie ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: Rollbacks the given micro - transaction . [CODESPLIT] public void rollback ( final OMicroTransaction microTransaction ) { try { checkOpenness ( ) ; stateLock . acquireReadLock ( ) ; try { try { checkOpenness ( ) ; if ( transaction . get ( ) == null ) { return ; } if ( transaction . get ( ) . getMicroTransaction ( ) . getId ( ) != microTransaction . getId ( ) ) { throw new OStorageException ( "Passed in and active micro-transaction are different micro-transactions. Passed in micro-transaction cannot be " + "rolled back." ) ; } makeStorageDirty ( ) ; rollbackStorageTx ( ) ; microTransaction . updateRecordCacheAfterRollback ( ) ; txRollback . incrementAndGet ( ) ; } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( "Error during micro-transaction rollback" ) , e ) ; } finally { transaction . set ( null ) ; } } finally { stateLock . releaseReadLock ( ) ; } } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: Method that completes the cluster rename operation . <strong > IT WILL NOT RENAME A CLUSTER IT JUST CHANGES THE NAME IN THE INTERNAL MAPPING< / strong > [CODESPLIT] public final void renameCluster ( final String oldName , final String newName ) { try { clusterMap . put ( newName . toLowerCase ( configuration . getLocaleInstance ( ) ) , clusterMap . remove ( oldName . toLowerCase ( configuration . getLocaleInstance ( ) ) ) ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: Executes the command request and return the result back . [CODESPLIT] @ Override public final Object command ( final OCommandRequestText iCommand ) { try { while ( true ) { try { final OCommandExecutor executor = OCommandManager . instance ( ) . getExecutor ( iCommand ) ; // COPY THE CONTEXT FROM THE REQUEST executor . setContext ( iCommand . getContext ( ) ) ; executor . setProgressListener ( iCommand . getProgressListener ( ) ) ; executor . parse ( iCommand ) ; return executeCommand ( iCommand , executor ) ; } catch ( final ORetryQueryException ignore ) { if ( iCommand instanceof OQueryAbstract ) { final OQueryAbstract query = ( OQueryAbstract ) iCommand ; query . reset ( ) ; } } } } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee , false ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }


Input: Register the cluster internally . [CODESPLIT] private int registerCluster ( final OCluster cluster ) { final int id ; if ( cluster != null ) { // CHECK FOR DUPLICATION OF NAMES if ( clusterMap . containsKey ( cluster . getName ( ) . toLowerCase ( configuration . getLocaleInstance ( ) ) ) ) { throw new OConfigurationException ( "Cannot add cluster '" + cluster . getName ( ) + "' because it is already registered in database '" + name + "'" ) ; } // CREATE AND ADD THE NEW REF SEGMENT clusterMap . put ( cluster . getName ( ) . toLowerCase ( configuration . getLocaleInstance ( ) ) , cluster ) ; id = cluster . getId ( ) ; } else { id = clusters . size ( ) ; } setCluster ( id , cluster ) ; return id ; }


Input: Method which is called before any data modification operation to check alarm conditions such as : <ol > <li > Low disk space< / li > <li > Exception during data flush in background threads< / li > <li > Broken files< / li > < / ol > If one of those conditions are satisfied data modification operation is aborted and storage is switched in read only mode . [CODESPLIT] private void checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) { if ( transaction . get ( ) != null ) { return ; } if ( lowDiskSpace != null ) { if ( checkpointInProgress . compareAndSet ( false , true ) ) { try { if ( writeCache . checkLowDiskSpace ( ) ) { OLogManager . instance ( ) . error ( this , "Not enough disk space, force sync will be called" , null ) ; synch ( ) ; if ( writeCache . checkLowDiskSpace ( ) ) { throw new OLowDiskSpaceException ( "Error occurred while executing a write operation to database '" + name + "' due to limited free space on the disk (" + ( lowDiskSpace . freeSpace / ( 1024 * 1024 ) ) + " MB). The database is now working in read-only mode." + " Please close the database (or stop OrientDB), make room on your hard drive and then reopen the database. " + "The minimal required space is " + ( lowDiskSpace . requiredSpace / ( 1024 * 1024 ) ) + " MB. " + "Required space is now set to " + configuration . getContextConfiguration ( ) . getValueAsInteger ( OGlobalConfiguration . DISK_CACHE_FREE_SPACE_LIMIT ) + "MB (you can change it by setting parameter " + OGlobalConfiguration . DISK_CACHE_FREE_SPACE_LIMIT . getKey ( ) + ") ." ) ; } else { lowDiskSpace = null ; } } else { lowDiskSpace = null ; } } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( "Error during low disk space handling" ) , e ) ; } finally { checkpointInProgress . set ( false ) ; } } } checkReadOnlyConditions ( ) ; }


Input: Sets a property value [CODESPLIT] public Object setProperty ( final String iName , final Object iValue ) { if ( iValue != null ) { return properties . put ( iName . toLowerCase ( Locale . ENGLISH ) , iValue ) ; } else { return properties . remove ( iName . toLowerCase ( Locale . ENGLISH ) ) ; } }


Input: Execute the CREATE CLASS . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( className == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseDocument database = getDatabase ( ) ; boolean alreadyExists = database . getMetadata ( ) . getSchema ( ) . existsClass ( className ) ; if ( ! alreadyExists || ! ifNotExists ) { if ( clusters != null ) database . getMetadata ( ) . getSchema ( ) . createClass ( className , clusters , superClasses . toArray ( new OClass [ 0 ] ) ) ; else database . getMetadata ( ) . getSchema ( ) . createClass ( className , clusterIds , superClasses . toArray ( new OClass [ 0 ] ) ) ; } return database . getMetadata ( ) . getSchema ( ) . getClasses ( ) . size ( ) ; }


Input: ( Blueprints Extension ) Counts the total items found . This method is more efficient than executing the query and browse the returning Iterable . [CODESPLIT] @ Override public long count ( ) { if ( hasContainers . isEmpty ( ) ) { // NO CONDITIONS: USE THE FAST COUNT long counter = ( ( OrientVertex ) vertex ) . countEdges ( direction , labels ) ; if ( limit != Integer . MAX_VALUE && counter > limit ) return limit ; return counter ; } // ITERATE EDGES TO MATCH CONDITIONS return super . count ( ) ; }


Input: Execute the SYNC DATABASE . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . DATABASE , "sync" , ORole . PERMISSION_UPDATE ) ; final OStorage stg = database . getStorage ( ) ; if ( ! ( stg instanceof ODistributedStorage ) ) throw new ODistributedException ( "SYNC DATABASE command cannot be executed against a non distributed server" ) ; final ODistributedStorage dStg = ( ODistributedStorage ) stg ; final OHazelcastPlugin dManager = ( OHazelcastPlugin ) dStg . getDistributedManager ( ) ; if ( dManager == null || ! dManager . isEnabled ( ) ) throw new OCommandExecutionException ( "OrientDB is not started in distributed mode" ) ; final String databaseName = database . getName ( ) ; return dManager . installDatabase ( true , databaseName , parsedStatement . isForce ( ) , ! parsedStatement . isFull ( ) ) ; }


Input: { [CODESPLIT] public OCommandExecutorSQLAbstract createCommand ( final String name ) throws OCommandExecutionException { final Class < ? extends OCommandExecutorSQLAbstract > clazz = COMMANDS . get ( name ) ; if ( clazz == null ) { throw new OCommandExecutionException ( "Unknowned command name :" + name ) ; } try { return clazz . newInstance ( ) ; } catch ( Exception e ) { throw OException . wrapException ( new OCommandExecutionException ( "Error in creation of command " + name + "(). Probably there is not an empty constructor or the constructor generates errors" ) , e ) ; } }


Input: { [CODESPLIT] public < RET extends ORecord > RET load ( final ORID iRecordId , final String iFetchPlan , final boolean iIgnoreCache ) { return ( RET ) executeReadRecord ( ( ORecordId ) iRecordId , null , - 1 , iFetchPlan , iIgnoreCache , ! iIgnoreCache , false , OStorage . LOCKING_STRATEGY . DEFAULT , new SimpleRecordReader ( prefetchRecords ) ) ; }


Input: Deletes the record checking the version . [CODESPLIT] public ODatabase < ORecord > delete ( final ORID iRecord , final int iVersion ) { ORecord record = load ( iRecord ) ; ORecordInternal . setVersion ( record , iVersion ) ; delete ( record ) ; return this ; }


Input: { [CODESPLIT] @ Override @ Deprecated public < REC extends ORecord > ORecordIteratorCluster < REC > browseCluster ( final String iClusterName , final Class < REC > iRecordClass , final long startClusterPosition , final long endClusterPosition , final boolean loadTombstones ) { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; checkIfActive ( ) ; final int clusterId = getClusterIdByName ( iClusterName ) ; return new ORecordIteratorCluster < REC > ( this , clusterId , startClusterPosition , endClusterPosition , OStorage . LOCKING_STRATEGY . DEFAULT ) ; }


Input: { [CODESPLIT] public OCommandRequest command ( final OCommandRequest iCommand ) { checkSecurity ( ORule . ResourceGeneric . COMMAND , ORole . PERMISSION_READ ) ; checkIfActive ( ) ; final OCommandRequestInternal command = ( OCommandRequestInternal ) iCommand ; try { command . reset ( ) ; return command ; } catch ( Exception e ) { throw OException . wrapException ( new ODatabaseException ( "Error on command execution" ) , e ) ; } }


Input: { [CODESPLIT] public < RET extends List < ? > > RET query ( final OQuery < ? > iCommand , final Object ... iArgs ) { checkIfActive ( ) ; iCommand . reset ( ) ; return ( RET ) iCommand . execute ( iArgs ) ; }


Input: { [CODESPLIT] @ Override public long countClusterElements ( int [ ] iClusterIds , boolean countTombstones ) { checkIfActive ( ) ; String name ; for ( int iClusterId : iClusterIds ) { name = getClusterNameById ( iClusterId ) ; checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , name ) ; } return getStorage ( ) . count ( iClusterIds , countTombstones ) ; }


Input: { [CODESPLIT] @ Override public long countClusterElements ( final String iClusterName ) { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; checkIfActive ( ) ; final int clusterId = getClusterIdByName ( iClusterName ) ; if ( clusterId < 0 ) throw new IllegalArgumentException ( "Cluster '" + iClusterName + "' was not found" ) ; return getStorage ( ) . count ( clusterId ) ; }


Input: { [CODESPLIT] public < DB extends ODatabaseDocument > DB checkSecurity ( final ORule . ResourceGeneric resourceGeneric , final String resourceSpecific , final int iOperation ) { if ( user != null ) { try { user . allow ( resourceGeneric , resourceSpecific , iOperation ) ; } catch ( OSecurityAccessException e ) { if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . debug ( this , "User '%s' tried to access the reserved resource '%s.%s', operation '%s'" , getUser ( ) , resourceGeneric , resourceSpecific , iOperation ) ; throw e ; } } return ( DB ) this ; }


Input: { [CODESPLIT] public < DB extends ODatabaseDocument > DB checkSecurity ( final ORule . ResourceGeneric iResourceGeneric , final int iOperation , final Object ... iResourcesSpecific ) { if ( user != null ) { try { if ( iResourcesSpecific . length != 0 ) { for ( Object target : iResourcesSpecific ) { if ( target != null ) { user . allow ( iResourceGeneric , target . toString ( ) , iOperation ) ; } else user . allow ( iResourceGeneric , null , iOperation ) ; } } else user . allow ( iResourceGeneric , null , iOperation ) ; } catch ( OSecurityAccessException e ) { if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . debug ( this , "[checkSecurity] User '%s' tried to access the reserved resource '%s', target(s) '%s', operation '%s'" , getUser ( ) , iResourceGeneric , Arrays . toString ( iResourcesSpecific ) , iOperation ) ; throw e ; } } return ( DB ) this ; }


Input: { [CODESPLIT] public < DB extends ODatabaseDocument > DB checkSecurity ( final ORule . ResourceGeneric iResourceGeneric , final int iOperation , final Object iResourceSpecific ) { checkOpenness ( ) ; if ( user != null ) { try { if ( iResourceSpecific != null ) user . allow ( iResourceGeneric , iResourceSpecific . toString ( ) , iOperation ) ; else user . allow ( iResourceGeneric , null , iOperation ) ; } catch ( OSecurityAccessException e ) { if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . debug ( this , "[checkSecurity] User '%s' tried to access the reserved resource '%s', target '%s', operation '%s'" , getUser ( ) , iResourceGeneric , iResourceSpecific , iOperation ) ; throw e ; } } return ( DB ) this ; }


Input: { [CODESPLIT] public < DB extends ODatabase > DB setStatus ( final STATUS status ) { checkIfActive ( ) ; setStatusInternal ( status ) ; return ( DB ) this ; }


Input: { [CODESPLIT] public void setUser ( final OSecurityUser user ) { checkIfActive ( ) ; if ( user instanceof OUser ) { OMetadata metadata = getMetadata ( ) ; if ( metadata != null ) { final OSecurity security = metadata . getSecurity ( ) ; this . user = new OImmutableUser ( security . getVersion ( ) , ( OUser ) user ) ; } else this . user = new OImmutableUser ( - 1 , ( OUser ) user ) ; } else this . user = ( OImmutableUser ) user ; }


Input: { [CODESPLIT] public < DB extends ODatabase < ? > > DB registerHook ( final ORecordHook iHookImpl , final ORecordHook . HOOK_POSITION iPosition ) { checkOpenness ( ) ; checkIfActive ( ) ; final Map < ORecordHook , ORecordHook . HOOK_POSITION > tmp = new LinkedHashMap < ORecordHook , ORecordHook . HOOK_POSITION > ( hooks ) ; tmp . put ( iHookImpl , iPosition ) ; hooks . clear ( ) ; for ( ORecordHook . HOOK_POSITION p : ORecordHook . HOOK_POSITION . values ( ) ) { for ( Map . Entry < ORecordHook , ORecordHook . HOOK_POSITION > e : tmp . entrySet ( ) ) { if ( e . getValue ( ) == p ) hooks . put ( e . getKey ( ) , e . getValue ( ) ) ; } } compileHooks ( ) ; return ( DB ) this ; }


Input: { [CODESPLIT] public < DB extends ODatabase < ? > > DB registerHook ( final ORecordHook iHookImpl ) { return ( DB ) registerHook ( iHookImpl , ORecordHook . HOOK_POSITION . REGULAR ) ; }


Input: { [CODESPLIT] public < DB extends ODatabase < ? > > DB unregisterHook ( final ORecordHook iHookImpl ) { checkIfActive ( ) ; if ( iHookImpl != null ) { iHookImpl . onUnregister ( ) ; hooks . remove ( iHookImpl ) ; compileHooks ( ) ; } return ( DB ) this ; }


Input: Callback the registered hooks if any . [CODESPLIT] public ORecordHook . RESULT callbackHooks ( final ORecordHook . TYPE type , final OIdentifiable id ) { if ( id == null || hooks . isEmpty ( ) || id . getIdentity ( ) . getClusterId ( ) == 0 ) return ORecordHook . RESULT . RECORD_NOT_CHANGED ; final ORecordHook . SCOPE scope = ORecordHook . SCOPE . typeToScope ( type ) ; final int scopeOrdinal = scope . ordinal ( ) ; final ORID identity = id . getIdentity ( ) . copy ( ) ; if ( ! pushInHook ( identity ) ) return ORecordHook . RESULT . RECORD_NOT_CHANGED ; try { final ORecord rec = id . getRecord ( ) ; if ( rec == null ) return ORecordHook . RESULT . RECORD_NOT_CHANGED ; final OScenarioThreadLocal . RUN_MODE runMode = OScenarioThreadLocal . INSTANCE . getRunMode ( ) ; boolean recordChanged = false ; for ( ORecordHook hook : hooksByScope [ scopeOrdinal ] ) { switch ( runMode ) { case DEFAULT : // NON_DISTRIBUTED OR PROXIED DB if ( getStorage ( ) . isDistributed ( ) && hook . getDistributedExecutionMode ( ) == ORecordHook . DISTRIBUTED_EXECUTION_MODE . TARGET_NODE ) // SKIP continue ; break ; // TARGET NODE case RUNNING_DISTRIBUTED : if ( hook . getDistributedExecutionMode ( ) == ORecordHook . DISTRIBUTED_EXECUTION_MODE . SOURCE_NODE ) continue ; } final ORecordHook . RESULT res = hook . onTrigger ( type , rec ) ; if ( res == ORecordHook . RESULT . RECORD_CHANGED ) recordChanged = true ; else if ( res == ORecordHook . RESULT . SKIP_IO ) // SKIP IO OPERATION return res ; else if ( res == ORecordHook . RESULT . SKIP ) // SKIP NEXT HOOKS AND RETURN IT return res ; else if ( res == ORecordHook . RESULT . RECORD_REPLACED ) return res ; } return recordChanged ? ORecordHook . RESULT . RECORD_CHANGED : ORecordHook . RESULT . RECORD_NOT_CHANGED ; } finally { popInHook ( identity ) ; } }


Input: { [CODESPLIT] public < DB extends ODatabaseDocument > DB setValidationEnabled ( final boolean iEnabled ) { set ( ATTRIBUTES . VALIDATION , iEnabled ) ; return ( DB ) this ; }


Input: Deletes the record without checking the version . [CODESPLIT] public ODatabaseDocument delete ( final ORID iRecord ) { checkOpenness ( ) ; checkIfActive ( ) ; final ORecord rec = load ( iRecord ) ; if ( rec != null ) delete ( rec ) ; return this ; }


Input: { [CODESPLIT] public < RET extends ORecord > RET load ( final ORecord iRecord , final String iFetchPlan , final boolean iIgnoreCache ) { return ( RET ) executeReadRecord ( ( ORecordId ) iRecord . getIdentity ( ) , iRecord , - 1 , iFetchPlan , iIgnoreCache , ! iIgnoreCache , false , OStorage . LOCKING_STRATEGY . NONE , new SimpleRecordReader ( prefetchRecords ) ) ; }


Input: This method is internal it can be subject to signature change or be removed do not use . [CODESPLIT] public boolean executeHideRecord ( OIdentifiable record , final OPERATION_MODE iMode ) { checkOpenness ( ) ; checkIfActive ( ) ; final ORecordId rid = ( ORecordId ) record . getIdentity ( ) ; if ( rid == null ) throw new ODatabaseException ( "Cannot hide record because it has no identity. Probably was created from scratch or contains projections of fields rather than a full record" ) ; if ( ! rid . isValid ( ) ) return false ; checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_DELETE , getClusterNameById ( rid . getClusterId ( ) ) ) ; getMetadata ( ) . makeThreadLocalSchemaSnapshot ( ) ; if ( record instanceof ODocument ) ODocumentInternal . checkClass ( ( ODocument ) record , this ) ; ORecordSerializationContext . pushContext ( ) ; try { final OStorageOperationResult < Boolean > operationResult ; operationResult = getStorage ( ) . hideRecord ( rid , iMode . ordinal ( ) , null ) ; // REMOVE THE RECORD FROM 1 AND 2 LEVEL CACHES if ( ! operationResult . isMoved ( ) ) getLocalCache ( ) . deleteRecord ( rid ) ; return operationResult . getResult ( ) ; } finally { ORecordSerializationContext . pullContext ( ) ; getMetadata ( ) . clearThreadLocalSchemaSnapshot ( ) ; } }


Input: { [CODESPLIT] @ Override public void freeze ( final boolean throwException ) { checkOpenness ( ) ; if ( ! ( getStorage ( ) instanceof OFreezableStorageComponent ) ) { OLogManager . instance ( ) . error ( this , "Only local paginated storage supports freeze. If you are using remote client please use OServerAdmin instead" , null ) ; return ; } final long startTime = Orient . instance ( ) . getProfiler ( ) . startChrono ( ) ; final OFreezableStorageComponent storage = getFreezableStorage ( ) ; if ( storage != null ) { storage . freeze ( throwException ) ; } Orient . instance ( ) . getProfiler ( ) . stopChrono ( "db." + getName ( ) + ".freeze" , "Time to freeze the database" , startTime , "db.*.freeze" ) ; }


Input: { [CODESPLIT] public ORecordIteratorClass < ODocument > browseClass ( final String iClassName , final boolean iPolymorphic ) { if ( getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getClass ( iClassName ) == null ) throw new IllegalArgumentException ( "Class '" + iClassName + "' not found in current database" ) ; checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_READ , iClassName ) ; return new ORecordIteratorClass < ODocument > ( this , iClassName , iPolymorphic , false ) ; }


Input: { [CODESPLIT] @ Override public ORecordIteratorCluster < ODocument > browseCluster ( final String iClusterName ) { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; return new ORecordIteratorCluster < ODocument > ( this , getClusterIdByName ( iClusterName ) ) ; }


Input: { [CODESPLIT] @ Override @ Deprecated public ORecordIteratorCluster < ODocument > browseCluster ( String iClusterName , long startClusterPosition , long endClusterPosition , boolean loadTombstones ) { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; return new ORecordIteratorCluster < ODocument > ( this , getClusterIdByName ( iClusterName ) , startClusterPosition , endClusterPosition , OStorage . LOCKING_STRATEGY . DEFAULT ) ; }


Input: Saves a document to the database . Behavior depends by the current running transaction if any . If no transaction is running then changes apply immediately . If an Optimistic transaction is running then the record will be changed at commit time . The current transaction will continue to see the record as modified while others not . If a Pessimistic transaction is running then an exclusive lock is acquired against the record . Current transaction will continue to see the record as modified while others cannot access to it since it s locked . <p > If MVCC is enabled and the version of the document is different by the version stored in the database then a { @link OConcurrentModificationException } exception is thrown . Before to save the document it must be valid following the constraints declared in the schema if any ( can work also in schema - less mode ) . To validate the document the { @link ODocument#validate () } is called . [CODESPLIT] @ Override public < RET extends ORecord > RET save ( final ORecord iRecord ) { return ( RET ) save ( iRecord , null , OPERATION_MODE . SYNCHRONOUS , false , null , null ) ; }


Input: Saves a document to the database . Behavior depends by the current running transaction if any . If no transaction is running then changes apply immediately . If an Optimistic transaction is running then the record will be changed at commit time . The current transaction will continue to see the record as modified while others not . If a Pessimistic transaction is running then an exclusive lock is acquired against the record . Current transaction will continue to see the record as modified while others cannot access to it since it s locked . <p > If MVCC is enabled and the version of the document is different by the version stored in the database then a { @link OConcurrentModificationException } exception is thrown . Before to save the document it must be valid following the constraints declared in the schema if any ( can work also in schema - less mode ) . To validate the document the { @link ODocument#validate () } is called . [CODESPLIT] @ Override public < RET extends ORecord > RET save ( final ORecord iRecord , final OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { return save ( iRecord , null , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; }


Input: Saves a document specifying a cluster where to store the record . Behavior depends by the current running transaction if any . If no transaction is running then changes apply immediately . If an Optimistic transaction is running then the record will be changed at commit time . The current transaction will continue to see the record as modified while others not . If a Pessimistic transaction is running then an exclusive lock is acquired against the record . Current transaction will continue to see the record as modified while others cannot access to it since it s locked . <p > If MVCC is enabled and the version of the document is different by the version stored in the database then a { @link OConcurrentModificationException } exception is thrown . Before to save the document it must be valid following the constraints declared in the schema if any ( can work also in schema - less mode ) . To validate the document the { @link ODocument#validate () } is called . [CODESPLIT] @ Override public < RET extends ORecord > RET save ( ORecord iRecord , String iClusterName , final OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { checkOpenness ( ) ; if ( iRecord instanceof OVertex ) { iRecord = iRecord . getRecord ( ) ; } if ( iRecord instanceof OEdge ) { if ( ( ( OEdge ) iRecord ) . isLightweight ( ) ) { iRecord = ( ( OEdge ) iRecord ) . getFrom ( ) ; } else { iRecord = iRecord . getRecord ( ) ; } } ODirtyManager dirtyManager = ORecordInternal . getDirtyManager ( iRecord ) ; if ( iRecord instanceof OElement && dirtyManager != null && dirtyManager . getReferences ( ) != null && ! dirtyManager . getReferences ( ) . isEmpty ( ) ) { if ( ( ( ( OElement ) iRecord ) . isVertex ( ) || ( ( OElement ) iRecord ) . isEdge ( ) ) && ! getTransaction ( ) . isActive ( ) && inHook . isEmpty ( ) ) { return saveGraph ( iRecord , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; } } return saveInternal ( iRecord , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; }


Input: Returns the number of the records of the class iClassName . [CODESPLIT] public long countView ( final String viewName ) { final OView cls = getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getView ( viewName ) ; if ( cls == null ) throw new IllegalArgumentException ( "View '" + cls + "' not found in database" ) ; return countClass ( cls , false ) ; }


Input: Returns the number of the records of the class iClassName considering also sub classes if polymorphic is true . [CODESPLIT] public long countClass ( final String iClassName , final boolean iPolymorphic ) { final OClass cls = getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getClass ( iClassName ) ; if ( cls == null ) throw new IllegalArgumentException ( "Class '" + cls + "' not found in database" ) ; return countClass ( cls , iPolymorphic ) ; }


Input: Activates current database instance on current thread . [CODESPLIT] @ Override public ODatabaseDocumentAbstract activateOnCurrentThread ( ) { final ODatabaseRecordThreadLocal tl = ODatabaseRecordThreadLocal . instance ( ) ; if ( tl != null ) tl . set ( this ) ; return this ; }


Input: Registers a stateful implementations a new instance will be created for each storage . [CODESPLIT] public void register ( final OEncryption iEncryption ) { try { final String name = iEncryption . name ( ) ; if ( instances . containsKey ( name ) ) throw new IllegalArgumentException ( "Encryption with name '" + name + "' was already registered" ) ; if ( classes . containsKey ( name ) ) throw new IllegalArgumentException ( "Encryption with name '" + name + "' was already registered" ) ; instances . put ( name , iEncryption ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Cannot register storage encryption algorithm '%s'" , e , iEncryption ) ; } }


Input:
/ * ( non - Javadoc ) [CODESPLIT] public byte [ ] getBytes ( long pos , int length ) throws SQLException { if ( pos < 1 ) throw new SQLException ( "The position of the first byte in the BLOB value to be " + "extracted cannot be less than 1" ) ; if ( length < 0 ) throw new SQLException ( "The number of the consecutive bytes in the BLOB value to " + "be extracted cannot be a negative number" ) ; int relativeIndex = this . getRelativeIndex ( pos ) ; ByteBuffer buffer = ByteBuffer . allocate ( length ) ; int j ; for ( j = 0 ; j < length ; j ++ ) { if ( relativeIndex == currentChunk . length ) { // go to the next chunk, if any...
 currentChunkIndex ++ ; if ( currentChunkIndex < binaryDataChunks . size ( ) ) { // the next chunk exists so we update the relative index and
 // the current chunk reference
 relativeIndex = 0 ; currentChunk = binaryDataChunks . get ( currentChunkIndex ) ; } else // exit from the loop: there are no more bytes to be read
 break ; } buffer . put ( currentChunk [ relativeIndex ] ) ; relativeIndex ++ ; } return buffer . array ( ) ; }


Input:
Calculates the index within a binary chunk corresponding to the given absolute position within this BLOB [CODESPLIT] private int getRelativeIndex ( long pos ) { int currentSize = 0 ; currentChunkIndex = 0 ; // loop until we find the chuks holding the given position
 while ( pos >= ( currentSize += binaryDataChunks . get ( currentChunkIndex ) . length ) ) currentChunkIndex ++ ; currentChunk = binaryDataChunks . get ( currentChunkIndex ) ; currentSize -= currentChunk . length ; // the position referred to the target binary chunk
 int relativePosition = ( int ) ( pos - currentSize ) ; // the index of the first byte to be returned
 return relativePosition - 1 ; }


Input: Parses the next word . It returns the word parsed if any . [CODESPLIT] protected String parserOptionalWord ( final boolean iUpperCase ) { parserPreviousPos = parserCurrentPos ; parserNextWord ( iUpperCase ) ; if ( parserLastWord . length ( ) == 0 ) return null ; return parserLastWord . toString ( ) ; }


Input: Parses the next word . If no word is found or the parsed word is not present in the word array received as parameter then a SyntaxError exception with the custom message received as parameter is thrown . It returns the word parsed if any . [CODESPLIT] protected String parserRequiredWord ( final boolean iUpperCase , final String iCustomMessage , String iSeparators ) { if ( iSeparators == null ) iSeparators = " ()=><,\r\n" ; parserNextWord ( iUpperCase , iSeparators ) ; if ( parserLastWord . length ( ) == 0 ) throwSyntaxErrorException ( iCustomMessage ) ; if ( parserLastWord . charAt ( 0 ) == ' ' && parserLastWord . charAt ( parserLastWord . length ( ) - 1 ) == ' ' ) { return parserLastWord . substring ( 1 , parserLastWord . length ( ) - 1 ) ; } return parserLastWord . toString ( ) ; }


Input: Parses the next sequence of chars . [CODESPLIT] protected int parserNextChars ( final boolean iUpperCase , final boolean iMandatory , final String ... iCandidateWords ) { parserPreviousPos = parserCurrentPos ; parserSkipWhiteSpaces ( ) ; parserEscapeSequenceCount = 0 ; parserLastWord . setLength ( 0 ) ; final String [ ] processedWords = Arrays . copyOf ( iCandidateWords , iCandidateWords . length ) ; // PARSE THE CHARS final String text2Use = iUpperCase ? parserTextUpperCase : parserText ; final int max = text2Use . length ( ) ; parserCurrentPos = parserCurrentPos + parserTextUpperCase . length ( ) - parserText . length ( ) ; // PARSE TILL 1 CHAR AFTER THE END TO SIMULATE A SEPARATOR AS EOF for ( int i = 0 ; parserCurrentPos <= max ; ++ i ) { final char ch = parserCurrentPos < max ? text2Use . charAt ( parserCurrentPos ) : ' ' ; final boolean separator = ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' ; if ( ! separator ) parserLastWord . append ( ch ) ; // CLEAR CANDIDATES int candidatesWordsCount = 0 ; int candidatesWordsPos = - 1 ; for ( int c = 0 ; c < processedWords . length ; ++ c ) { final String w = processedWords [ c ] ; if ( w != null ) { final int wordSize = w . length ( ) ; if ( ( separator && wordSize > i ) || ( ! separator && ( i > wordSize - 1 || w . charAt ( i ) != ch ) ) ) // DISCARD IT processedWords [ c ] = null ; else { candidatesWordsCount ++ ; if ( candidatesWordsCount == 1 ) // REMEMBER THE POSITION candidatesWordsPos = c ; } } } if ( candidatesWordsCount == 1 ) { // ONE RESULT, CHECKING IF FOUND final String w = processedWords [ candidatesWordsPos ] ; if ( w . length ( ) == i + ( separator ? 0 : 1 ) && ! Character . isLetter ( ch ) ) // FOUND! return candidatesWordsPos ; } if ( candidatesWordsCount == 0 || separator ) break ; parserCurrentPos ++ ; } if ( iMandatory ) throwSyntaxErrorException ( "Found unexpected keyword '" + parserLastWord + "' while it was expected '" + Arrays . toString ( iCandidateWords ) + "'" ) ; return - 1 ; }


Input: Parses optional keywords between the iWords . If a keyword is found but doesn t match with iWords then a SyntaxError is raised . [CODESPLIT] protected boolean parserOptionalKeyword ( final String ... iWords ) { parserNextWord ( true , " \r\n," ) ; if ( parserLastWord . length ( ) == 0 ) return false ; // FOUND: CHECK IF IT'S IN RANGE boolean found = iWords . length == 0 ; for ( String w : iWords ) { if ( parserLastWord . toString ( ) . equals ( w ) ) { found = true ; break ; } } if ( ! found ) throwSyntaxErrorException ( "Found unexpected keyword '" + parserLastWord + "' while it was expected '" + Arrays . toString ( iWords ) + "'" ) ; return true ; }


Input: Check for a separator [CODESPLIT] private boolean parserCheckSeparator ( final char c , final String iSeparatorChars ) { for ( int sepIndex = 0 ; sepIndex < iSeparatorChars . length ( ) ; ++ sepIndex ) { if ( iSeparatorChars . charAt ( sepIndex ) == c ) { parserLastSeparator = c ; return true ; } } return false ; }