Input: Adds the specified cluster to the class if it doesn t already exist . [CODESPLIT] public void createCluster ( final String className , final String clusterName ) { final ODatabaseDocumentInternal currentDB = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { final ODatabaseDocumentInternal sysdb = openSystemDatabase ( ) ; try { if ( ! sysdb . existsCluster ( clusterName ) ) { OSchema schema = sysdb . getMetadata ( ) . getSchema ( ) ; OClass cls = schema . getClass ( className ) ; if ( cls != null ) { cls . addCluster ( clusterName ) ; } else { OLogManager . instance ( ) . error ( this , "createCluster() Class name %s does not exist" , null , className ) ; } } } finally { sysdb . close ( ) ; } } finally { if ( currentDB != null ) ODatabaseRecordThreadLocal . instance ( ) . set ( currentDB ) ; else ODatabaseRecordThreadLocal . instance ( ) . remove ( ) ; } }


Input: Remove all records belonging to specified cluster [CODESPLIT] public void freeCluster ( final int cid ) { final Set < ORID > toRemove = new HashSet < ORID > ( underlying . size ( ) / 2 ) ; final Set < ORID > keys = new HashSet < ORID > ( underlying . keys ( ) ) ; for ( final ORID id : keys ) if ( id . getClusterId ( ) == cid ) toRemove . add ( id ) ; for ( final ORID ridToRemove : toRemove ) underlying . remove ( ridToRemove ) ; }


Input: All operations running at cache initialization stage [CODESPLIT] public void startup ( ) { underlying . startup ( ) ; Orient . instance ( ) . getProfiler ( ) . registerHookValue ( profilerPrefix + "current" , "Number of entries in cache" , METRIC_TYPE . SIZE , new OProfilerHookValue ( ) { public Object getValue ( ) { return getSize ( ) ; } } , profilerMetadataPrefix + "current" ) ; }


Input: All operations running at cache destruction stage [CODESPLIT] public void shutdown ( ) { underlying . shutdown ( ) ; if ( Orient . instance ( ) . getProfiler ( ) != null ) { Orient . instance ( ) . getProfiler ( ) . unregisterHookValue ( profilerPrefix + "enabled" ) ; Orient . instance ( ) . getProfiler ( ) . unregisterHookValue ( profilerPrefix + "current" ) ; Orient . instance ( ) . getProfiler ( ) . unregisterHookValue ( profilerPrefix + "max" ) ; } }


Input: Result set with a single result ; [CODESPLIT] public static OScriptResultSet singleton ( Object entity , OScriptTransformer transformer ) { return new OScriptResultSet ( Collections . singletonList ( entity ) . iterator ( ) , transformer ) ; }


Input: Grant a permission to the resource . [CODESPLIT] public ORole grant ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific , final int iOperation ) { ORule rule = rules . get ( resourceGeneric ) ; if ( rule == null ) { rule = new ORule ( resourceGeneric , null , null ) ; rules . put ( resourceGeneric , rule ) ; } rule . grantAccess ( resourceSpecific , iOperation ) ; rules . put ( resourceGeneric , rule ) ; updateRolesDocumentContent ( ) ; return this ; }


Input: Revoke a permission to the resource . [CODESPLIT] public ORole revoke ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific , final int iOperation ) { if ( iOperation == PERMISSION_NONE ) return this ; ORule rule = rules . get ( resourceGeneric ) ; if ( rule == null ) { rule = new ORule ( resourceGeneric , null , null ) ; rules . put ( resourceGeneric , rule ) ; } rule . revokeAccess ( resourceSpecific , iOperation ) ; rules . put ( resourceGeneric , rule ) ; updateRolesDocumentContent ( ) ; return this ; }


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


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


Input:
Deletes the current record . [CODESPLIT] public boolean result ( final Object iRecord ) { final ORecordAbstract record = ( ( OIdentifiable ) iRecord ) . getRecord ( ) ; if ( record instanceof ODocument && compiledFilter != null && ! Boolean . TRUE . equals ( this . compiledFilter . evaluate ( record , ( ODocument ) record , getContext ( ) ) ) ) { return true ; } try { if ( record . getIdentity ( ) . isValid ( ) ) { if ( returning . equalsIgnoreCase ( "BEFORE" ) ) allDeletedRecords . add ( record ) ; // RESET VERSION TO DISABLE MVCC AVOIDING THE CONCURRENT EXCEPTION IF LOCAL CACHE IS NOT UPDATED
 //        ORecordInternal.setVersion(record, -1);
 if ( ! unsafe && record instanceof ODocument ) { // CHECK IF ARE VERTICES OR EDGES
 final OClass cls = ( ( ODocument ) record ) . getSchemaClass ( ) ; if ( cls != null ) { if ( cls . isSubClassOf ( "V" ) ) // FOUND VERTEX
 throw new OCommandExecutionException ( "'DELETE' command cannot delete vertices. Use 'DELETE VERTEX' command instead, or apply the 'UNSAFE' keyword to force it" ) ; else if ( cls . isSubClassOf ( "E" ) ) // FOUND EDGE
 throw new OCommandExecutionException ( "'DELETE' command cannot delete edges. Use 'DELETE EDGE' command instead, or apply the 'UNSAFE' keyword to force it" ) ; } } record . delete ( ) ; recordCount ++ ; return true ; } return false ; } finally { if ( lockStrategy . equalsIgnoreCase ( "RECORD" ) ) ( ( OAbstractPaginatedStorage ) getDatabase ( ) . getStorage ( ) ) . releaseWriteLock ( record . getIdentity ( ) ) ; } }


Input: add a step that transforms a normal OResult in a specific object that under setProperty () updates the actual OIdentifiable [CODESPLIT] private void convertToModifiableResult ( OUpdateExecutionPlan plan , OCommandContext ctx , boolean profilingEnabled ) { plan . chain ( new ConvertToUpdatableResultStep ( ctx , profilingEnabled ) ) ; }


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


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


Input: Binds parameters . [CODESPLIT] public void bindParameters ( final Map < Object , Object > iArgs ) { if ( parameterItems == null || iArgs == null || iArgs . size ( ) == 0 ) return ; for ( int i = 0 ; i < parameterItems . size ( ) ; i ++ ) { OSQLFilterItemParameter value = parameterItems . get ( i ) ; if ( "?" . equals ( value . getName ( ) ) ) { value . setValue ( iArgs . get ( i ) ) ; } else { value . setValue ( iArgs . get ( value . getName ( ) ) ) ; } } }


Input: Convert the item requested . [CODESPLIT] private void convert ( final int iIndex ) { if ( converted ) return ; Object o = list . get ( iIndex ) ; if ( o == null ) { o = serializedList . get ( iIndex ) ; list . set ( iIndex , OObjectEntitySerializer . deserializeFieldValue ( deserializeClass , o ) ) ; } }


Input: TODO refactor this method to receive the item . [CODESPLIT] protected Iterable < OResultInternal > traversePatternEdge ( OIdentifiable startingPoint , OCommandContext iCommandContext ) { Iterable possibleResults = null ; if ( this . item . getFilter ( ) != null ) { String alias = getEndpointAlias ( ) ; Object matchedNodes = iCommandContext . getVariable ( MatchPrefetchStep . PREFETCHED_MATCH_ALIAS_PREFIX + alias ) ; if ( matchedNodes != null ) { if ( matchedNodes instanceof Iterable ) { possibleResults = ( Iterable ) matchedNodes ; } else { possibleResults = Collections . singleton ( matchedNodes ) ; } } } Object prevCurrent = iCommandContext . getVariable ( "$current" ) ; iCommandContext . setVariable ( "$current" , startingPoint ) ; Object qR ; try { qR = this . item . getMethod ( ) . execute ( startingPoint , possibleResults , iCommandContext ) ; } finally { iCommandContext . setVariable ( "$current" , prevCurrent ) ; } if ( qR == null ) { return Collections . EMPTY_LIST ; } if ( qR instanceof OIdentifiable ) { return Collections . singleton ( new OResultInternal ( ( OIdentifiable ) qR ) ) ; } if ( qR instanceof Iterable ) { final Iterator < Object > iter = ( ( Iterable ) qR ) . iterator ( ) ; Iterable < OResultInternal > result = ( ) -> new Iterator < OResultInternal > ( ) { private OResultInternal nextElement ; @ Override public boolean hasNext ( ) { if ( nextElement == null ) { fetchNext ( ) ; } return nextElement != null ; } @ Override public OResultInternal next ( ) { if ( nextElement == null ) { fetchNext ( ) ; } if ( nextElement == null ) { throw new IllegalStateException ( ) ; } OResultInternal res = nextElement ; nextElement = null ; return res ; } public void fetchNext ( ) { while ( iter . hasNext ( ) ) { Object o = iter . next ( ) ; if ( o instanceof OIdentifiable ) { nextElement = new OResultInternal ( ( OIdentifiable ) o ) ; break ; } else if ( o instanceof OResultInternal ) { nextElement = ( OResultInternal ) o ; break ; } else if ( o == null ) { continue ; } else { throw new UnsupportedOperationException ( ) ; } } } } ; return result ; } return Collections . EMPTY_LIST ; }


Input: Convert the item requested . [CODESPLIT] private void convert ( final int iIndex ) { if ( converted ) return ; Object o = list . get ( iIndex ) ; if ( o == null ) { o = serializedList . get ( iIndex ) ; if ( o instanceof Number ) o = enumClass . getEnumConstants ( ) [ ( ( Number ) o ) . intValue ( ) ] ; else o = Enum . valueOf ( enumClass , o . toString ( ) ) ; list . set ( iIndex , ( TYPE ) o ) ; } }


Input:
Parses a string returning the closer type . Numbers by default are INTEGER if haven t decimal separator otherwise FLOAT . To treat all the number types numbers are postponed with a character that tells the type : b = byte s = short l = long f = float d = double t = date . [CODESPLIT] public static OType getType ( final String iValue ) { if ( iValue . length ( ) == 0 ) return null ; final char firstChar = iValue . charAt ( 0 ) ; if ( firstChar == ORID . PREFIX ) // RID
 return OType . LINK ; else if ( firstChar == ' ' || firstChar == ' ' ) return OType . STRING ; else if ( firstChar == OStringSerializerHelper . BINARY_BEGINEND ) return OType . BINARY ; else if ( firstChar == OStringSerializerHelper . EMBEDDED_BEGIN ) return OType . EMBEDDED ; else if ( firstChar == OStringSerializerHelper . LIST_BEGIN ) return OType . EMBEDDEDLIST ; else if ( firstChar == OStringSerializerHelper . SET_BEGIN ) return OType . EMBEDDEDSET ; else if ( firstChar == OStringSerializerHelper . MAP_BEGIN ) return OType . EMBEDDEDMAP ; else if ( firstChar == OStringSerializerHelper . CUSTOM_TYPE ) return OType . CUSTOM ; // BOOLEAN?
 if ( iValue . equalsIgnoreCase ( "true" ) || iValue . equalsIgnoreCase ( "false" ) ) return OType . BOOLEAN ; // NUMBER OR STRING?
 boolean integer = true ; for ( int index = 0 ; index < iValue . length ( ) ; ++ index ) { final char c = iValue . charAt ( index ) ; if ( c < ' ' || c > ' ' ) if ( ( index == 0 && ( c == ' ' || c == ' ' ) ) ) continue ; else if ( c == DECIMAL_SEPARATOR ) integer = false ; else { if ( index > 0 ) if ( ! integer && c == ' ' ) { // CHECK FOR SCIENTIFIC NOTATION
 if ( index < iValue . length ( ) ) { if ( iValue . charAt ( index + 1 ) == ' ' ) // JUMP THE DASH IF ANY (NOT MANDATORY)
 index ++ ; continue ; } } else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . FLOAT ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . DECIMAL ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . LONG ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . DOUBLE ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . BYTE ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . DATE ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . DATETIME ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . SHORT ; else if ( c == ' ' ) { //eg. 1e-06
 try { Double . parseDouble ( iValue ) ; return OType . DOUBLE ; } catch ( Exception ignore ) { return OType . STRING ; } } return OType . STRING ; } } if ( integer ) { // AUTO CONVERT TO LONG IF THE INTEGER IS TOO BIG
 final int numberLength = iValue . length ( ) ; if ( numberLength > MAX_INTEGER_DIGITS || ( numberLength == MAX_INTEGER_DIGITS && iValue . compareTo ( MAX_INTEGER_AS_STRING ) > 0 ) ) return OType . LONG ; return OType . INTEGER ; } // CHECK IF THE DECIMAL NUMBER IS A FLOAT OR DOUBLE
 final double dou = Double . parseDouble ( iValue ) ; if ( dou <= Float . MAX_VALUE && dou >= Float . MIN_VALUE && Double . toString ( dou ) . equals ( Float . toString ( ( float ) dou ) ) && new Double ( new Double ( dou ) . floatValue ( ) ) . doubleValue ( ) == dou ) { return OType . FLOAT ; } else if ( ! new Double ( dou ) . toString ( ) . equals ( iValue ) ) { return OType . DECIMAL ; } return OType . DOUBLE ; }


Input: Parses the field type char returning the closer type . Default is STRING . b = binary if iValue . length () > = 4 b = byte if iValue . length () < = 3 s = short l = long f = float d = double a = date t = datetime [CODESPLIT] public static OType getType ( final String iValue , final char iCharType ) { if ( iCharType == ' ' ) return OType . FLOAT ; else if ( iCharType == ' ' ) return OType . DECIMAL ; else if ( iCharType == ' ' ) return OType . LONG ; else if ( iCharType == ' ' ) return OType . DOUBLE ; else if ( iCharType == ' ' ) { if ( iValue . length ( ) >= 1 && iValue . length ( ) <= 3 ) return OType . BYTE ; else return OType . BINARY ; } else if ( iCharType == ' ' ) return OType . DATE ; else if ( iCharType == ' ' ) return OType . DATETIME ; else if ( iCharType == ' ' ) return OType . SHORT ; else if ( iCharType == ' ' ) return OType . EMBEDDEDSET ; else if ( iCharType == ' ' ) return OType . LINKBAG ; else if ( iCharType == ' ' ) return OType . LINKLIST ; else if ( iCharType == ' ' ) return OType . LINKMAP ; else if ( iCharType == ' ' ) return OType . LINK ; else if ( iCharType == ' ' ) return OType . LINKSET ; else if ( iCharType == ' ' ) return OType . LINK ; else if ( iCharType == ' ' ) return OType . CUSTOM ; return OType . STRING ; }


Input:
Parses a string returning the value with the closer type . Numbers by default are INTEGER if haven t decimal separator otherwise FLOAT . To treat all the number types numbers are postponed with a character that tells the type : b = byte s = short l = long f = float d = double t = date . If starts with # it s a RecordID . Most of the code is equals to getType () but has been copied to speed - up it . [CODESPLIT] public static Object getTypeValue ( final String iValue ) { if ( iValue == null || iValue . equalsIgnoreCase ( "NULL" ) ) return null ; if ( iValue . length ( ) == 0 ) return "" ; if ( iValue . length ( ) > 1 ) if ( iValue . charAt ( 0 ) == ' ' && iValue . charAt ( iValue . length ( ) - 1 ) == ' ' ) // STRING
 return OStringSerializerHelper . decode ( iValue . substring ( 1 , iValue . length ( ) - 1 ) ) ; else if ( iValue . charAt ( 0 ) == OStringSerializerHelper . BINARY_BEGINEND && iValue . charAt ( iValue . length ( ) - 1 ) == OStringSerializerHelper . BINARY_BEGINEND ) // STRING
 return OStringSerializerHelper . getBinaryContent ( iValue ) ; else if ( iValue . charAt ( 0 ) == OStringSerializerHelper . LIST_BEGIN && iValue . charAt ( iValue . length ( ) - 1 ) == OStringSerializerHelper . LIST_END ) { // LIST
 final ArrayList < String > coll = new ArrayList < String > ( ) ; OStringSerializerHelper . getCollection ( iValue , 0 , coll , OStringSerializerHelper . LIST_BEGIN , OStringSerializerHelper . LIST_END , OStringSerializerHelper . COLLECTION_SEPARATOR ) ; return coll ; } else if ( iValue . charAt ( 0 ) == OStringSerializerHelper . SET_BEGIN && iValue . charAt ( iValue . length ( ) - 1 ) == OStringSerializerHelper . SET_END ) { // SET
 final Set < String > coll = new HashSet < String > ( ) ; OStringSerializerHelper . getCollection ( iValue , 0 , coll , OStringSerializerHelper . SET_BEGIN , OStringSerializerHelper . SET_END , OStringSerializerHelper . COLLECTION_SEPARATOR ) ; return coll ; } else if ( iValue . charAt ( 0 ) == OStringSerializerHelper . MAP_BEGIN && iValue . charAt ( iValue . length ( ) - 1 ) == OStringSerializerHelper . MAP_END ) { // MAP
 return OStringSerializerHelper . getMap ( iValue ) ; } if ( iValue . charAt ( 0 ) == ORID . PREFIX ) // RID
 return new ORecordId ( iValue ) ; boolean integer = true ; char c ; boolean stringStarBySign = false ; for ( int index = 0 ; index < iValue . length ( ) ; ++ index ) { c = iValue . charAt ( index ) ; if ( c < ' ' || c > ' ' ) { if ( ( index == 0 && ( c == ' ' || c == ' ' ) ) ) { stringStarBySign = true ; continue ; } else if ( c == DECIMAL_SEPARATOR ) integer = false ; else { if ( index > 0 ) { if ( ! integer && c == ' ' ) { // CHECK FOR SCIENTIFIC NOTATION
 if ( index < iValue . length ( ) ) index ++ ; if ( iValue . charAt ( index ) == ' ' ) continue ; } final String v = iValue . substring ( 0 , index ) ; if ( c == ' ' ) return new Float ( v ) ; else if ( c == ' ' ) return new BigDecimal ( v ) ; else if ( c == ' ' ) return new Long ( v ) ; else if ( c == ' ' ) return new Double ( v ) ; else if ( c == ' ' ) return new Byte ( v ) ; else if ( c == ' ' || c == ' ' ) return new Date ( Long . parseLong ( v ) ) ; else if ( c == ' ' ) return new Short ( v ) ; } return iValue ; } } else if ( stringStarBySign ) { stringStarBySign = false ; } } if ( stringStarBySign ) return iValue ; if ( integer ) { try { return new Integer ( iValue ) ; } catch ( NumberFormatException ignore ) { return new Long ( iValue ) ; } } else if ( "NaN" . equals ( iValue ) || "Infinity" . equals ( iValue ) ) // NaN and Infinity CANNOT BE MANAGED BY BIG-DECIMAL TYPE
 return new Double ( iValue ) ; else return new BigDecimal ( iValue ) ; }


Input: Increments the popularity of the element if it does not exceed the maximum ( 15 ) . The popularity of all elements will be periodically down sampled when the observed events exceeds a threshold . This process provides a frequency aging to allow expired long term entries to fade away . [CODESPLIT] @ Override public void increment ( int hash ) { hash = spread ( hash ) ; final int start = ( hash & 3 ) << 2 ; // Loop unrolling improves throughput by 5m ops/s final int index0 = indexOf ( hash , 0 ) ; final int index1 = indexOf ( hash , 1 ) ; final int index2 = indexOf ( hash , 2 ) ; final int index3 = indexOf ( hash , 3 ) ; boolean added = incrementAt ( index0 , start ) ; added |= incrementAt ( index1 , start + 1 ) ; added |= incrementAt ( index2 , start + 2 ) ; added |= incrementAt ( index3 , start + 3 ) ; if ( added && ( ++ size == sampleSize ) ) { reset ( ) ; } }


Input: Increments the specified counter by 1 if it is not already at the maximum value ( 15 ) . [CODESPLIT] private boolean incrementAt ( final int i , final int j ) { final int offset = j << 2 ; final long mask = ( 0xf L << offset ) ; if ( ( table [ i ] & mask ) != mask ) { table [ i ] += ( 1L << offset ) ; return true ; } return false ; }


Input: Reduces every counter by half of its original value . [CODESPLIT] private void reset ( ) { int count = 0 ; for ( int i = 0 ; i < table . length ; i ++ ) { count += Long . bitCount ( table [ i ] & ONE_MASK ) ; table [ i ] = ( table [ i ] >>> 1 ) & RESET_MASK ; } size = ( size >>> 1 ) - ( count >>> 2 ) ; }


Input: Returns the table index for the counter at the specified depth . [CODESPLIT] private int indexOf ( final int item , final int i ) { long hash = SEED [ i ] * item ; hash += hash >> 32 ; return ( ( int ) hash ) & tableMask ; }


Input: Applies a supplemental hash function to a given hashCode which defends against poor quality hash functions . [CODESPLIT] private int spread ( int x ) { x = ( ( x >>> 16 ) ^ x ) * 0x45d9f3b ; x = ( ( x >>> 16 ) ^ x ) * randomSeed ; return ( x >>> 16 ) ^ x ; }


Input: Creates an index on this property . Indexes speed up queries but slow down insert and update operations . For massive inserts we suggest to remove the index make the massive insert and recreate it . [CODESPLIT] public OIndex < ? > createIndex ( final String iType ) { acquireSchemaReadLock ( ) ; try { return owner . createIndex ( getFullName ( ) , iType , globalRef . getName ( ) ) ; } finally { releaseSchemaReadLock ( ) ; } }


Input: Remove the index on property [CODESPLIT] @ Deprecated public OPropertyImpl dropIndexes ( ) { getDatabase ( ) . checkSecurity ( ORule . ResourceGeneric . SCHEMA , ORole . PERMISSION_DELETE ) ; acquireSchemaReadLock ( ) ; try { final OIndexManager indexManager = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) ; final ArrayList < OIndex < ? > > relatedIndexes = new ArrayList < OIndex < ? > > ( ) ; for ( final OIndex < ? > index : indexManager . getClassIndexes ( owner . getName ( ) ) ) { final OIndexDefinition definition = index . getDefinition ( ) ; if ( OCollections . indexOf ( definition . getFields ( ) , globalRef . getName ( ) , new OCaseInsentiveComparator ( ) ) > - 1 ) { if ( definition instanceof OPropertyIndexDefinition ) { relatedIndexes . add ( index ) ; } else { throw new IllegalArgumentException ( "This operation applicable only for property indexes. " + index . getName ( ) + " is " + index . getDefinition ( ) ) ; } } } for ( final OIndex < ? > index : relatedIndexes ) getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( index . getName ( ) ) ; return this ; } finally { releaseSchemaReadLock ( ) ; } }


Input: Returns the first index defined for the property . [CODESPLIT] @ Deprecated public OIndex < ? > getIndex ( ) { acquireSchemaReadLock ( ) ; try { Set < OIndex < ? > > indexes = owner . getInvolvedIndexes ( globalRef . getName ( ) ) ; if ( indexes != null && ! indexes . isEmpty ( ) ) return indexes . iterator ( ) . next ( ) ; return null ; } finally { releaseSchemaReadLock ( ) ; } }


Input: Returns the linked class in lazy mode because while unmarshalling the class could be not loaded yet . [CODESPLIT] public OClass getLinkedClass ( ) { acquireSchemaReadLock ( ) ; try { if ( linkedClass == null && linkedClassName != null ) linkedClass = owner . owner . getClass ( linkedClassName ) ; return linkedClass ; } finally { releaseSchemaReadLock ( ) ; } }


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


Input: Add new key value to the list of already registered values . <p > If passed in value is { @link OCompositeKey } itself then its values will be copied in current index . But key itself will not be added . [CODESPLIT] public void addKey ( final Object key ) { if ( key instanceof OCompositeKey ) { final OCompositeKey compositeKey = ( OCompositeKey ) key ; for ( final Object inKey : compositeKey . keys ) { addKey ( inKey ) ; } } else { keys . add ( key ) ; } }


Input: Create a new index . <p > May require quite a long time if big amount of data should be indexed . [CODESPLIT] public OIndex < ? > createIndex ( ODatabaseDocumentInternal database , final String iName , String type , final OIndexDefinition indexDefinition , final int [ ] clusterIdsToIndex , OProgressListener progressListener , ODocument metadata , String algorithm ) { if ( database . getTransaction ( ) . isActive ( ) ) throw new IllegalStateException ( "Cannot create a new index inside a transaction" ) ; final Character c = OSchemaShared . checkFieldNameIfValid ( iName ) ; if ( c != null ) throw new IllegalArgumentException ( "Invalid index name '" + iName + "'. Character '" + c + "' is invalid" ) ; if ( indexDefinition == null ) { throw new IllegalArgumentException ( "Index definition cannot be null" ) ; } final Locale locale = getServerLocale ( ) ; type = type . toUpperCase ( locale ) ; if ( algorithm == null ) { algorithm = OIndexes . chooseDefaultIndexAlgorithm ( type ) ; } final String valueContainerAlgorithm = chooseContainerAlgorithm ( type ) ; final OIndexInternal < ? > index ; acquireExclusiveLock ( ) ; try { if ( indexes . containsKey ( iName ) ) throw new OIndexException ( "Index with name " + iName + " already exists." ) ; // manual indexes are always durable if ( clusterIdsToIndex == null || clusterIdsToIndex . length == 0 ) { if ( metadata == null ) metadata = new ODocument ( ) . setTrackingChanges ( false ) ; final Object durable = metadata . field ( "durableInNonTxMode" ) ; if ( ! ( durable instanceof Boolean ) ) metadata . field ( "durableInNonTxMode" , true ) ; if ( metadata . field ( "trackMode" ) == null ) metadata . field ( "trackMode" , "FULL" ) ; } index = OIndexes . createIndex ( getStorage ( ) , iName , type , algorithm , valueContainerAlgorithm , metadata , - 1 ) ; if ( progressListener == null ) // ASSIGN DEFAULT PROGRESS LISTENER progressListener = new OIndexRebuildOutputListener ( index ) ; final Set < String > clustersToIndex = findClustersByIds ( clusterIdsToIndex , database ) ; Object ignoreNullValues = metadata == null ? null : metadata . field ( "ignoreNullValues" ) ; if ( Boolean . TRUE . equals ( ignoreNullValues ) ) { indexDefinition . setNullValuesIgnored ( true ) ; } else if ( Boolean . FALSE . equals ( ignoreNullValues ) ) { indexDefinition . setNullValuesIgnored ( false ) ; } else { indexDefinition . setNullValuesIgnored ( database . getConfiguration ( ) . getValueAsBoolean ( OGlobalConfiguration . INDEX_IGNORE_NULL_VALUES_DEFAULT ) ) ; } // decide which cluster to use ("index" - for automatic and "manindex" for manual) final String clusterName = indexDefinition . getClassName ( ) != null ? defaultClusterName : manualClusterName ; index . create ( iName , indexDefinition , clusterName , clustersToIndex , true , progressListener ) ; addIndexInternal ( index ) ; if ( metadata != null ) { final ODocument config = index . getConfiguration ( ) ; config . field ( "metadata" , metadata , OType . EMBEDDED ) ; } setDirty ( ) ; save ( ) ; } finally { releaseExclusiveLock ( ) ; } notifyInvolvedClasses ( database , clusterIdsToIndex ) ; return preProcessBeforeReturn ( database , index ) ; }


Input: Binds POJO to ODocument . [CODESPLIT] @ Override public ODocument toStream ( ) { internalAcquireExclusiveLock ( ) ; try { document . setInternalStatus ( ORecordElement . STATUS . UNMARSHALLING ) ; try { final OTrackedSet < ODocument > indexes = new OTrackedSet <> ( document ) ; for ( final OIndex < ? > i : this . indexes . values ( ) ) { indexes . add ( ( ( OIndexInternal < ? > ) i ) . updateConfiguration ( ) ) ; } document . field ( CONFIG_INDEXES , indexes , OType . EMBEDDEDSET ) ; } finally { document . setInternalStatus ( ORecordElement . STATUS . LOADED ) ; } document . setDirty ( ) ; return document ; } finally { internalReleaseExclusiveLock ( ) ; } }


Input: Sets the server role between MASTER ( default ) and REPLICA . [CODESPLIT] public void setServerRole ( final String iServerName , final ROLES role ) { synchronized ( configuration ) { ODocument servers = configuration . field ( SERVERS ) ; if ( servers == null ) { servers = new ODocument ( ) ; configuration . field ( SERVERS , servers , OType . EMBEDDED ) ; } servers . field ( iServerName , role ) ; incrementVersion ( ) ; } }


Input: Adds a server in the configuration . It replaces all the tags &lt ; NEW_NODE&gt ; with the new server name<br > NOTE : It must be executed in distributed database lock . [CODESPLIT] public List < String > addNewNodeInServerList ( final String iNode ) { synchronized ( configuration ) { final List < String > changedPartitions = new ArrayList < String > ( ) ; // ADD THE NODE IN CONFIGURATION. LOOK FOR $newNode TAG for ( String clusterName : getClusterNames ( ) ) { final List < String > partitions = getClusterConfiguration ( clusterName ) . field ( SERVERS ) ; if ( partitions != null ) { final int newNodePos = partitions . indexOf ( OModifiableDistributedConfiguration . NEW_NODE_TAG ) ; if ( newNodePos > - 1 && ! partitions . contains ( iNode ) ) { partitions . add ( newNodePos , iNode ) ; changedPartitions . add ( clusterName ) ; } } } if ( ! changedPartitions . isEmpty ( ) ) { // INCREMENT VERSION incrementVersion ( ) ; if ( ! getRegisteredServers ( ) . contains ( iNode ) ) { if ( getNewNodeStrategy ( ) == NEW_NODE_STRATEGIES . STATIC ) { // REGISTER THE SERVER AS STATIC AND INCREMENT VERSION setServerRole ( iNode , getServerRole ( "*" ) ) ; } } return changedPartitions ; } } return null ; }


Input: Sets the server as owner for the given cluster . The owner server is the first in server list . <br > NOTE : It must be executed in distributed database lock . [CODESPLIT] public void setServerOwner ( final String iClusterName , final String iServerName ) { if ( iClusterName == null ) throw new IllegalArgumentException ( "cluster name cannot be null" ) ; synchronized ( configuration ) { final ODocument clusters = configuration . field ( CLUSTERS ) ; ODocument cluster = clusters . field ( iClusterName ) ; if ( cluster == null ) // CREATE IT cluster = createCluster ( iClusterName ) ; else { // CHECK IF THE OWNER IS ALREADY CONFIGURED final String owner = cluster . field ( OWNER ) ; if ( owner != null && ! iServerName . equalsIgnoreCase ( owner ) ) throw new ODistributedException ( "Cannot overwrite ownership of cluster '" + iClusterName + "' to the server '" + iServerName + "', because server '" + owner + "' was already configured as owner" ) ; } List < String > serverList = getClusterConfiguration ( iClusterName ) . field ( SERVERS ) ; if ( serverList == null ) { serverList = initClusterServers ( cluster ) ; } if ( ! serverList . isEmpty ( ) && serverList . get ( 0 ) . equals ( iServerName ) ) // ALREADY OWNER return ; // REMOVE THE NODE IF ANY boolean removed = false ; for ( Iterator < String > it = serverList . iterator ( ) ; it . hasNext ( ) ; ) { if ( it . next ( ) . equals ( iServerName ) ) { it . remove ( ) ; removed = true ; break ; } } if ( ! removed ) throw new ODistributedException ( "Cannot set ownership of cluster '" + iClusterName + "' to the server '" + iServerName + "', because the server has no that cluster (sharding)" ) ; // ADD THE NODE AS FIRST OF THE LIST = MASTER serverList . add ( 0 , iServerName ) ; incrementVersion ( ) ; } }


Input: Removes a server from the list . <br > NOTE : It must be executed in distributed database lock . [CODESPLIT] public List < String > removeServer ( final String iNode ) { synchronized ( configuration ) { final List < String > changedPartitions = new ArrayList < String > ( ) ; for ( String clusterName : getClusterNames ( ) ) { final Collection < String > nodes = getClusterConfiguration ( clusterName ) . field ( SERVERS ) ; if ( nodes != null ) { for ( String node : nodes ) { if ( node . equals ( iNode ) ) { // FOUND: REMOVE IT nodes . remove ( node ) ; changedPartitions . add ( clusterName ) ; break ; } } } } if ( ! changedPartitions . isEmpty ( ) ) { incrementVersion ( ) ; return changedPartitions ; } } return null ; }


Input: Set a server offline . It assures the offline server is never on top of the list . <br > NOTE : It must be executed in distributed database lock . [CODESPLIT] public List < String > setServerOffline ( final String iNode , final String newLockManagerServer ) { final List < String > changedPartitions = new ArrayList < String > ( ) ; final String [ ] clusters = getClusterNames ( ) ; synchronized ( configuration ) { for ( String clusterName : clusters ) { final List < String > nodes = getClusterConfiguration ( clusterName ) . field ( SERVERS ) ; if ( nodes != null && nodes . size ( ) > 1 ) { for ( String node : nodes ) { if ( node . equals ( iNode ) ) { // FOUND: PUT THE NODE AT THE END (BEFORE ANY TAG <NEW_NODE>) nodes . remove ( node ) ; final boolean newNodeRemoved = nodes . remove ( NEW_NODE_TAG ) ; nodes . add ( node ) ; if ( newNodeRemoved ) // REINSERT NEW NODE TAG AT THE END nodes . add ( NEW_NODE_TAG ) ; if ( newLockManagerServer != null ) { // ASSURE THE NEW LOCK MANAGER IS THE FIRST IN THE LIST if ( nodes . remove ( newLockManagerServer ) ) nodes . add ( 0 , newLockManagerServer ) ; } changedPartitions . add ( clusterName ) ; break ; } } } } if ( ! changedPartitions . isEmpty ( ) ) { incrementVersion ( ) ; return changedPartitions ; } } return null ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public void configure ( OStorage iStorage , int iId , String iClusterName , Object ... iParameters ) { id = iId ; name = iClusterName ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public void configure ( OStorage iStorage , OStorageClusterConfiguration iConfig ) throws IOException { id = iConfig . getId ( ) ; name = iConfig . getName ( ) ; }


Input: Remove the current event listener . [CODESPLIT] protected void removeListener ( final ORecordListener listener ) { if ( _listeners != null ) { _listeners . remove ( listener ) ; if ( _listeners . isEmpty ( ) ) _listeners = null ; } }


Input: Creates a distributed database instance if not defined yet . [CODESPLIT] public ODistributedDatabaseImpl registerDatabase ( final String iDatabaseName , ODistributedConfiguration cfg ) { final ODistributedDatabaseImpl ddb = databases . get ( iDatabaseName ) ; if ( ddb != null ) return ddb ; return new ODistributedDatabaseImpl ( manager , this , iDatabaseName , cfg , manager . getServerInstance ( ) ) ; }


Input: Not synchronized it s called when a message arrives [CODESPLIT] public void dispatchResponseToThread ( final ODistributedResponse response ) { try { final long msgId = response . getRequestId ( ) . getMessageId ( ) ; // GET ASYNCHRONOUS MSG MANAGER IF ANY final ODistributedResponseManager asynchMgr = responsesByRequestIds . get ( msgId ) ; if ( asynchMgr == null ) { if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , manager . getLocalNodeName ( ) , response . getExecutorNodeName ( ) , DIRECTION . IN , "received response for message %d after the timeout (%dms)" , msgId , OGlobalConfiguration . DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT . getValueAsLong ( ) ) ; } else if ( asynchMgr . collectResponse ( response ) ) { // ALL RESPONSE RECEIVED, REMOVE THE RESPONSE MANAGER WITHOUT WAITING THE PURGE THREAD REMOVE THEM FOR TIMEOUT responsesByRequestIds . remove ( msgId ) ; } } finally { Orient . instance ( ) . getProfiler ( ) . updateCounter ( "distributed.node.msgReceived" , "Number of replication messages received in current node" , + 1 , "distributed.node.msgReceived" ) ; Orient . instance ( ) . getProfiler ( ) . updateCounter ( "distributed.node." + response . getExecutorNodeName ( ) + ".msgReceived" , "Number of replication messages received in current node from a node" , + 1 , "distributed.node.*.msgReceived" ) ; } }


Input: Removes a response manager because in timeout . [CODESPLIT] public void timeoutRequest ( final long msgId ) { final ODistributedResponseManager asynchMgr = responsesByRequestIds . remove ( msgId ) ; if ( asynchMgr != null ) asynchMgr . timeout ( ) ; }


Input: { [CODESPLIT] public void internalCreate ( OrientDBConfig config , OSharedContext ctx ) { this . sharedContext = ctx ; this . status = STATUS . OPEN ; // THIS IF SHOULDN'T BE NEEDED, CREATE HAPPEN ONLY IN EMBEDDED applyAttributes ( config ) ; applyListeners ( config ) ; metadata = new OMetadataDefault ( this ) ; installHooksEmbedded ( ) ; createMetadata ( ctx ) ; if ( this . getMetadata ( ) . getCommandCache ( ) . isEnabled ( ) ) registerHook ( new OCommandCacheHook ( this ) , ORecordHook . HOOK_POSITION . REGULAR ) ; }


Input: Returns a copy of current database if it s open . The returned instance can be used by another thread without affecting current instance . The database copy is not set in thread local . [CODESPLIT] public ODatabaseDocumentInternal copy ( ) { ODatabaseDocumentEmbedded database = new ODatabaseDocumentEmbedded ( getSharedContext ( ) . getStorage ( ) ) ; database . init ( config , this . sharedContext ) ; String user ; if ( getUser ( ) != null ) { user = getUser ( ) . getName ( ) ; } else { user = null ; } database . internalOpen ( user , null , false ) ; database . callOnOpenListeners ( ) ; this . activateOnCurrentThread ( ) ; return database ; }


Input: This method is internal it can be subject to signature change or be removed do not use . [CODESPLIT] public void executeDeleteRecord ( OIdentifiable record , final int iVersion , final boolean iRequired , final OPERATION_MODE iMode , boolean prohibitTombstones ) { checkOpenness ( ) ; checkIfActive ( ) ; final ORecordId rid = ( ORecordId ) record . getIdentity ( ) ; if ( rid == null ) throw new ODatabaseException ( "Cannot delete 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 ; record = record . getRecord ( ) ; if ( record == null ) return ; final OMicroTransaction microTx = beginMicroTransaction ( ) ; try { microTx . deleteRecord ( record . getRecord ( ) , iMode ) ; } catch ( Exception e ) { endMicroTransaction ( false ) ; throw e ; } endMicroTransaction ( true ) ; return ; }


Input: This method is internal it can be subject to signature change or be removed do not use . [CODESPLIT] public < RET extends ORecord > RET executeReadRecord ( final ORecordId rid , ORecord iRecord , final int recordVersion , final String fetchPlan , final boolean ignoreCache , final boolean iUpdateCache , final boolean loadTombstones , final OStorage . LOCKING_STRATEGY lockingStrategy , RecordReader recordReader ) { checkOpenness ( ) ; checkIfActive ( ) ; getMetadata ( ) . makeThreadLocalSchemaSnapshot ( ) ; ORecordSerializationContext . pushContext ( ) ; try { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , getClusterNameById ( rid . getClusterId ( ) ) ) ; // either regular or micro tx must be active or both inactive assert ! ( getTransaction ( ) . isActive ( ) && ( microTransaction != null && microTransaction . isActive ( ) ) ) ; // SEARCH IN LOCAL TX ORecord record = getTransaction ( ) . getRecord ( rid ) ; if ( record == OBasicTransaction . DELETED_RECORD ) // DELETED IN TX return null ; if ( record == null ) { if ( microTransaction != null && microTransaction . isActive ( ) ) { record = microTransaction . getRecord ( rid ) ; if ( record == OBasicTransaction . DELETED_RECORD ) return null ; } } if ( record == null && ! ignoreCache ) // SEARCH INTO THE CACHE record = getLocalCache ( ) . findRecord ( rid ) ; if ( record != null ) { if ( iRecord != null ) { iRecord . fromStream ( record . toStream ( ) ) ; ORecordInternal . setVersion ( iRecord , record . getVersion ( ) ) ; record = iRecord ; } OFetchHelper . checkFetchPlanValid ( fetchPlan ) ; if ( beforeReadOperations ( record ) ) return null ; if ( record . getInternalStatus ( ) == ORecordElement . STATUS . NOT_LOADED ) record . reload ( ) ; if ( lockingStrategy == OStorage . LOCKING_STRATEGY . KEEP_SHARED_LOCK ) { OLogManager . instance ( ) . warn ( this , "You use deprecated record locking strategy: %s it may lead to deadlocks " + lockingStrategy ) ; record . lock ( false ) ; } else if ( lockingStrategy == OStorage . LOCKING_STRATEGY . KEEP_EXCLUSIVE_LOCK ) { OLogManager . instance ( ) . warn ( this , "You use deprecated record locking strategy: %s it may lead to deadlocks " + lockingStrategy ) ; record . lock ( true ) ; } afterReadOperations ( record ) ; if ( record instanceof ODocument ) ODocumentInternal . checkClass ( ( ODocument ) record , this ) ; return ( RET ) record ; } final ORawBuffer recordBuffer ; if ( ! rid . isValid ( ) ) recordBuffer = null ; else { OFetchHelper . checkFetchPlanValid ( fetchPlan ) ; int version ; if ( iRecord != null ) version = iRecord . getVersion ( ) ; else version = recordVersion ; recordBuffer = recordReader . readRecord ( getStorage ( ) , rid , fetchPlan , ignoreCache , version ) ; } if ( recordBuffer == null ) return null ; if ( iRecord == null || ORecordInternal . getRecordType ( iRecord ) != recordBuffer . recordType ) // NO SAME RECORD TYPE: CAN'T REUSE OLD ONE BUT CREATE A NEW ONE FOR IT iRecord = Orient . instance ( ) . getRecordFactoryManager ( ) . newInstance ( recordBuffer . recordType , rid . getClusterId ( ) , this ) ; ORecordInternal . setRecordSerializer ( iRecord , getSerializer ( ) ) ; ORecordInternal . fill ( iRecord , rid , recordBuffer . version , recordBuffer . buffer , false , this ) ; if ( iRecord instanceof ODocument ) ODocumentInternal . checkClass ( ( ODocument ) iRecord , this ) ; if ( ORecordVersionHelper . isTombstone ( iRecord . getVersion ( ) ) ) return ( RET ) iRecord ; if ( beforeReadOperations ( iRecord ) ) return null ; iRecord . fromStream ( recordBuffer . buffer ) ; afterReadOperations ( iRecord ) ; if ( iUpdateCache ) getLocalCache ( ) . updateRecord ( iRecord ) ; return ( RET ) iRecord ; } catch ( OOfflineClusterException t ) { throw t ; } catch ( ORecordNotFoundException t ) { throw t ; } catch ( Exception t ) { if ( rid . isTemporary ( ) ) throw OException . wrapException ( new ODatabaseException ( "Error on retrieving record using temporary RID: " + rid ) , t ) ; else throw OException . wrapException ( new ODatabaseException ( "Error on retrieving record " + rid + " (cluster: " + getStorage ( ) . getPhysicalClusterNameById ( rid . getClusterId ( ) ) + ")" ) , t ) ; } finally { ORecordSerializationContext . pullContext ( ) ; getMetadata ( ) . clearThreadLocalSchemaSnapshot ( ) ; } }


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


Input: Notify collection that changes has been saved . Converts to non embedded implementation if needed . <p > WARNING! Method is for internal usage . [CODESPLIT] public void notifySaved ( OBonsaiCollectionPointer newPointer ) { if ( newPointer . isValid ( ) ) { if ( isEmbedded ( ) ) { replaceWithSBTree ( newPointer ) ; } else { ( ( OSBTreeRidBag ) delegate ) . setCollectionPointer ( newPointer ) ; ( ( OSBTreeRidBag ) delegate ) . clearChanges ( ) ; } } }


Input: IMPORTANT! Only for internal usage . [CODESPLIT] public boolean tryMerge ( final ORidBag otherValue , boolean iMergeSingleItemsOfMultiValueFields ) { if ( ! isEmbedded ( ) && ! otherValue . isEmbedded ( ) ) { final OSBTreeRidBag thisTree = ( OSBTreeRidBag ) delegate ; final OSBTreeRidBag otherTree = ( OSBTreeRidBag ) otherValue . delegate ; if ( thisTree . getCollectionPointer ( ) . equals ( otherTree . getCollectionPointer ( ) ) ) { thisTree . mergeChanges ( otherTree ) ; uuid = otherValue . uuid ; return true ; } } else if ( iMergeSingleItemsOfMultiValueFields ) { final Iterator < OIdentifiable > iter = otherValue . rawIterator ( ) ; while ( iter . hasNext ( ) ) { final OIdentifiable value = iter . next ( ) ; if ( value != null ) { final Iterator < OIdentifiable > localIter = rawIterator ( ) ; boolean found = false ; while ( localIter . hasNext ( ) ) { final OIdentifiable v = localIter . next ( ) ; if ( value . equals ( v ) ) { found = true ; break ; } } if ( ! found ) add ( value ) ; } } return true ; } return false ; }


Input: Silently replace delegate by tree implementation . [CODESPLIT] private void replaceWithSBTree ( OBonsaiCollectionPointer pointer ) { delegate . requestDelete ( ) ; final OSBTreeRidBag treeBag = new OSBTreeRidBag ( ) ; treeBag . setCollectionPointer ( pointer ) ; treeBag . setOwner ( delegate . getOwner ( ) ) ; for ( OMultiValueChangeListener < OIdentifiable , OIdentifiable > listener : delegate . getChangeListeners ( ) ) treeBag . addChangeListener ( listener ) ; delegate = treeBag ; }


Input: Manages cross compiler compatibility issues . [CODESPLIT] public static Object transformResult ( Object result ) { if ( java8MethodIsArray == null || ! ( result instanceof Map ) ) { return result ; } // PATCH BY MAT ABOUT NASHORN RETURNING VALUE FOR ARRAYS. try { if ( ( Boolean ) java8MethodIsArray . invoke ( result ) ) { List < ? > partial = new ArrayList ( ( ( Map ) result ) . values ( ) ) ; List < Object > finalResult = new ArrayList < Object > ( ) ; for ( Object o : partial ) { finalResult . add ( transformResult ( o ) ) ; } return finalResult ; } else { Map < Object , Object > mapResult = ( Map ) result ; List < Object > keys = new ArrayList < Object > ( mapResult . keySet ( ) ) ; for ( Object key : keys ) { mapResult . put ( key , transformResult ( mapResult . get ( key ) ) ) ; } return mapResult ; } } catch ( Exception e ) { OLogManager . instance ( ) . error ( OCommandExecutorUtility . class , "" , e ) ; } return result ; }


Input: Execute the CREATE CLUSTER . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clusterName == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseDocument database = getDatabase ( ) ; final int clusterId = database . getClusterIdByName ( clusterName ) ; if ( clusterId > - 1 ) throw new OCommandSQLParsingException ( "Cluster '" + clusterName + "' already exists" ) ; if ( blob ) { if ( requestedId == - 1 ) { return database . addBlobCluster ( clusterName ) ; } else { throw new OCommandExecutionException ( "Request id not supported by blob cluster creation." ) ; } } else { if ( requestedId == - 1 ) { return database . addCluster ( clusterName ) ; } else { return database . addCluster ( clusterName , requestedId , null ) ; } } }


Input: Closes all the databases . [CODESPLIT] public void close ( ) { lock ( ) ; try { if ( this . evictionTask != null ) { this . evictionTask . cancel ( ) ; } for ( Entry < String , OReentrantResourcePool < String , DB > > pool : pools . entrySet ( ) ) { for ( DB db : pool . getValue ( ) . getResources ( ) ) { pool . getValue ( ) . close ( ) ; try { OLogManager . instance ( ) . debug ( this , "Closing pooled database '%s'..." , db . getName ( ) ) ; ( ( ODatabasePooled ) db ) . forceClose ( ) ; OLogManager . instance ( ) . debug ( this , "OK" , db . getName ( ) ) ; } catch ( Exception e ) { OLogManager . instance ( ) . debug ( this , "Error: %d" , e . toString ( ) ) ; } } } } finally { unlock ( ) ; } }


Input: Removes from memory the pool associated to the closed storage . This avoids pool open against closed storages . [CODESPLIT] public void onStorageUnregistered ( final OStorage iStorage ) { final String storageURL = iStorage . getURL ( ) ; lock ( ) ; try { Set < String > poolToClose = null ; for ( Entry < String , OReentrantResourcePool < String , DB > > e : pools . entrySet ( ) ) { final int pos = e . getKey ( ) . indexOf ( "@" ) ; final String dbName = e . getKey ( ) . substring ( pos + 1 ) ; if ( storageURL . equals ( dbName ) ) { if ( poolToClose == null ) poolToClose = new HashSet < String > ( ) ; poolToClose . add ( e . getKey ( ) ) ; } } if ( poolToClose != null ) for ( String pool : poolToClose ) remove ( pool ) ; } finally { unlock ( ) ; } }


Input: Iterates on all factories and append all function names . [CODESPLIT] public static Set < String > getFunctionNames ( ) { final Set < String > types = new HashSet < String > ( ) ; final Iterator < OSQLFunctionFactory > ite = getFunctionFactories ( ) ; while ( ite . hasNext ( ) ) { types . addAll ( ite . next ( ) . getFunctionNames ( ) ) ; } return types ; }


Input: Iterates on all factories and append all collate names . [CODESPLIT] public static Set < String > getCollateNames ( ) { final Set < String > types = new HashSet < String > ( ) ; final Iterator < OCollateFactory > ite = getCollateFactories ( ) ; while ( ite . hasNext ( ) ) { types . addAll ( ite . next ( ) . getNames ( ) ) ; } return types ; }


Input: Iterates on all factories and append all command names . [CODESPLIT] public static Set < String > getCommandNames ( ) { final Set < String > types = new HashSet < String > ( ) ; final Iterator < OCommandExecutorSQLFactory > ite = getCommandFactories ( ) ; while ( ite . hasNext ( ) ) { types . addAll ( ite . next ( ) . getCommandNames ( ) ) ; } return types ; }


Input: use only for named fields [CODESPLIT] private Tuple < Integer , OType > getFieldSizeAndTypeFromCurrentPosition ( BytesContainer bytes ) { int fieldSize = OVarIntSerializer . readAsInteger ( bytes ) ; OType type = readOType ( bytes , false ) ; return new Tuple <> ( fieldSize , type ) ; }


Input: Sets the response s status as HTTP code and reason . [CODESPLIT] public OHttpResponseWrapper writeStatus ( final int iHttpCode , final String iReason ) throws IOException { response . writeStatus ( iHttpCode , iReason ) ; return this ; }


Input: Sets the response s headers specifying when using the keep - alive or not . [CODESPLIT] public OHttpResponseWrapper writeHeaders ( final String iContentType , final boolean iKeepAlive ) throws IOException { response . writeHeaders ( iContentType , iKeepAlive ) ; return this ; }


Input: Writes records as response specifying a fetch - plan to serialize nested records . The records are serialized in JSON format . [CODESPLIT] public OHttpResponseWrapper writeRecords ( final Object iRecords , final String iFetchPlan ) throws IOException { response . writeRecords ( iRecords , iFetchPlan ) ; return this ; }


Input: Writes a record as response . The record is serialized in JSON format . [CODESPLIT] public OHttpResponseWrapper writeRecord ( final ORecord iRecord , final String iFetchPlan ) throws IOException { response . writeRecord ( iRecord , iFetchPlan , null ) ; return this ; }


Input: Sends the complete HTTP response in one call . [CODESPLIT] public OHttpResponseWrapper send ( final int iCode , final String iReason , final String iContentType , final Object iContent ) throws IOException { response . send ( iCode , iReason , iContentType , iContent , null ) ; return this ; }


Input: Sends the complete HTTP response in one call specifying a stream as content . [CODESPLIT] public OHttpResponseWrapper sendStream ( final int iCode , final String iReason , final String iContentType , final InputStream iContent , final long iSize ) throws IOException { response . sendStream ( iCode , iReason , iContentType , iContent , iSize ) ; return this ; }


Input:
Return the element at the current position and move backward the cursor to the previous position available . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) @ Override public REC previous ( ) { checkDirection ( false ) ; if ( currentRecord != null ) { try { return ( REC ) currentRecord ; } finally { currentRecord = null ; } } // ITERATE UNTIL THE PREVIOUS GOOD RECORD
 while ( hasPrevious ( ) ) { try { return ( REC ) currentRecord ; } finally { currentRecord = null ; } } return null ; }


Input:
Return the element at the current position and move forward the cursor to the next position available . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public REC next ( ) { checkDirection ( true ) ; ORecord record ; // ITERATE UNTIL THE NEXT GOOD RECORD
 while ( hasNext ( ) ) { // FOUND
 if ( currentRecord != null ) { try { return ( REC ) currentRecord ; } finally { currentRecord = null ; } } record = getTransactionEntry ( ) ; if ( record != null ) return ( REC ) record ; } return null ; }


Input: Move the iterator to the begin of the range . If no range was specified move to the first record of the cluster . [CODESPLIT] @ Override public ORecordIteratorCluster < REC > begin ( ) { browsedRecords = 0 ; updateRangesOnLiveUpdate ( ) ; resetCurrentPosition ( ) ; currentRecord = readCurrentRecord ( getRecord ( ) , + 1 ) ; return this ; }


Input:
Tell to the iterator that the upper limit must be checked at every cycle . Useful when concurrent deletes or additions change the size of the cluster while you re browsing it . Default is false . [CODESPLIT] @ Override public ORecordIteratorCluster < REC > setLiveUpdated ( boolean iLiveUpdated ) { super . setLiveUpdated ( iLiveUpdated ) ; // SET THE RANGE LIMITS
 if ( iLiveUpdated ) { firstClusterEntry = 0L ; lastClusterEntry = Long . MAX_VALUE ; } else { final long [ ] range = database . getStorage ( ) . getClusterDataRange ( current . getClusterId ( ) ) ; firstClusterEntry = range [ 0 ] ; lastClusterEntry = range [ 1 ] ; } totalAvailableRecords = database . countClusterElements ( current . getClusterId ( ) ) ; return this ; }


Input: Open a database specified by name using the username and password if needed [CODESPLIT] public ODatabaseObject open ( String name , String user , String password ) { return new OObjectDatabaseTx ( ( ODatabaseDocumentInternal ) orientDB . open ( name , user , password ) ) ; }


Input: Create a new database [CODESPLIT] public void create ( String name , ODatabaseType type , OrientDBConfig config ) { orientDB . create ( name , type , config ) ; }


Input: @param target @param value @param ctx [CODESPLIT] public void setValue ( Object target , Object value , OCommandContext ctx ) { if ( target == null ) { return ; } if ( target . getClass ( ) . isArray ( ) ) { setArrayValue ( target , value , ctx ) ; } else if ( target instanceof List ) { setValue ( ( List ) target , value , ctx ) ; } else if ( OMultiValue . isMultiValue ( value ) ) { //TODO } //TODO }


Input: Avoid to close it but rather release itself to the owner pool . [CODESPLIT] @ Override public void close ( ) { if ( isClosed ( ) ) return ; checkOpenness ( ) ; if ( ownerPool != null && ownerPool . getConnectionsInCurrentThread ( getURL ( ) , userName ) > 1 ) { ownerPool . release ( this ) ; return ; } try { commit ( true ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Error on releasing database '%s' in pool" , e , getName ( ) ) ; } try { callOnCloseListeners ( ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Error on releasing database '%s' in pool" , e , getName ( ) ) ; } getLocalCache ( ) . clear ( ) ; if ( ownerPool != null ) { final ODatabaseDocumentPool localCopy = ownerPool ; ownerPool = null ; localCopy . release ( this ) ; } ODatabaseRecordThreadLocal . instance ( ) . remove ( ) ; }


Input: Change UUID to null to prevent its serialization to disk . [CODESPLIT] @ Override public UUID listenForChanges ( ORidBag collection ) { UUID ownerUUID = collection . getTemporaryId ( ) ; if ( ownerUUID != null ) { final OBonsaiCollectionPointer pointer = collection . getPointer ( ) ; Map < UUID , OBonsaiCollectionPointer > changedPointers = collectionPointerChanges . get ( ) ; if ( pointer != null && pointer . isValid ( ) ) { changedPointers . put ( ownerUUID , pointer ) ; } } return null ; }


Input: Distributed requests against the available workers by using one queue per worker . This guarantee the sequence of the operations against the same record cluster . [CODESPLIT] public synchronized void processRequest ( final ODistributedRequest request , final boolean waitForAcceptingRequests ) { if ( ! running ) { throw new ODistributedException ( "Server is going down or is removing the database:'" + getDatabaseName ( ) + "' discarding" ) ; } final ORemoteTask task = request . getTask ( ) ; if ( waitForAcceptingRequests ) { waitIsReady ( task ) ; if ( ! running ) { throw new ODistributedException ( "Server is going down or is removing the database:'" + getDatabaseName ( ) + "' discarding" ) ; } } totalReceivedRequests . incrementAndGet ( ) ; // final ODistributedMomentum lastMomentum = filterByMomentum.get(); // if (lastMomentum != null && task instanceof OAbstractReplicatedTask) { // final OLogSequenceNumber taskLastLSN = ((OAbstractReplicatedTask) task).getLastLSN(); // // final String sourceServer = manager.getNodeNameById(request.getId().getNodeId()); // final OLogSequenceNumber lastLSNFromMomentum = lastMomentum.getLSN(sourceServer); // // if (taskLastLSN != null && lastLSNFromMomentum != null && taskLastLSN.compareTo(lastLSNFromMomentum) < 0) { // // SKIP REQUEST BECAUSE CONTAINS AN OLD LSN // final String msg = String.format("Skipped request %s on database '%s' because %s < current %s", request, databaseName, // taskLastLSN, lastLSNFromMomentum); // ODistributedServerLog.info(this, localNodeName, null, DIRECTION.NONE, msg); // ODistributedWorker.sendResponseBack(this, manager, request, new ODistributedException(msg)); // return; // } // } final int [ ] partitionKeys = task . getPartitionKey ( ) ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , localNodeName , task . getNodeSource ( ) , DIRECTION . IN , "Request %s on database '%s' partitionKeys=%s task=%s" , request , databaseName , Arrays . toString ( partitionKeys ) , task ) ; if ( partitionKeys . length > 1 || partitionKeys [ 0 ] == - 1 ) { final Set < Integer > involvedWorkerQueues ; if ( partitionKeys . length > 1 ) involvedWorkerQueues = getInvolvedQueuesByPartitionKeys ( partitionKeys ) ; else // LOCK ALL THE QUEUES involvedWorkerQueues = ALL_QUEUES ; // if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog . debug ( this , localNodeName , null , DIRECTION . NONE , "Request %s on database '%s' involvedQueues=%s" , request , databaseName , involvedWorkerQueues ) ; if ( involvedWorkerQueues . size ( ) == 1 ) // JUST ONE QUEUE INVOLVED: PROCESS IT IMMEDIATELY processRequest ( involvedWorkerQueues . iterator ( ) . next ( ) , request ) ; else { // INVOLVING MULTIPLE QUEUES // if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog . debug ( this , localNodeName , null , DIRECTION . NONE , "Request %s on database '%s' waiting for all the previous requests to be completed" , request , databaseName ) ; CyclicBarrier started = new CyclicBarrier ( involvedWorkerQueues . size ( ) ) ; CyclicBarrier finished = new CyclicBarrier ( involvedWorkerQueues . size ( ) ) ; // WAIT ALL THE INVOLVED QUEUES ARE FREE AND SYNCHRONIZED for ( int queue : involvedWorkerQueues ) { ODistributedWorker worker = workerThreads . get ( queue ) ; OWaitPartitionsReadyTask waitRequest = new OWaitPartitionsReadyTask ( started , task , finished ) ; final ODistributedRequest syncRequest = new ODistributedRequest ( null , request . getId ( ) . getNodeId ( ) , request . getId ( ) . getMessageId ( ) , databaseName , waitRequest ) ; worker . processRequest ( syncRequest ) ; } } } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 2 ) { // ANY PARTITION: USE THE FIRST EMPTY IF ANY, OTHERWISE THE FIRST IN THE LIST boolean found = false ; for ( ODistributedWorker q : workerThreads ) { if ( q . isWaitingForNextRequest ( ) && q . localQueue . isEmpty ( ) ) { q . processRequest ( request ) ; found = true ; break ; } } if ( ! found ) // ALL THE THREADS ARE BUSY, SELECT THE FIRST EMPTY ONE for ( ODistributedWorker q : workerThreads ) { if ( q . localQueue . isEmpty ( ) ) { q . processRequest ( request ) ; found = true ; break ; } } if ( ! found ) // EXEC ON THE FIRST QUEUE workerThreads . get ( 0 ) . processRequest ( request ) ; } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 3 ) { // SERVICE - LOCK ODistributedServerLog . debug ( this , localNodeName , request . getTask ( ) . getNodeSource ( ) , DIRECTION . IN , "Request %s on database '%s' dispatched to the lock worker" , request , databaseName ) ; lockThread . processRequest ( request ) ; } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 4 ) { // SERVICE - FAST_NOLOCK ODistributedServerLog . debug ( this , localNodeName , request . getTask ( ) . getNodeSource ( ) , DIRECTION . IN , "Request %s on database '%s' dispatched to the nowait worker" , request , databaseName ) ; nowaitThread . processRequest ( request ) ; } else { processRequest ( partitionKeys [ 0 ] , request ) ; } }


Input: Called inside of { @link com . orientechnologies . orient . core . storage . impl . local . paginated . base . ODurableComponent } to notify that component started to perform operation on data . After that all performance characteristic started to be gathered for this component till method { @link #completeComponentOperation () } will be called . <p > Components can be stacked so if components <code > c1< / code > and then <code > c2< / code > call this method than performance data for both components at once started to be gathered . [CODESPLIT] public void startComponentOperation ( String componentName , ComponentType type ) { final Component currentComponent = componentsStack . peek ( ) ; if ( currentComponent != null && componentName . equals ( currentComponent . name ) ) { currentComponent . operationCount ++ ; return ; } componentsStack . push ( new Component ( componentName , type ) ) ; }


Input: Indicates that the most earliest component in stack of components has completed it s operation so performance data for this component is stopped to be gathered . [CODESPLIT] public void completeComponentOperation ( ) { final Component currentComponent = componentsStack . peek ( ) ; if ( currentComponent == null ) return ; currentComponent . operationCount -- ; if ( currentComponent . operationCount == 0 ) { final String componentName = currentComponent . name ; PerformanceCountersHolder cHolder = countersByComponent . computeIfAbsent ( componentName , k -> currentComponent . type . newCountersHolder ( ) ) ; cHolder . operationsCount ++ ; componentsStack . pop ( ) ; makeSnapshotIfNeeded ( - 1 ) ; } }


Input: Read speed of data in pages per second on cache level for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getReadSpeedFromCacheInPages ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getReadSpeedFromCacheInPages ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getReadSpeedFromCacheInPages ( ) ; return - 1 ; }


Input: Read speed of data from file system in pages for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getReadSpeedFromFileInPages ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getReadSpeedFromFileInPages ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getReadSpeedFromFileInPages ( ) ; return - 1 ; }


Input: Amount of pages read from cache for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesReadFromCache ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getAmountOfPagesReadFromCache ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getAmountOfPagesReadFromCache ( ) ; return - 1 ; }


Input: Amount of pages are read from file for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesReadFromFile ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getAmountOfPagesReadFromFile ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getAmountOfPagesReadFromFile ( ) ; return - 1 ; }


Input: Write speed of data in pages per second on cache level for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getWriteSpeedInCacheInPages ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getWriteSpeedInCacheInPages ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getWriteSpeedInCacheInPages ( ) ; return - 1 ; }


Input: Amount of pages written to cache for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesWrittenInCache ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getAmountOfPagesWrittenInCache ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getAmountOfPagesWrittenInCache ( ) ; return - 1 ; }


Input: Percent of cache hits for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public int getCacheHits ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getCacheHits ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getCacheHits ( ) ; return - 1 ; }


Input: Average amount of pages which were read from cache for component with given name during single data operation . <p > If null value is passed or data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesPerOperation ( String componentName ) { if ( componentName == null ) { return - 1 ; } final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getAmountOfPagesPerOperation ( ) ; return - 1 ; }


Input: Takes performance data are split by components from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data . [CODESPLIT] public void pushComponentCounters ( Map < String , PerformanceCountersHolder > counters ) { if ( snapshot == null ) return ; for ( Map . Entry < String , PerformanceCountersHolder > entry : snapshot . countersByComponent . entrySet ( ) ) { final String componentName = entry . getKey ( ) ; PerformanceCountersHolder holder = counters . computeIfAbsent ( componentName , k -> entry . getValue ( ) . newInstance ( ) ) ; entry . getValue ( ) . pushData ( holder ) ; } }


Input: Takes write cache performance data from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data and as result of this method call . [CODESPLIT] public WritCacheCountersHolder pushWriteCacheCounters ( WritCacheCountersHolder holder ) { if ( snapshot == null ) return holder ; if ( snapshot . writCacheCountersHolder == null ) return holder ; if ( holder == null ) holder = new WritCacheCountersHolder ( ) ; snapshot . writCacheCountersHolder . pushData ( holder ) ; return holder ; }


Input: Takes storage performance data from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data and as result of this method call . [CODESPLIT] public StorageCountersHolder pushStorageCounters ( StorageCountersHolder holder ) { if ( snapshot == null ) return holder ; if ( snapshot . storageCountersHolder == null ) return holder ; if ( holder == null ) holder = new StorageCountersHolder ( ) ; snapshot . storageCountersHolder . pushData ( holder ) ; return holder ; }


Input: Takes write ahead log data from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data and as result of this method call . [CODESPLIT] public WALCountersHolder pushWALCounters ( WALCountersHolder holder ) { if ( snapshot == null ) return holder ; if ( snapshot . walCountersHolder == null ) return holder ; if ( holder == null ) holder = new WALCountersHolder ( ) ; snapshot . walCountersHolder . pushData ( holder ) ; return holder ; }


Input: Takes performance data for component from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data . [CODESPLIT] public void pushComponentCounters ( String name , PerformanceCountersHolder holder ) { if ( snapshot == null ) return ; final PerformanceCountersHolder countersHolder = snapshot . countersByComponent . get ( name ) ; if ( countersHolder != null ) { countersHolder . pushData ( holder ) ; } }


Input: Converts properties of given class into values of fields of returned document . Names of fields equal to names of properties . <p > All data related to separate components are stored in field <code > dataByComponent< / code > map which has type { @link OType#EMBEDDEDMAP } where key of map entry is name of component and value is document which contains the same fields as high level document but with values for single component not whole system . <p > Write ahead log performance data are stored inside of <code > walData< / code > field . [CODESPLIT] public ODocument toDocument ( ) { final ODocument document = performanceCountersHolder . toDocument ( ) ; document . field ( "commitTime" , getCommitTime ( ) , OType . LONG ) ; final Map < String , ODocument > countersMap = new HashMap <> ( ) ; for ( Map . Entry < String , PerformanceCountersHolder > entry : countersByComponent . entrySet ( ) ) { countersMap . put ( entry . getKey ( ) , entry . getValue ( ) . toDocument ( ) ) ; } document . field ( "dataByComponent" , countersMap , OType . EMBEDDEDMAP ) ; if ( walCountersHolder != null ) { final ODocument wal = walCountersHolder . toDocument ( ) ; document . field ( "walData" , wal , OType . EMBEDDED ) ; } return document ; }


Input: Increments counter of page accesses from cache . <p > If you wish to gather statistic for current durable component please call { [CODESPLIT] public void incrementPageAccessOnCacheLevel ( boolean cacheHit ) { performanceCountersHolder . cacheAccessCount ++ ; if ( cacheHit ) performanceCountersHolder . cacheHit ++ ; for ( Component component : componentsStack ) { final String componentName = component . name ; PerformanceCountersHolder cHolder = countersByComponent . computeIfAbsent ( componentName , k -> component . type . newCountersHolder ( ) ) ; cHolder . cacheAccessCount ++ ; if ( cacheHit ) cHolder . cacheHit ++ ; } makeSnapshotIfNeeded ( - 1 ) ; }


Input: Stops and records results of timer which counts how much time was spent on operation of flush pages in write cache . [CODESPLIT] public void stopWriteCacheFlushTimer ( int pagesFlushed ) { // lazy initialization to prevent memory consumption if ( writCacheCountersHolder == null ) writCacheCountersHolder = new WritCacheCountersHolder ( ) ; final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; writCacheCountersHolder . flushOperationsCount ++ ; writCacheCountersHolder . amountOfPagesFlushed += pagesFlushed ; writCacheCountersHolder . flushOperationsTime += timeDiff ; makeSnapshotIfNeeded ( endTs ) ; }


Input: Stops and records results of timer which counts how much time was spent on fuzzy checkpoint operation . [CODESPLIT] public void stopFuzzyCheckpointTimer ( ) { if ( writCacheCountersHolder == null ) writCacheCountersHolder = new WritCacheCountersHolder ( ) ; final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; writCacheCountersHolder . fuzzyCheckpointCount ++ ; writCacheCountersHolder . fuzzyCheckpointTime += timeDiff ; makeSnapshotIfNeeded ( endTs ) ; }


Input: Stops and records results of timer which counts how much time was spent on read of page from disk cache . <p > If you wish to gather statistic for current durable component please call { [CODESPLIT] public void stopPageReadFromCacheTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; performanceCountersHolder . pageReadFromCacheTime += timeDiff ; performanceCountersHolder . pageReadFromCacheCount ++ ; for ( Component component : componentsStack ) { final String componentName = component . name ; PerformanceCountersHolder cHolder = countersByComponent . computeIfAbsent ( componentName , k -> component . type . newCountersHolder ( ) ) ; cHolder . pageReadFromCacheTime += timeDiff ; cHolder . pageReadFromCacheCount ++ ; } final Component currentComponent = componentsStack . peek ( ) ; if ( currentComponent != null ) { PerformanceCountersHolder currentHolder = countersByComponent . get ( currentComponent . name ) ; if ( currentHolder . currentOperation != null ) { currentHolder . currentOperation . incrementOperationsCounter ( 1 , 0 ) ; } } makeSnapshotIfNeeded ( endTs ) ; }


Input: Stops and records results of timer which counts how much time was spent on full checkpoint operation . [CODESPLIT] public void stopFullCheckpointTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; if ( storageCountersHolder == null ) storageCountersHolder = new StorageCountersHolder ( ) ; storageCountersHolder . fullCheckpointOperationsCount ++ ; storageCountersHolder . fullCheckpointOperationsTime += timeDiff ; makeSnapshotIfNeeded ( endTs ) ; }


Input: Stops and records results of timer which counts how much time was spent to write page to disk cache . <p > If you wish to gather statistic for current durable component please call { [CODESPLIT] public void stopPageWriteInCacheTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; performanceCountersHolder . pageWriteToCacheTime += timeDiff ; performanceCountersHolder . pageWriteToCacheCount ++ ; for ( Component component : componentsStack ) { final String componentName = component . name ; PerformanceCountersHolder cHolder = countersByComponent . computeIfAbsent ( componentName , k -> component . type . newCountersHolder ( ) ) ; cHolder . pageWriteToCacheTime += timeDiff ; cHolder . pageWriteToCacheCount ++ ; } makeSnapshotIfNeeded ( endTs ) ; }


Input: Stops and records results of timer which counts how much time was spent on atomic operation commit . [CODESPLIT] public void stopCommitTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; performanceCountersHolder . commitTime += timeDiff ; performanceCountersHolder . commitCount ++ ; makeSnapshotIfNeeded ( endTs ) ; }


Input: Stops and records results of timer which counts how much time was spent on logging of single write ahead log record . [CODESPLIT] public void stopWALRecordTimer ( boolean isStartRecord , boolean isStopRecord ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; if ( walCountersHolder == null ) walCountersHolder = new WALCountersHolder ( ) ; walCountersHolder . logRecordCount ++ ; walCountersHolder . logRecordTime += timeDiff ; if ( isStartRecord ) { walCountersHolder . startRecordCount ++ ; walCountersHolder . startRecordTime += timeDiff ; } else if ( isStopRecord ) { walCountersHolder . stopRecordCount ++ ; walCountersHolder . stopRecordTime += timeDiff ; } makeSnapshotIfNeeded ( endTs ) ; }


Input: Stops timer and records how much time was spent on flushing of data from write ahead log cache . [CODESPLIT] public void stopWALFlushTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; if ( walCountersHolder == null ) walCountersHolder = new WALCountersHolder ( ) ; walCountersHolder . flushCount ++ ; walCountersHolder . flushTime += timeDiff ; makeSnapshotIfNeeded ( endTs ) ; }


Input: Makes snapshot of data if time for next snapshot is passed . Also clear all data if { @link #cleanUpInterval } interval is over . [CODESPLIT] private void makeSnapshotIfNeeded ( long currentTime ) { if ( currentTime < 0 ) { currentTime = nanoTimer . getNano ( ) ; } if ( lastSnapshotTimestamp == - 1 ) lastSnapshotTimestamp = 0 ; if ( lastSnapshotTimestamp < 0 || currentTime - lastSnapshotTimestamp >= intervalBetweenSnapshots ) { snapshot = new PerformanceSnapshot ( performanceCountersHolder , countersByComponent , writCacheCountersHolder , storageCountersHolder , walCountersHolder ) ; lastSnapshotTimestamp = currentTime ; } if ( cleanUpInterval > 0 ) { if ( currentTime - lastCleanUpTimeStamp >= cleanUpInterval ) { performanceCountersHolder . clean ( ) ; for ( PerformanceCountersHolder pch : countersByComponent . values ( ) ) { pch . clean ( ) ; } if ( writCacheCountersHolder != null ) writCacheCountersHolder . clean ( ) ; if ( storageCountersHolder != null ) storageCountersHolder . clean ( ) ; if ( writCacheCountersHolder != null ) walCountersHolder . clean ( ) ; lastCleanUpTimeStamp = currentTime ; } } }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void shutdown ( ) { try { MBeanServer mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; if ( onProfiler != null ) if ( mBeanServer . isRegistered ( onProfiler ) ) mBeanServer . unregisterMBean ( onProfiler ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "OrientDB Server v" + OConstants . getVersion ( ) + " unregisterMBean error" , e ) ; } }


Input: returns an already parsed SQL executor taking it from the cache if it exists or creating a new one ( parsing and then putting it into the cache ) if it doesn t [CODESPLIT] public static OStatement get ( String statement , ODatabaseDocumentInternal db ) { if ( db == null ) { return parse ( statement ) ; } OStatementCache resource = db . getSharedContext ( ) . getStatementCache ( ) ; return resource . get ( statement ) ; }


Input: @param statement an SQL statement [CODESPLIT] public OStatement get ( String statement ) { OStatement result ; synchronized ( map ) { //LRU result = map . remove ( statement ) ; if ( result != null ) { map . put ( statement , result ) ; } } if ( result == null ) { result = parse ( statement ) ; synchronized ( map ) { map . put ( statement , result ) ; } } return result ; }


Input: parses an SQL statement and returns the corresponding executor [CODESPLIT] protected static OStatement parse ( String statement ) throws OCommandSQLParsingException { try { ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; InputStream is ; if ( db == null ) { is = new ByteArrayInputStream ( statement . getBytes ( ) ) ; } else { try { is = new ByteArrayInputStream ( statement . getBytes ( db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ) ; } catch ( UnsupportedEncodingException e2 ) { OLogManager . instance ( ) . warn ( null , "Unsupported charset for database " + db + " " + db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; is = new ByteArrayInputStream ( statement . getBytes ( ) ) ; } } OrientSql osql = null ; if ( db == null ) { osql = new OrientSql ( is ) ; } else { try { osql = new OrientSql ( is , db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; } catch ( UnsupportedEncodingException e2 ) { OLogManager . instance ( ) . warn ( null , "Unsupported charset for database " + db + " " + db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; osql = new OrientSql ( is ) ; } } OStatement result = osql . parse ( ) ; result . originalStatement = statement ; return result ; } catch ( ParseException e ) { throwParsingException ( e , statement ) ; } catch ( TokenMgrError e2 ) { throwParsingException ( e2 , statement ) ; } return null ; }


Input: / * =============== START / STOP ================= [CODESPLIT] protected void start ( ) { try { initNetwork ( ) ; initReceiveMessages ( ) ; initDiscoveryPing ( ) ; initCheckLeader ( ) ; initCheckDisconnect ( ) ; } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , "Cannot start distributed node discovery: " + ex . getMessage ( ) , ex ) ; } }


Input: inits the procedure that listens to pings from other servers eg . that discovers other nodes in the network [CODESPLIT] protected void initReceiveMessages ( ) throws IOException { messageThread = new Thread ( ( ) -> { while ( ! Thread . interrupted ( ) ) { receiveMessages ( ) ; } } ) ; messageThread . setName ( "OrientDB_DistributedDiscoveryThread" ) ; messageThread . setDaemon ( true ) ; messageThread . start ( ) ; }


Input: init the procedure that sends pings to other servers ie . that notifies that you are alive [CODESPLIT] protected void initDiscoveryPing ( ) { discoveryTimer = new TimerTask ( ) { @ Override public void run ( ) { try { sendPing ( ) ; if ( running ) { initDiscoveryPing ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; taskScheduler . scheduleOnce ( discoveryTimer , discoveryPingIntervalMillis ) ; }


Input: inits the procedure that checks if a server is no longer available ie . if he did not ping for a long time [CODESPLIT] protected void initCheckDisconnect ( ) { disconnectTimer = new TimerTask ( ) { public void run ( ) { try { checkIfKnownServersAreAlive ( ) ; if ( running ) { initCheckDisconnect ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; taskScheduler . scheduleOnce ( disconnectTimer , discoveryPingIntervalMillis ) ; }


Input: init the procedure that sends pings to other servers ie . that notifies that you are alive [CODESPLIT] private void initCheckLeader ( ) { checkerTimer = new TimerTask ( ) { @ Override public void run ( ) { try { if ( running ) { checkLeader ( ) ; initCheckLeader ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; taskScheduler . scheduleOnce ( checkerTimer , checkLeaderIntervalMillis ) ; }


Input: / * =============== NETWORK UTILITIES ================= [CODESPLIT] protected byte [ ] serializeMessage ( OBroadcastMessage message ) throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; message . write ( new DataOutputStream ( buffer ) ) ; return encrypt ( buffer . toByteArray ( ) ) ; }


Input: / * =============== ENCRYPTION ================= [CODESPLIT] private byte [ ] encrypt ( byte [ ] data ) throws Exception { if ( config . getGroupPassword ( ) == null ) { return data ; } Cipher cipher = Cipher . getInstance ( "AES/CBC/PKCS5Padding" ) ; byte [ ] iv = cipher . getParameters ( ) . getParameterSpec ( IvParameterSpec . class ) . getIV ( ) ; IvParameterSpec ivSpec = new IvParameterSpec ( iv ) ; SecretKeySpec keySpec = new SecretKeySpec ( paddedPassword ( config . getGroupPassword ( ) ) , "AES" ) ; cipher . init ( Cipher . ENCRYPT_MODE , keySpec , ivSpec ) ; ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; DataOutput output = new DataOutputStream ( stream ) ; output . writeInt ( iv . length ) ; output . write ( iv ) ; byte [ ] cypher = cipher . doFinal ( data ) ; output . writeInt ( cypher . length ) ; output . write ( cypher ) ; return stream . toByteArray ( ) ; }


Input: Removes the Element from the Graph . In case the element is a Vertex all the incoming and outgoing edges are automatically removed too . [CODESPLIT] void removeRecord ( ) { checkIfAttached ( ) ; final OrientBaseGraph graph = getGraph ( ) ; graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; if ( checkDeletedInTx ( ) ) graph . throwRecordNotFoundException ( getIdentity ( ) , "The graph element with id " + getIdentity ( ) + " not found" ) ; try { getRecord ( ) . load ( ) ; } catch ( ORecordNotFoundException e ) { graph . throwRecordNotFoundException ( getIdentity ( ) , e . getMessage ( ) ) ; } getRecord ( ) . delete ( ) ; }


Input: ( Blueprints Extension ) Sets multiple properties in one shot against Vertices and Edges . This improves performance avoiding to save the graph element at every property set . <br > Example : <p > <code > vertex . setProperties ( name Jill age 33 city Rome born Victoria TX ) ; < / code > You can also pass a Map of values as first argument . In this case all the map entries will be set as element properties : <p > <code > Map<String Object > props = new HashMap<String Object > () ; props . put ( name Jill ) ; props . put ( age 33 ) ; props . put ( city Rome ) ; props . put ( born Victoria TX ) ; vertex . setProperties ( props ) ; < / code > [CODESPLIT] public < T extends OrientElement > T setProperties ( final Object ... fields ) { if ( checkDeletedInTx ( ) ) graph . throwRecordNotFoundException ( getIdentity ( ) , "The graph element " + getIdentity ( ) + " has been deleted" ) ; setPropertiesInternal ( fields ) ; save ( ) ; return ( T ) this ; }


Input: Sets a Property value . [CODESPLIT] @ Override public void setProperty ( final String key , final Object value ) { if ( checkDeletedInTx ( ) ) graph . throwRecordNotFoundException ( getIdentity ( ) , "The graph element " + getIdentity ( ) + " has been deleted" ) ; validateProperty ( this , key , value ) ; final OrientBaseGraph graph = getGraph ( ) ; if ( graph != null ) graph . autoStartTransaction ( ) ; getRecord ( ) . field ( key , value ) ; if ( graph != null ) save ( ) ; }


Input: Removes a Property . [CODESPLIT] @ Override public < T > T removeProperty ( final String key ) { if ( checkDeletedInTx ( ) ) throw new IllegalStateException ( "The vertex " + getIdentity ( ) + " has been deleted" ) ; final OrientBaseGraph graph = getGraph ( ) ; if ( graph != null ) graph . autoStartTransaction ( ) ; final Object oldValue = getRecord ( ) . removeField ( key ) ; if ( graph != null ) save ( ) ; return ( T ) oldValue ; }


Input: Returns a Property value . [CODESPLIT] @ Override public < T > T getProperty ( final String key ) { if ( key == null ) return null ; final OrientBaseGraph graph = getGraph ( ) ; if ( key . equals ( "_class" ) ) return ( T ) ODocumentInternal . getImmutableSchemaClass ( getRecord ( ) ) . getName ( ) ; else if ( key . equals ( "_version" ) ) return ( T ) new Integer ( getRecord ( ) . getVersion ( ) ) ; else if ( key . equals ( "_rid" ) ) return ( T ) rawElement . getIdentity ( ) . toString ( ) ; final ODocument record = getRecord ( ) ; if ( record == null ) // NO RECORD return null ; final Object fieldValue = record . field ( key ) ; if ( graph != null && fieldValue instanceof OIdentifiable && ! ( ( ( OIdentifiable ) fieldValue ) . getRecord ( ) instanceof OBlob ) ) { ODocument fieldRecord = ( ( OIdentifiable ) fieldValue ) . getRecord ( ) ; if ( fieldRecord != null ) { final OClass schemaClass = fieldRecord . getSchemaClass ( ) ; if ( schemaClass != null && ( schemaClass . isVertexType ( ) || schemaClass . isEdgeType ( ) ) ) { // CONVERT IT TO VERTEX/EDGE return ( T ) graph . getElement ( fieldValue ) ; } } return ( T ) fieldValue ; } else if ( ! ( fieldValue instanceof Map ) && OMultiValue . isMultiValue ( fieldValue ) && OMultiValue . getFirstValue ( fieldValue ) instanceof OIdentifiable ) { final OIdentifiable firstValue = ( OIdentifiable ) OMultiValue . getFirstValue ( fieldValue ) ; if ( firstValue instanceof ODocument ) { final ODocument document = ( ODocument ) firstValue ; /// clusterId -2 Is considered a projection so does not have a class but is a not embedded record if ( document . getIdentity ( ) . getClusterId ( ) != - 2 && ( document . isEmbedded ( ) || ODocumentInternal . getImmutableSchemaClass ( document ) == null ) ) return ( T ) fieldValue ; } if ( graph != null ) // CONVERT IT TO ITERABLE<VERTEX/EDGE> return ( T ) new OrientElementIterable < OrientElement > ( graph , OMultiValue . getMultiValueIterable ( fieldValue ) ) ; } return ( T ) fieldValue ; }


Input: ( Blueprints Extension ) Saves current element to a particular cluster . You don t need to call save () unless you re working against Temporary Vertices . [CODESPLIT] public void save ( final String iClusterName ) { final OrientBaseGraph graph = checkIfAttached ( ) ; graph . setCurrentGraphInThreadLocal ( ) ; if ( rawElement instanceof ODocument ) if ( iClusterName != null ) rawElement = ( ( ODocument ) rawElement ) . save ( iClusterName ) ; else rawElement = ( ( ODocument ) rawElement ) . save ( ) ; }


Input: ( Blueprints Extension ) Fills the Element from a byte [] [CODESPLIT] @ Override public OSerializableStream fromStream ( final byte [ ] stream ) throws OSerializationException { final ODocument record = getRecord ( ) ; ( ( ORecordId ) record . getIdentity ( ) ) . fromString ( new String ( stream ) ) ; return this ; }


Input: ( Blueprints Extension ) Returns the record s identity . [CODESPLIT] @ Override public ORID getIdentity ( ) { if ( rawElement == null ) return ORecordId . EMPTY_RECORD_ID ; final ORID rid = rawElement . getIdentity ( ) ; if ( ! rid . isValid ( ) ) { final OrientBaseGraph graph = getGraph ( ) ; if ( graph != null ) { // SAVE THE RECORD TO OBTAIN A VALID RID graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; save ( ) ; } } return rid ; }


Input: ( Blueprints Extension ) Returns the underlying record . [CODESPLIT] @ Override public ODocument getRecord ( ) { if ( rawElement == null ) return null ; if ( rawElement instanceof ODocument ) return ( ODocument ) rawElement ; final ODocument doc = rawElement . getRecord ( ) ; if ( doc == null ) return null ; // CHANGE THE RID -> DOCUMENT rawElement = doc ; return doc ; }


Input: ( Blueprints Extension ) Removes the reference to the current graph instance to let working offline . To reattach it use @attach . <p > This methods works only in classic detach / attach mode when dettachment / attachment is done manually by default it is done automatically and currently active graph connection will be used as graph elements owner . [CODESPLIT] public OrientElement detach ( ) { // EARLY UNMARSHALL FIELDS getRecord ( ) . setLazyLoad ( false ) ; getRecord ( ) . fieldNames ( ) ; // COPY GRAPH SETTINGS TO WORK OFFLINE if ( graph != null ) { settings = graph . settings . copy ( ) ; graph = null ; } classicDetachMode = true ; return this ; }


Input: ( Blueprints Extension ) Replaces current graph instance with new one on @detach - ed elements . Use this method to pass elements between graphs or to switch between Tx and NoTx instances . <p > This methods works only in classic detach / attach mode when detachment / attachment is done manually by default it is done automatically and currently active graph connection will be used as graph elements owner . <p > To set classic detach / attach mode please set custom database parameter <code > classicDetachMode< / code > to <code > true< / code > . [CODESPLIT] public OrientElement attach ( final OrientBaseGraph iNewGraph ) { if ( iNewGraph == null ) throw new IllegalArgumentException ( "Graph is null" ) ; classicDetachMode = true ; graph = iNewGraph ; // LINK THE GRAPHS SETTINGS settings = graph . settings ; return this ; }


Input: ( Blueprints Extension ) Returns the Graph instance associated to the current element . On [CODESPLIT] public OrientBaseGraph getGraph ( ) { if ( classicDetachMode ) return graph ; OrientBaseGraph result = OrientBaseGraph . getActiveGraph ( ) ; if ( result == null && this . graph != null && ! graph . isClosed ( ) ) { result = graph ; } return result ; }


Input: ( Blueprints Extension ) Validates an Element property . [CODESPLIT] public final void validateProperty ( final Element element , final String key , final Object value ) throws IllegalArgumentException { if ( settings . isStandardElementConstraints ( ) && null == value ) throw ExceptionFactory . propertyValueCanNotBeNull ( ) ; if ( null == key ) throw ExceptionFactory . propertyKeyCanNotBeNull ( ) ; if ( settings . isStandardElementConstraints ( ) && key . equals ( StringFactory . ID ) ) throw ExceptionFactory . propertyKeyIdIsReserved ( ) ; if ( element instanceof Edge && key . equals ( StringFactory . LABEL ) ) throw ExceptionFactory . propertyKeyLabelIsReservedForEdges ( ) ; if ( key . isEmpty ( ) ) throw ExceptionFactory . propertyKeyCanNotBeEmpty ( ) ; }


Input: Check if a class already exists otherwise create it at the fly . If a transaction is running commit changes create the class and begin a new transaction . [CODESPLIT] protected String checkForClassInSchema ( final String className ) { if ( className == null ) return null ; OrientBaseGraph graph = getGraph ( ) ; if ( graph == null ) return className ; final OSchema schema = graph . getRawGraph ( ) . getMetadata ( ) . getSchema ( ) ; if ( ! schema . existsClass ( className ) ) { // CREATE A NEW CLASS AT THE FLY try { graph . executeOutsideTx ( new OCallable < OClass , OrientBaseGraph > ( ) { @ Override public OClass call ( final OrientBaseGraph g ) { return schema . createClass ( className , schema . getClass ( getBaseClassName ( ) ) ) ; } } , "Committing the active transaction to create the new type '" , className , "' as subclass of '" , getBaseClassName ( ) , "'. The transaction will be reopen right after that. To avoid this behavior create the classes outside the transaction" ) ; } catch ( OSchemaException e ) { if ( ! schema . existsClass ( className ) ) throw e ; } } else { // CHECK THE CLASS INHERITANCE final OClass cls = schema . getClass ( className ) ; if ( ! cls . isSubClassOf ( getBaseClassName ( ) ) ) throw new IllegalArgumentException ( "Class '" + className + "' is not an instance of " + getBaseClassName ( ) ) ; } return className ; }


Input: ( Blueprints Extension ) Sets multiple properties in one shot against Vertices and Edges without saving the element . This improves performance avoiding to save the graph element at every property set . Example : <p > <code > vertex . setProperties ( name Jill age 33 city Rome born Victoria TX ) ; < / code > You can also pass a Map of values as first argument . In this case all the map entries will be set as element properties : <p > <code > Map<String Object > props = new HashMap<String Object > () ; props . put ( name Jill ) ; props . put ( age 33 ) ; props . put ( city Rome ) ; props . put ( born Victoria TX ) ; vertex . setProperties ( props ) ; < / code > [CODESPLIT] protected < T extends OrientElement > T setPropertiesInternal ( final Object ... fields ) { OrientBaseGraph graph = getGraph ( ) ; if ( fields != null && fields . length > 0 && fields [ 0 ] != null ) { if ( graph != null ) graph . autoStartTransaction ( ) ; if ( fields . length == 1 ) { Object f = fields [ 0 ] ; if ( f instanceof Map < ? , ? > ) { for ( Map . Entry < Object , Object > entry : ( ( Map < Object , Object > ) f ) . entrySet ( ) ) setPropertyInternal ( this , ( ODocument ) rawElement . getRecord ( ) , entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } else if ( f instanceof Collection ) { for ( Object o : ( Collection ) f ) { if ( ! ( o instanceof OPair ) ) throw new IllegalArgumentException ( "Invalid fields: expecting a pairs of fields as String,Object, but found the item: " + o ) ; final OPair entry = ( OPair ) o ; setPropertyInternal ( this , ( ODocument ) rawElement . getRecord ( ) , entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } } else throw new IllegalArgumentException ( "Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: " + f ) ; } else { if ( fields . length % 2 != 0 ) throw new IllegalArgumentException ( "Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: " + Arrays . toString ( fields ) ) ; // SET THE FIELDS for ( int i = 0 ; i < fields . length ; i += 2 ) setPropertyInternal ( this , ( ODocument ) rawElement . getRecord ( ) , fields [ i ] . toString ( ) , fields [ i + 1 ] ) ; } } return ( T ) this ; }


Input: @param config Global configuration parameter . [CODESPLIT] public < T extends Enum < T > > T getValueAsEnum ( final OGlobalConfiguration config , Class < T > enumType ) { final Object value ; if ( this . config != null && this . config . containsKey ( config . getKey ( ) ) ) { value = this . config . get ( config . getKey ( ) ) ; } else { value = config . getValue ( ) ; } if ( value == null ) return null ; if ( enumType . isAssignableFrom ( value . getClass ( ) ) ) { return enumType . cast ( value ) ; } else if ( value instanceof String ) { final String presentation = value . toString ( ) ; return Enum . valueOf ( enumType , presentation ) ; } else { throw new ClassCastException ( "Value " + value + " can not be cast to enumeration " + enumType . getSimpleName ( ) ) ; } }


Input: Wraps courser only if it is not already wrapped . [CODESPLIT] public static OIndexCursor wrap ( OIndex < ? > source , OIndexCursor cursor , long indexRebuildVersion ) { if ( cursor instanceof OIndexChangesWrapper ) return cursor ; if ( cursor instanceof OSizeable ) { return new OIndexChangesSizeable ( source , cursor , indexRebuildVersion ) ; } return new OIndexChangesWrapper ( source , cursor , indexRebuildVersion ) ; }


Input: { [CODESPLIT] @ Override public Map . Entry < Object , OIdentifiable > nextEntry ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final Map . Entry < Object , OIdentifiable > entry = delegate . nextEntry ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return entry ; }


Input: { [CODESPLIT] @ Override public Set < OIdentifiable > toValues ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final Set < OIdentifiable > values = delegate . toValues ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return values ; }


Input: { [CODESPLIT] @ Override public Set < Map . Entry < Object , OIdentifiable > > toEntries ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final Set < Map . Entry < Object , OIdentifiable > > entries = delegate . toEntries ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return entries ; }


Input: { [CODESPLIT] @ Override public Set < Object > toKeys ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final Set < Object > keys = delegate . toKeys ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return keys ; }


Input: { [CODESPLIT] @ Override public boolean hasNext ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final boolean isNext = delegate . hasNext ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return isNext ; }