signature:
public class OGraphSONUtility { /** * Creates GraphSON for a single graph element . */
public ObjectNode objectNodeFromElement ( final Element element ) { } }

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


signature:
public class OGraphSONUtility { /** * Reads an individual Vertex from JSON . The vertex must match the accepted GraphSON format .
 * @ param json
 * a single vertex in GraphSON format as Jettison JSONObject
 * @ param factory
 * the factory responsible for constructing graph elements
 * @ param mode
 * the mode of the GraphSON
 * @ param propertyKeys
 * a list of keys to include on reading of element properties */
public static Vertex vertexFromJson ( final JSONObject json , final ElementFactory factory , final GraphSONMode mode , final Set < String > propertyKeys ) throws IOException { } }

implementation: final OGraphSONUtility graphson = new OGraphSONUtility ( mode , factory , propertyKeys , null ) ; return graphson . vertexFromJson ( json ) ;


signature:
public class OGraphSONUtility { /** * Reads an individual Edge from JSON . The edge must match the accepted GraphSON format .
 * @ param json
 * a single edge in GraphSON format as a Jettison JSONObject
 * @ param factory
 * the factory responsible for constructing graph elements
 * @ param mode
 * the mode of the GraphSON
 * @ param propertyKeys
 * a list of keys to include when reading of element properties */
public static Edge edgeFromJson ( final JSONObject json , final Vertex out , final Vertex in , final ElementFactory factory , final GraphSONMode mode , final Set < String > propertyKeys ) throws IOException { } }

implementation: final OGraphSONUtility graphson = new OGraphSONUtility ( mode , factory , null , propertyKeys ) ; return graphson . edgeFromJson ( json , out , in ) ;


signature:
public class OGraphSONUtility { /** * Creates a Jettison JSONObject from a graph element .
 * @ param element
 * the graph element to convert to JSON .
 * @ param propertyKeys
 * The property keys at the root of the element to serialize . If null , then all keys are serialized .
 * @ param mode
 * the type of GraphSON to be generated . */
public static JSONObject jsonFromElement ( final Element element , final Set < String > propertyKeys , final GraphSONMode mode ) throws JSONException { } }

implementation: final OGraphSONUtility graphson = element instanceof Edge ? new OGraphSONUtility ( mode , null , null , propertyKeys ) : new OGraphSONUtility ( mode , null , propertyKeys , null ) ; return graphson . jsonFromElement ( element ) ;


signature:
public class OGraphSONUtility { /** * Creates a Jackson ObjectNode from a graph element .
 * @ param element
 * the graph element to convert to JSON .
 * @ param propertyKeys
 * The property keys at the root of the element to serialize . If null , then all keys are serialized .
 * @ param mode
 * The type of GraphSON to generate . */
public static ObjectNode objectNodeFromElement ( final Element element , final Set < String > propertyKeys , final GraphSONMode mode ) { } }

implementation: final OGraphSONUtility graphson = element instanceof Edge ? new OGraphSONUtility ( mode , null , null , propertyKeys ) : new OGraphSONUtility ( mode , null , propertyKeys , null ) ; return graphson . objectNodeFromElement ( element ) ;


signature:
public class OETLHandler { /** * Executes import with configuration ; */
public void executeImport ( ODocument cfg , OServer server ) { } }

implementation: OETLJob job = new OETLJob ( cfg , server , new OETLListener ( ) { @ Override public void onEnd ( OETLJob etlJob ) { currentJob = null ; } } ) ; job . validate ( ) ; currentJob = job ; pool . execute ( job ) ;


signature:
public class OETLHandler { /** * Status of the Running Jobs
 * @ return ODocument */
public ODocument status ( ) { } }

implementation: ODocument status = new ODocument ( ) ; Collection < ODocument > jobs = new ArrayList < ODocument > ( ) ; if ( currentJob != null ) { jobs . add ( currentJob . status ( ) ) ; } status . field ( "jobs" , jobs ) ; return status ;


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

implementation:
final ORID r = object . getIdentity ( ) ; buffer . putShort ( ( short ) r . getClusterId ( ) ) ; // Wrong implementation but needed for binary compatibility
byte [ ] stream = new byte [ OLongSerializer . LONG_SIZE ] ; OLongSerializer . INSTANCE . serialize ( r . getClusterPosition ( ) , stream , 0 ) ; buffer . put ( stream ) ;


signature:
public class OLinkSerializer { /** * { @ inheritDoc } */
@ Override public OIdentifiable deserializeFromByteBufferObject ( ByteBuffer buffer ) { } }

implementation:
final int clusterId = buffer . getShort ( ) ; final byte [ ] stream = new byte [ OLongSerializer . LONG_SIZE ] ; buffer . get ( stream ) ; // Wrong implementation but needed for binary compatibility
final long clusterPosition = OLongSerializer . INSTANCE . deserialize ( stream , 0 ) ; return new ORecordId ( clusterId , clusterPosition ) ;


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

implementation:
final int clusterId = walChanges . getShortValue ( buffer , offset ) ; // Wrong implementation but needed for binary compatibility
final long clusterPosition = OLongSerializer . INSTANCE . deserialize ( walChanges . getBinaryValue ( buffer , offset + OShortSerializer . SHORT_SIZE , OLongSerializer . LONG_SIZE ) , 0 ) ; // final long clusterPosition = OLongSerializer . INSTANCE
// . deserializeFromDirectMemory ( pointer , offset + OShortSerializer . SHORT _ SIZE ) ;
return new ORecordId ( clusterId , clusterPosition ) ;


signature:
public class OComparatorFactory { /** * Returns { @ link Comparator } instance if applicable one exist or < code > null < / code > otherwise .
 * @ param clazz
 * Class of object that is going to be compared .
 * @ param < T >
 * Class of object that is going to be compared .
 * @ return { @ link Comparator } instance if applicable one exist or < code > null < / code > otherwise . */
@ SuppressWarnings ( "unchecked" ) public < T > Comparator < T > getComparator ( Class < T > clazz ) { } }

implementation: boolean useUnsafe = OGlobalConfiguration . MEMORY_USE_UNSAFE . getValueAsBoolean ( ) ; if ( clazz . equals ( byte [ ] . class ) ) { if ( useUnsafe && unsafeWasDetected ) return ( Comparator < T > ) OUnsafeByteArrayComparator . INSTANCE ; return ( Comparator < T > ) OByteArrayComparator . INSTANCE ; } return null ;


signature:
public class ODatabaseDocumentDistributed { /** * returns the cluster map for current deploy . The keys of the map are node names , the values contain names of clusters ( data
 * files ) available on the single node .
 * @ return the cluster map for current deploy */
public Map < String , Set < String > > getActiveClusterMap ( ) { } }

implementation:
if ( distributedManager . isOffline ( ) || ! distributedManager . isNodeOnline ( distributedManager . getLocalNodeName ( ) , getName ( ) ) || OScenarioThreadLocal . INSTANCE . isRunModeDistributed ( ) ) { return super . getActiveClusterMap ( ) ; } Map < String , Set < String > > result = new HashMap < > ( ) ; ODistributedConfiguration cfg = getDistributedConfiguration ( ) ; for ( String server : distributedManager . getActiveServers ( ) ) { if ( getClustersOnServer ( cfg , server ) . contains ( "*" ) ) { // TODO check this ! ! !
result . put ( server , getStorage ( ) . getClusterNames ( ) ) ; } else { result . put ( server , getClustersOnServer ( cfg , server ) ) ; } } return result ;


signature:
public class ODatabaseDocumentDistributed { /** * returns the data center map for current deploy . The keys are data center names , the values are node names per data center
 * @ return data center map for current deploy */
public Map < String , Set < String > > getActiveDataCenterMap ( ) { } }

implementation: Map < String , Set < String > > result = new HashMap < > ( ) ; ODistributedConfiguration cfg = getDistributedConfiguration ( ) ; Set < String > servers = cfg . getRegisteredServers ( ) ; for ( String server : servers ) { String dc = cfg . getDataCenterOfServer ( server ) ; Set < String > dcConfig = result . get ( dc ) ; if ( dcConfig == null ) { dcConfig = new HashSet < > ( ) ; result . put ( dc , dcConfig ) ; } dcConfig . add ( server ) ; } return result ;


signature:
public class ODatabaseDocumentDistributed { /** * @ param transactionId
 * @ return null returned means that commit failed */
public boolean commit2pc ( ODistributedRequestId transactionId , boolean local ) { } }

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


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

implementation: return "create index `" + indexName + "` " + indexType + ' ' + "runtime " + serializer . getId ( ) ;


signature:
public class OSymmetricKey { /** * Returns the secret key algorithm portion of the cipher transformation . */
protected static String separateAlgorithm ( final String cipherTransform ) { } }

implementation: String [ ] array = cipherTransform . split ( "/" ) ; if ( array . length > 1 ) return array [ 0 ] ; return null ;


signature:
public class OSymmetricKey { /** * Creates an OSymmetricKey from an OSymmetricKeyConfig interface . */
public static OSymmetricKey fromConfig ( final OSymmetricKeyConfig keyConfig ) { } }

implementation: if ( keyConfig . usesKeyString ( ) ) { return fromString ( keyConfig . getKeyAlgorithm ( ) , keyConfig . getKeyString ( ) ) ; } else if ( keyConfig . usesKeyFile ( ) ) { return fromFile ( keyConfig . getKeyAlgorithm ( ) , keyConfig . getKeyFile ( ) ) ; } else if ( keyConfig . usesKeystore ( ) ) { return fromKeystore ( keyConfig . getKeystoreFile ( ) , keyConfig . getKeystorePassword ( ) , keyConfig . getKeystoreKeyAlias ( ) , keyConfig . getKeystoreKeyPassword ( ) ) ; } else { throw new OSecurityException ( "OSymmetricKey(OSymmetricKeyConfig) Invalid configuration" ) ; }


signature:
public class OSymmetricKey { /** * Creates an OSymmetricKey from a file containing a Base64 key . */
public static OSymmetricKey fromFile ( final String algorithm , final String path ) { } }

implementation: String base64Key = null ; try { java . io . FileInputStream fis = null ; try { fis = new java . io . FileInputStream ( OSystemVariableResolver . resolveSystemVariables ( path ) ) ; return fromStream ( algorithm , fis ) ; } finally { if ( fis != null ) fis . close ( ) ; } } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.fromFile() Exception: " + ex . getMessage ( ) ) , ex ) ; }


signature:
public class OSymmetricKey { /** * Creates an OSymmetricKey from an InputStream containing a Base64 key . */
public static OSymmetricKey fromStream ( final String algorithm , final InputStream is ) { } }

implementation: String base64Key = null ; try { base64Key = OIOUtils . readStreamAsString ( is ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.fromStream() Exception: " + ex . getMessage ( ) ) , ex ) ; } return new OSymmetricKey ( algorithm , base64Key ) ;


signature:
public class OSymmetricKey { /** * Creates an OSymmetricKey from a Java " JCEKS " KeyStore .
 * @ param path The location of the KeyStore file .
 * @ param password The password for the KeyStore . May be null .
 * @ param keyAlias The alias name of the key to be used from the KeyStore . Required .
 * @ param keyPassword The password of the key represented by keyAlias . May be null . */
public static OSymmetricKey fromKeystore ( final String path , final String password , final String keyAlias , final String keyPassword ) { } }

implementation:
OSymmetricKey sk = null ; try { KeyStore ks = KeyStore . getInstance ( "JCEKS" ) ; // JCEKS is required to hold SecretKey entries .
java . io . FileInputStream fis = null ; try { fis = new java . io . FileInputStream ( OSystemVariableResolver . resolveSystemVariables ( path ) ) ; return fromKeystore ( fis , password , keyAlias , keyPassword ) ; } finally { if ( fis != null ) fis . close ( ) ; } } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.fromKeystore() Exception: " + ex . getMessage ( ) ) , ex ) ; }


signature:
public class OSymmetricKey { /** * Creates an OSymmetricKey from a Java " JCEKS " KeyStore .
 * @ param is The InputStream used to load the KeyStore .
 * @ param password The password for the KeyStore . May be null .
 * @ param keyAlias The alias name of the key to be used from the KeyStore . Required .
 * @ param keyPassword The password of the key represented by keyAlias . May be null . */
public static OSymmetricKey fromKeystore ( final InputStream is , final String password , final String keyAlias , final String keyPassword ) { } }

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


signature:
public class OSymmetricKey { /** * This is a convenience method that takes a String argument , encodes it as Base64 , then calls encrypt ( byte [ ] ) .
 * @ param value The String to be encoded to Base64 then encrypted .
 * @ return A Base64 - encoded JSON document . */
public String encrypt ( final String value ) { } }

implementation: try { return encrypt ( value . getBytes ( "UTF8" ) ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.encrypt() Exception: " + ex . getMessage ( ) ) , ex ) ; }


signature:
public class OSymmetricKey { /** * This method encrypts an array of bytes .
 * @ param transform The cipher transformation to use .
 * @ param bytes The array of bytes to be encrypted .
 * @ return The encrypted bytes as a Base64 - encoded JSON document or null if unsuccessful . */
public String encrypt ( final String transform , final byte [ ] bytes ) { } }

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


signature:
public class OSymmetricKey { /** * This method decrypts the Base64 - encoded JSON document using the specified algorithm and cipher transformation .
 * @ param encodedJSON The Base64 - encoded JSON document .
 * @ return The decrypted array of bytes as a UTF8 String or null if not successful . */
public String decryptAsString ( final String encodedJSON ) { } }

implementation: try { byte [ ] decrypted = decrypt ( encodedJSON ) ; return new String ( decrypted , "UTF8" ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.decryptAsString() Exception: " + ex . getMessage ( ) ) , ex ) ; }


signature:
public class OSymmetricKey { /** * This method decrypts the Base64 - encoded JSON document using the specified algorithm and cipher transformation .
 * @ param encodedJSON The Base64 - encoded JSON document .
 * @ return The decrypted array of bytes or null if unsuccessful . */
public byte [ ] decrypt ( final String encodedJSON ) { } }

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


signature:
public class OSymmetricKey { /** * Saves the internal SecretKey to the specified OutputStream as a Base64 String . */
public void saveToStream ( final OutputStream os ) { } }

implementation: if ( os == null ) throw new OSecurityException ( "OSymmetricKey.saveToStream() OutputStream is null" ) ; try { final OutputStreamWriter osw = new OutputStreamWriter ( os ) ; try { final BufferedWriter writer = new BufferedWriter ( osw ) ; try { writer . write ( getBase64Key ( ) ) ; } finally { writer . close ( ) ; } } finally { os . close ( ) ; } } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( "OSymmetricKey.saveToStream() Exception: " + ex . getMessage ( ) ) , ex ) ; }


signature:
public class OSymmetricKey { /** * Saves the internal SecretKey as a KeyStore . */
public void saveToKeystore ( final OutputStream os , final String ksPasswd , final String keyAlias , final String keyPasswd ) { } }

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


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

implementation: buffer . putLong ( object . getMostSignificantBits ( ) ) ; buffer . putLong ( object . getLeastSignificantBits ( ) ) ;


signature:
public class OUUIDSerializer { /** * { @ inheritDoc } */
@ Override public UUID deserializeFromByteBufferObject ( ByteBuffer buffer ) { } }

implementation: final long mostSignificantBits = buffer . getLong ( ) ; final long leastSignificantBits = buffer . getLong ( ) ; return new UUID ( mostSignificantBits , leastSignificantBits ) ;


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

implementation: final long mostSignificantBits = walChanges . getLongValue ( buffer , offset ) ; final long leastSignificantBits = walChanges . getLongValue ( buffer , offset + OLongSerializer . LONG_SIZE ) ; return new UUID ( mostSignificantBits , leastSignificantBits ) ;


signature:
public class OBasicCommandContext { /** * Set the inherited context avoiding to copy all the values every time .
 * @ return */
public OCommandContext setChild ( final OCommandContext iContext ) { } }

implementation:
if ( iContext == null ) { if ( child != null ) { // REMOVE IT
child . setParent ( null ) ; child = null ; } } else if ( child != iContext ) { // ADD IT
child = iContext ; iContext . setParent ( this ) ; } return this ;


signature:
public class OBasicCommandContext { /** * adds an item to the unique result set
 * @ param o the result item to add
 * @ return true if the element is successfully added ( it was not present yet ) , false otherwise ( it was already present ) */
public synchronized boolean addToUniqueResult ( Object o ) { } }

implementation: Object toAdd = o ; if ( o instanceof ODocument && ( ( ODocument ) o ) . getIdentity ( ) . isNew ( ) ) { toAdd = new ODocumentEqualityWrapper ( ( ODocument ) o ) ; } return this . uniqueResult . add ( toAdd ) ;


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

implementation: buffer . putInt ( object . scale ( ) ) ; OBinaryTypeSerializer . INSTANCE . serializeInByteBufferObject ( object . unscaledValue ( ) . toByteArray ( ) , buffer ) ;


signature:
public class ODecimalSerializer { /** * { @ inheritDoc } */
@ Override public BigDecimal deserializeFromByteBufferObject ( ByteBuffer buffer ) { } }

implementation: final int scale = buffer . getInt ( ) ; final byte [ ] unscaledValue = OBinaryTypeSerializer . INSTANCE . deserializeFromByteBufferObject ( buffer ) ; return new BigDecimal ( new BigInteger ( unscaledValue ) , scale ) ;


signature:
public class ODecimalSerializer { /** * { @ inheritDoc } */
@ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer ) { } }

implementation: buffer . position ( buffer . position ( ) + OIntegerSerializer . INT_SIZE ) ; return OIntegerSerializer . INT_SIZE + OBinaryTypeSerializer . INSTANCE . getObjectSizeInByteBuffer ( buffer ) ;


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

implementation: final int scale = walChanges . getIntValue ( buffer , offset ) ; offset += OIntegerSerializer . INT_SIZE ; final byte [ ] unscaledValue = OBinaryTypeSerializer . INSTANCE . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ; return new BigDecimal ( new BigInteger ( unscaledValue ) , scale ) ;


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

implementation: return OIntegerSerializer . INT_SIZE + OBinaryTypeSerializer . INSTANCE . getObjectSizeInByteBuffer ( buffer , walChanges , offset + OIntegerSerializer . INT_SIZE ) ;


signature:
public class ORecordSerializerJSON { /** * OBJECT OR MAP . CHECK THE TYPE ATTRIBUTE TO KNOW IT . */
private Object getValueAsObjectOrMap ( ODocument iRecord , String iFieldValue , OType iType , OType iLinkedType , Map < String , Character > iFieldTypes , boolean iNoMap , String iOptions ) { } }

implementation: final String [ ] fields = OStringParser . getWords ( iFieldValue . substring ( 1 , iFieldValue . length ( ) - 1 ) , ":," , true ) ; if ( fields == null || fields . length == 0 ) if ( iNoMap ) { ODocument res = new ODocument ( ) ; ODocumentInternal . addOwner ( res , iRecord ) ; return res ; } else return new HashMap < String , Object > ( ) ; if ( iNoMap || hasTypeField ( fields ) ) { return getValueAsRecord ( iRecord , iFieldValue , iType , iOptions , fields ) ; } else { return getValueAsMap ( iRecord , iFieldValue , iLinkedType , iFieldTypes , false , iOptions , fields ) ; }


signature:
public class OServerCommandPostAuthToken { /** * null is returned in all other cases and means authentication was unsuccessful . */
protected String authenticate ( final String username , final String password , final String iDatabaseName ) throws IOException { } }

implementation:
ODatabaseDocument db = null ; String userRid = null ; try { db = ( ODatabaseDocument ) server . openDatabase ( iDatabaseName , username , password ) ; userRid = ( db . getUser ( ) == null ? "<server user>" : db . getUser ( ) . getDocument ( ) . getIdentity ( ) . toString ( ) ) ; } catch ( OSecurityAccessException e ) { // WRONG USER / PASSWD
} catch ( OLockException e ) { OLogManager . instance ( ) . error ( this , "Cannot access to the database '" + iDatabaseName + "'" , e ) ; } finally { if ( db != null ) { db . close ( ) ; } } return userRid ;


signature:
public class ODocumentHelper { /** * Retrieves the value crossing the map with the dotted notation
 * @ param iKey Field ( s ) to retrieve . If are multiple fields , then the dot must be used as separator
 * @ param iMap
 * @ return */
@ SuppressWarnings ( "unchecked" ) public static Object getMapEntry ( final Map < String , ? > iMap , final Object iKey ) { } }

implementation: if ( iMap == null || iKey == null ) return null ; if ( iKey instanceof String ) { String iName = ( String ) iKey ; int pos = iName . indexOf ( '.' ) ; if ( pos > - 1 ) iName = iName . substring ( 0 , pos ) ; final Object value = iMap . get ( iName ) ; if ( value == null ) return null ; if ( pos > - 1 ) { final String restFieldName = iName . substring ( pos + 1 ) ; if ( value instanceof ODocument ) return getFieldValue ( value , restFieldName ) ; else if ( value instanceof Map < ? , ? > ) return getMapEntry ( ( Map < String , ? > ) value , restFieldName ) ; } return value ; } else return iMap . get ( iKey ) ;


signature:
public class ODocumentHelper { /** * Makes a deep comparison field by field to check if the passed ODocument instance is identical as identity and content to the
 * current one . Instead equals ( ) just checks if the RID are the same .
 * @ param iOther ODocument instance
 * @ return true if the two document are identical , otherwise false
 * @ see # equals ( Object ) */
@ SuppressWarnings ( "unchecked" ) public static boolean hasSameContentOf ( final ODocument iCurrent , final ODatabaseDocumentInternal iMyDb , final ODocument iOther , final ODatabaseDocumentInternal iOtherDb , RIDMapper ridMapper ) { } }

implementation: return hasSameContentOf ( iCurrent , iMyDb , iOther , iOtherDb , ridMapper , true ) ;


signature:
public class ODocumentHelper { /** * Makes a deep comparison field by field to check if the passed ODocument instance is identical in the content to the current
 * one . Instead equals ( ) just checks if the RID are the same .
 * @ param iOther ODocument instance
 * @ return true if the two document are identical , otherwise false
 * @ see # equals ( Object ) */
@ SuppressWarnings ( "unchecked" ) public static boolean hasSameContentOf ( final ODocument iCurrent , final ODatabaseDocumentInternal iMyDb , final ODocument iOther , final ODatabaseDocumentInternal iOtherDb , RIDMapper ridMapper , final boolean iCheckAlsoIdentity ) { } }

implementation:
if ( iOther == null ) return false ; if ( iCheckAlsoIdentity && iCurrent . getIdentity ( ) . isValid ( ) && ! iCurrent . getIdentity ( ) . equals ( iOther . getIdentity ( ) ) ) return false ; if ( iMyDb != null ) makeDbCall ( iMyDb , new ODbRelatedCall < Object > ( ) { public Object call ( ODatabaseDocumentInternal database ) { if ( iCurrent . getInternalStatus ( ) == STATUS . NOT_LOADED ) iCurrent . reload ( ) ; return null ; } } ) ; if ( iOtherDb != null ) makeDbCall ( iOtherDb , new ODbRelatedCall < Object > ( ) { public Object call ( ODatabaseDocumentInternal database ) { if ( iOther . getInternalStatus ( ) == STATUS . NOT_LOADED ) iOther . reload ( ) ; return null ; } } ) ; if ( iMyDb != null ) makeDbCall ( iMyDb , new ODbRelatedCall < Object > ( ) { public Object call ( ODatabaseDocumentInternal database ) { iCurrent . checkForFields ( ) ; return null ; } } ) ; else iCurrent . checkForFields ( ) ; if ( iOtherDb != null ) makeDbCall ( iOtherDb , new ODbRelatedCall < Object > ( ) { public Object call ( ODatabaseDocumentInternal database ) { iOther . checkForFields ( ) ; return null ; } } ) ; else iOther . checkForFields ( ) ; if ( iCurrent . fields ( ) != iOther . fields ( ) ) return false ; // CHECK FIELD - BY - FIELD
Object myFieldValue ; Object otherFieldValue ; for ( Entry < String , Object > f : iCurrent ) { myFieldValue = f . getValue ( ) ; otherFieldValue = iOther . _fields . get ( f . getKey ( ) ) . value ; if ( myFieldValue == otherFieldValue ) continue ; // CHECK FOR NULLS
if ( myFieldValue == null ) { if ( otherFieldValue != null ) return false ; } else if ( otherFieldValue == null ) return false ; if ( myFieldValue != null ) if ( myFieldValue instanceof Set && otherFieldValue instanceof Set ) { if ( ! compareSets ( iMyDb , ( Set < ? > ) myFieldValue , iOtherDb , ( Set < ? > ) otherFieldValue , ridMapper ) ) return false ; } else if ( myFieldValue instanceof Collection && otherFieldValue instanceof Collection ) { if ( ! compareCollections ( iMyDb , ( Collection < ? > ) myFieldValue , iOtherDb , ( Collection < ? > ) otherFieldValue , ridMapper ) ) return false ; } else if ( myFieldValue instanceof ORidBag && otherFieldValue instanceof ORidBag ) { if ( ! compareBags ( iMyDb , ( ORidBag ) myFieldValue , iOtherDb , ( ORidBag ) otherFieldValue , ridMapper ) ) return false ; } else if ( myFieldValue instanceof Map && otherFieldValue instanceof Map ) { if ( ! compareMaps ( iMyDb , ( Map < Object , Object > ) myFieldValue , iOtherDb , ( Map < Object , Object > ) otherFieldValue , ridMapper ) ) return false ; } else if ( myFieldValue instanceof ODocument && otherFieldValue instanceof ODocument ) { if ( ! hasSameContentOf ( ( ODocument ) myFieldValue , iMyDb , ( ODocument ) otherFieldValue , iOtherDb , ridMapper ) ) return false ; } else { if ( ! compareScalarValues ( myFieldValue , iMyDb , otherFieldValue , iOtherDb , ridMapper ) ) return false ; } } return true ;


signature:
public class OClientConnection { /** * Returns the remote network address in the format < ip > : < port > . */
public String getRemoteAddress ( ) { } }

implementation: Socket socket = null ; if ( getProtocol ( ) != null ) { socket = getProtocol ( ) . getChannel ( ) . socket ; } else { for ( ONetworkProtocol protocol : this . protocols ) { socket = protocol . getChannel ( ) . socket ; if ( socket != null ) break ; } } if ( socket != null ) { final InetSocketAddress remoteAddress = ( InetSocketAddress ) socket . getRemoteSocketAddress ( ) ; return remoteAddress . getAddress ( ) . getHostAddress ( ) + ":" + remoteAddress . getPort ( ) ; } return null ;


signature:
public class OIdentifiableIterator { /** * Return the record to use for the operation .
 * @ return the record to use for the operation . */
protected ORecord getRecord ( ) { } }

implementation:
final ORecord record ; if ( reusedRecord != null ) { // REUSE THE SAME RECORD AFTER HAVING RESETTED IT
record = reusedRecord ; record . reset ( ) ; } else record = null ; return record ;


signature:
public class OIdentifiableIterator { /** * Read the current record and increment the counter if the record was found .
 * @ param iRecord to read value from database inside it . If record is null link will be created and stored in it .
 * @ return record which was read from db . */
protected ORecord readCurrentRecord ( ORecord iRecord , final int iMovement ) { } }

implementation:
if ( limit > - 1 && browsedRecords >= limit ) // LIMIT REACHED
return null ; do { final boolean moveResult ; switch ( iMovement ) { case 1 : moveResult = nextPosition ( ) ; break ; case - 1 : moveResult = prevPosition ( ) ; break ; case 0 : moveResult = checkCurrentPosition ( ) ; break ; default : throw new IllegalStateException ( "Invalid movement value : " + iMovement ) ; } if ( ! moveResult ) return null ; try { if ( iRecord != null ) { ORecordInternal . setIdentity ( iRecord , new ORecordId ( current . getClusterId ( ) , current . getClusterPosition ( ) ) ) ; iRecord = database . load ( iRecord , fetchPlan , false ) ; } else iRecord = database . load ( current , fetchPlan , false ) ; } catch ( ODatabaseException e ) { if ( Thread . interrupted ( ) || database . isClosed ( ) ) // THREAD INTERRUPTED : RETURN
throw e ; if ( e . getCause ( ) instanceof OSecurityException ) throw e ; brokenRIDs . add ( current . copy ( ) ) ; OLogManager . instance ( ) . error ( this , "Error on fetching record during browsing. The record has been skipped" , e ) ; } if ( iRecord != null ) { browsedRecords ++ ; return iRecord ; } } while ( iMovement != 0 ) ; return null ;


signature:
public class OIncrementalServerSync { /** * Deleted records are written in output stream first , then created / updated records . All records are sorted by record id .
 * Each record in output stream is written using following format :
 * < ol >
 * < li > Record ' s cluster id - 4 bytes < / li >
 * < li > Record ' s cluster position - 8 bytes < / li >
 * < li > Delete flag , 1 if record is deleted - 1 byte < / li >
 * < li > Record version , only if record is not deleted - 4 bytes < / li >
 * < li > Record type , only if record is not deleted - 1 byte < / li >
 * < li > Length of binary presentation of record , only if record is not deleted - 4 bytes < / li >
 * < li > Binary presentation of the record , only if record is not deleted - length of content is provided in above entity < / li >
 * < / ol > */
public void importDelta ( final OServer serverInstance , final String databaseName , final FileInputStream in , final String iNode ) throws IOException { } }

implementation:
final String nodeName = serverInstance . getDistributedManager ( ) . getLocalNodeName ( ) ; final ODatabaseDocumentInternal db = serverInstance . openDatabase ( databaseName ) ; try { OScenarioThreadLocal . executeAsDistributed ( new Callable < Object > ( ) { @ Override public Object call ( ) throws Exception { db . activateOnCurrentThread ( ) ; long totalRecords = 0 ; long totalCreated = 0 ; long totalUpdated = 0 ; long totalDeleted = 0 ; long totalHoles = 0 ; long totalSkipped = 0 ; ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , "Started import of delta for database '" + db . getName ( ) + "'" ) ; long lastLap = System . currentTimeMillis ( ) ; // final GZIPInputStream gzipInput = new GZIPInputStream ( in ) ;
try { final DataInputStream input = new DataInputStream ( in ) ; try { final long records = input . readLong ( ) ; for ( long i = 0 ; i < records ; ++ i ) { final int clusterId = input . readInt ( ) ; final long clusterPos = input . readLong ( ) ; final boolean deleted = input . readBoolean ( ) ; final ORecordId rid = new ORecordId ( clusterId , clusterPos ) ; totalRecords ++ ; final OPaginatedCluster cluster = ( OPaginatedCluster ) db . getStorage ( ) . getUnderlying ( ) . getClusterById ( rid . getClusterId ( ) ) ; final OPaginatedCluster . RECORD_STATUS recordStatus = cluster . getRecordStatus ( rid . getClusterPosition ( ) ) ; ORecord newRecord = null ; if ( deleted ) { ODistributedServerLog . debug ( this , nodeName , iNode , DIRECTION . IN , "DELTA <- deleting %s" , rid ) ; switch ( recordStatus ) { case REMOVED : // SKIP IT
totalSkipped ++ ; continue ; case ALLOCATED : case PRESENT : // DELETE IT
db . delete ( rid ) ; break ; case NOT_EXISTENT : totalSkipped ++ ; break ; } totalDeleted ++ ; } else { final int recordVersion = input . readInt ( ) ; final int recordType = input . readByte ( ) ; final int recordSize = input . readInt ( ) ; final byte [ ] recordContent = new byte [ recordSize ] ; input . read ( recordContent ) ; switch ( recordStatus ) { case REMOVED : // SKIP IT
totalSkipped ++ ; continue ; case ALLOCATED : case PRESENT : // UPDATE IT
newRecord = Orient . instance ( ) . getRecordFactoryManager ( ) . newInstance ( ( byte ) recordType , rid . getClusterId ( ) , null ) ; ORecordInternal . fill ( newRecord , rid , ORecordVersionHelper . setRollbackMode ( recordVersion ) , recordContent , true ) ; final ORecord loadedRecord = rid . getRecord ( ) ; if ( loadedRecord instanceof ODocument ) { // APPLY CHANGES FIELD BY FIELD TO MARK DIRTY FIELDS FOR INDEXES / HOOKS
ODocument loadedDocument = ( ODocument ) loadedRecord ; loadedDocument . merge ( ( ODocument ) newRecord , false , false ) ; ORecordInternal . setVersion ( loadedRecord , ORecordVersionHelper . setRollbackMode ( recordVersion ) ) ; loadedDocument . setDirty ( ) ; newRecord = loadedDocument ; } // SAVE THE UPDATE RECORD
newRecord . save ( ) ; ODistributedServerLog . debug ( this , nodeName , iNode , DIRECTION . IN , "DELTA <- updating rid=%s type=%d size=%d v=%d content=%s" , rid , recordType , recordSize , recordVersion , newRecord ) ; totalUpdated ++ ; break ; case NOT_EXISTENT : // CREATE AND DELETE RECORD IF NEEDED
do { newRecord = Orient . instance ( ) . getRecordFactoryManager ( ) . newInstance ( ( byte ) recordType , rid . getClusterId ( ) , null ) ; ORecordInternal . fill ( newRecord , new ORecordId ( rid . getClusterId ( ) , - 1 ) , recordVersion , recordContent , true ) ; try { newRecord . save ( ) ; } catch ( ORecordNotFoundException e ) { ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , "DELTA <- error on saving record (not found) rid=%s type=%d size=%d v=%d content=%s" , rid , recordType , recordSize , recordVersion , newRecord ) ; } catch ( ORecordDuplicatedException e ) { ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , "DELTA <- error on saving record (duplicated %s) rid=%s type=%d size=%d v=%d content=%s" , e . getRid ( ) , rid , recordType , recordSize , recordVersion , newRecord ) ; // throw OException . wrapException (
// new ODistributedDatabaseDeltaSyncException ( " Error on delta sync : found duplicated record " + rid ) , e ) ;
final ORecord duplicatedRecord = db . load ( e . getRid ( ) , null , true ) ; if ( duplicatedRecord == null ) { // RECORD REMOVED : THE INDEX IS DIRTY , FIX THE DIRTY INDEX
final ODocument doc = ( ODocument ) newRecord ; final OIndex < ? > index = db . getMetadata ( ) . getIndexManager ( ) . getIndex ( e . getIndexName ( ) ) ; final List < String > fields = index . getDefinition ( ) . getFields ( ) ; final List < Object > values = new ArrayList < Object > ( fields . size ( ) ) ; for ( String f : fields ) { values . add ( doc . field ( f ) ) ; } final Object keyValue = index . getDefinition ( ) . createValue ( values ) ; index . remove ( keyValue , e . getRid ( ) ) ; // RESAVE THE RECORD
newRecord . save ( ) ; } else break ; } if ( newRecord . getIdentity ( ) . getClusterPosition ( ) < clusterPos ) { // DELETE THE RECORD TO CREATE A HOLE
ODistributedServerLog . debug ( this , nodeName , iNode , DIRECTION . IN , "DELTA <- creating hole rid=%s" , newRecord . getIdentity ( ) ) ; newRecord . delete ( ) ; totalHoles ++ ; } } while ( newRecord . getIdentity ( ) . getClusterPosition ( ) < clusterPos ) ; ODistributedServerLog . debug ( this , nodeName , iNode , DIRECTION . IN , "DELTA <- creating rid=%s type=%d size=%d v=%d content=%s" , rid , recordType , recordSize , recordVersion , newRecord ) ; totalCreated ++ ; break ; } if ( newRecord . getIdentity ( ) . isPersistent ( ) && ! newRecord . getIdentity ( ) . equals ( rid ) ) throw new ODistributedDatabaseDeltaSyncException ( "Error on synchronization of records, rids are different: saved " + newRecord . getIdentity ( ) + ", but it should be " + rid ) ; } final long now = System . currentTimeMillis ( ) ; if ( now - lastLap > 2000 ) { // DUMP STATS EVERY SECOND
ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , "- %,d total entries: %,d created, %,d updated, %,d deleted, %,d holes, %,d skipped..." , totalRecords , totalCreated , totalUpdated , totalDeleted , totalHoles , totalSkipped ) ; lastLap = now ; } } db . getMetadata ( ) . reload ( ) ; } finally { input . close ( ) ; } } catch ( Exception e ) { ODistributedServerLog . error ( this , nodeName , iNode , DIRECTION . IN , "Error on installing database delta '%s' on local server" , e , db . getName ( ) ) ; throw OException . wrapException ( new ODistributedException ( "Error on installing database delta '" + db . getName ( ) + "' on local server" ) , e ) ; } finally { // gzipInput . close ( ) ;
} ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , "Installed database delta for '%s'. %d total entries: %d created, %d updated, %d deleted, %d holes, %,d skipped" , db . getName ( ) , totalRecords , totalCreated , totalUpdated , totalDeleted , totalHoles , totalSkipped ) ; return null ; } } ) ; db . activateOnCurrentThread ( ) ; } catch ( Exception e ) { // FORCE FULL DATABASE SYNC
ODistributedServerLog . error ( this , nodeName , iNode , DIRECTION . IN , "Error while applying changes of database delta sync on '%s': forcing full database sync..." , e , db . getName ( ) ) ; throw OException . wrapException ( new ODistributedDatabaseDeltaSyncException ( "Error while applying changes of database delta sync on '" + db . getName ( ) + "': forcing full database sync..." ) , e ) ; }


signature:
public class OSQLFunctionHeuristicPathFinderAbstract { /** * obtains from https : / / github . com / enderceylan / CS - 314 - - Data - Structures / blob / master / HW10 - Graph . java */
public double gcdist ( double lata , double longa , double latb , double longb ) { } }

implementation: double midlat , psi , dist ; midlat = 0.5 * ( lata + latb ) ; psi = 0.0174532925 * Math . sqrt ( Math . pow ( lata - latb , 2 ) + Math . pow ( ( longa - longb ) * Math . cos ( 0.0174532925 * midlat ) , 2 ) ) ; dist = 6372.640112 * psi ; return dist ;


signature:
public class OSQLFunctionHeuristicPathFinderAbstract { /** * obtains from http : / / theory . stanford . edu / ~ amitp / GameProgramming / Heuristics . html */
protected double getSimpleHeuristicCost ( double x , double g , double dFactor ) { } }

implementation: double dx = Math . abs ( x - g ) ; return dFactor * ( dx ) ;


signature:
public class OSQLFunctionHeuristicPathFinderAbstract { /** * obtains from http : / / theory . stanford . edu / ~ amitp / GameProgramming / Heuristics . html */
protected double getManhatanHeuristicCost ( double x , double y , double gx , double gy , double dFactor ) { } }

implementation: double dx = Math . abs ( x - gx ) ; double dy = Math . abs ( y - gy ) ; return dFactor * ( dx + dy ) ;


signature:
public class OSQLFunctionHeuristicPathFinderAbstract { /** * obtains from http : / / theory . stanford . edu / ~ amitp / GameProgramming / Heuristics . html */
protected double getDiagonalHeuristicCost ( double x , double y , double gx , double gy , double dFactor ) { } }

implementation: double dx = Math . abs ( x - gx ) ; double dy = Math . abs ( y - gy ) ; double h_diagonal = Math . min ( dx , dy ) ; double h_straight = dx + dy ; return ( dFactor * 2 ) * h_diagonal + dFactor * ( h_straight - 2 * h_diagonal ) ;


signature:
public class OSQLFunctionHeuristicPathFinderAbstract { /** * obtains from http : / / theory . stanford . edu / ~ amitp / GameProgramming / Heuristics . html */
protected double getEuclideanHeuristicCost ( double x , double y , double gx , double gy , double dFactor ) { } }

implementation: double dx = Math . abs ( x - gx ) ; double dy = Math . abs ( y - gy ) ; return ( dFactor * Math . sqrt ( Math . pow ( dx , 2 ) + Math . pow ( dy , 2 ) ) ) ;


signature:
public class OSQLFunctionHeuristicPathFinderAbstract { /** * obtains from http : / / theory . stanford . edu / ~ amitp / GameProgramming / Heuristics . html */
protected double getTieBreakingHeuristicCost ( double x , double y , double sx , double sy , double gx , double gy , double heuristic ) { } }

implementation: double dx1 = x - gx ; double dy1 = y - gy ; double dx2 = sx - gx ; double dy2 = sy - gy ; double cross = Math . abs ( dx1 * dy2 - dx2 * dy1 ) ; heuristic += ( cross * 0.0001 ) ; return heuristic ;


signature:
public class OrientGraphFactory { /** * Gets transactional graph with the database from pool if pool is configured . Otherwise creates a graph with new db instance . The
 * Graph instance inherits the factory ' s configuration .
 * @ return transactional graph */
public OrientGraph getTx ( ) { } }

implementation:
final OrientGraph g ; if ( pool == null ) { g = ( OrientGraph ) getTxGraphImplFactory ( ) . getGraph ( getDatabase ( ) , user , password , settings ) ; } else { // USE THE POOL
g = ( OrientGraph ) getTxGraphImplFactory ( ) . getGraph ( pool , settings ) ; } initGraph ( g ) ; return g ;


signature:
public class OrientGraphFactory { /** * Gets non transactional graph with the database from pool if pool is configured . Otherwise creates a graph with new db instance .
 * The Graph instance inherits the factory ' s configuration .
 * @ return non transactional graph */
public OrientGraphNoTx getNoTx ( ) { } }

implementation:
final OrientGraphNoTx g ; if ( pool == null ) { g = ( OrientGraphNoTx ) getNoTxGraphImplFactory ( ) . getGraph ( getDatabase ( ) , user , password , settings ) ; } else { // USE THE POOL
g = ( OrientGraphNoTx ) getNoTxGraphImplFactory ( ) . getGraph ( pool , settings ) ; } initGraph ( g ) ; return g ;


signature:
public class OrientGraphFactory { /** * Gives new connection to database . If current factory configured to use pool ( see { @ link # setupPool ( int , int ) } method ) ,
 * retrieves connection from pool . Otherwise creates new connection each time .
 * @ param iCreate if true automatically creates database if database with given URL does not exist
 * @ param iOpen if true automatically opens the database
 * @ return database */
public ODatabaseDocumentTx getDatabase ( final boolean iCreate , final boolean iOpen ) { } }

implementation: if ( pool != null ) return pool . acquire ( ) ; final ODatabaseDocument db = new ODatabaseDocumentTx ( url ) ; if ( properties != null ) { properties . entrySet ( ) . forEach ( e -> db . setProperty ( e . getKey ( ) , e . getValue ( ) ) ) ; } if ( ! db . getURL ( ) . startsWith ( "remote:" ) && ! db . exists ( ) ) { if ( iCreate ) db . create ( ) ; else if ( iOpen ) throw new ODatabaseException ( "Database '" + url + "' not found" ) ; } else if ( iOpen ) db . open ( user , password ) ; return ( ODatabaseDocumentTx ) db ;


signature:
public class OrientGraphFactory { /** * Check if the database with path given to the factory exists .
 * this api can be used only in embedded mode , and has no need of authentication .
 * @ return true if database is exists */
public boolean exists ( ) { } }

implementation: final ODatabaseDocument db = getDatabase ( false , false ) ; try { return db . exists ( ) ; } finally { db . close ( ) ; }


signature:
public class OrientGraphFactory { /** * Setting up the factory to use database pool instead of creation a new instance of database connection each time .
 * @ param iMin minimum size of pool
 * @ param iMax maximum size of pool
 * @ return this */
public OrientGraphFactory setupPool ( final int iMin , final int iMax ) { } }

implementation: if ( pool != null ) { pool . close ( ) ; } pool = new OPartitionedDatabasePool ( url , user , password , 8 , iMax ) . setAutoCreate ( true ) ; properties . entrySet ( ) . forEach ( p -> pool . setProperty ( p . getKey ( ) , p . getValue ( ) ) ) ; return this ;


signature:
public class OrientGraphFactory { /** * Gets the property value .
 * @ param iName Property name
 * @ return The previous value if any , otherwise null */
public Object getProperty ( final String iName ) { } }

implementation: return properties . get ( iName . toLowerCase ( Locale . ENGLISH ) ) ;


signature:
public class OrientTransactionalGraph { /** * Closes a transaction .
 * @ param conclusion Can be SUCCESS for commit and FAILURE to rollback . */
@ SuppressWarnings ( "deprecation" ) @ Override public void stopTransaction ( final Conclusion conclusion ) { } }

implementation: makeActive ( ) ; if ( getDatabase ( ) . isClosed ( ) || getDatabase ( ) . getTransaction ( ) instanceof OTransactionNoTx || getDatabase ( ) . getTransaction ( ) . getStatus ( ) != TXSTATUS . BEGUN ) return ; if ( Conclusion . SUCCESS == conclusion ) commit ( ) ; else rollback ( ) ;


signature:
public class OrientSql { /** * Root productions . */
final public OStatement parse ( ) throws ParseException { } }

implementation:
/* @ bgen ( jjtree ) parse */
Oparse jjtn000 = new Oparse ( JJTPARSE ) ; boolean jjtc000 = true ; jjtree . openNodeScope ( jjtn000 ) ; jjtn000 . jjtSetFirstToken ( getToken ( 1 ) ) ; OStatement result ; try { result = Statement ( ) ; jj_consume_token ( 0 ) ; jjtree . closeNodeScope ( jjtn000 , true ) ; jjtc000 = false ; jjtn000 . jjtSetLastToken ( getToken ( 0 ) ) ; { if ( true ) return result ; } } catch ( Throwable jjte000 ) { if ( jjtc000 ) { jjtree . clearNodeScope ( jjtn000 ) ; jjtc000 = false ; } else { jjtree . popNode ( ) ; } if ( jjte000 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte000 ; } } if ( jjte000 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte000 ; } } { if ( true ) throw ( Error ) jjte000 ; } } finally { if ( jjtc000 ) { jjtree . closeNodeScope ( jjtn000 , true ) ; jjtn000 . jjtSetLastToken ( getToken ( 0 ) ) ; } } throw new Error ( "Missing return statement in function" ) ;


signature:
public class OrientSql { /** * Get the next Token . */
final public Token getNextToken ( ) { } }

implementation: if ( token . next != null ) token = token . next ; else token = token . next = token_source . getNextToken ( ) ; jj_ntk = - 1 ; jj_gen ++ ; return token ;


signature:
public class OrientSql { /** * Get the specific Token . */
final public Token getToken ( int index ) { } }

implementation: Token t = token ; for ( int i = 0 ; i < index ; i ++ ) { if ( t . next != null ) t = t . next ; else t = t . next = token_source . getNextToken ( ) ; } return t ;


signature:
public class OrientSql { /** * Generate ParseException . */
public ParseException generateParseException ( ) { } }

implementation: jj_expentries . clear ( ) ; boolean [ ] la1tokens = new boolean [ 279 ] ; if ( jj_kind >= 0 ) { la1tokens [ jj_kind ] = true ; jj_kind = - 1 ; } for ( int i = 0 ; i < 424 ; i ++ ) { if ( jj_la1 [ i ] == jj_gen ) { for ( int j = 0 ; j < 32 ; j ++ ) { if ( ( jj_la1_0 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ j ] = true ; } if ( ( jj_la1_1 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 32 + j ] = true ; } if ( ( jj_la1_2 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 64 + j ] = true ; } if ( ( jj_la1_3 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 96 + j ] = true ; } if ( ( jj_la1_4 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 128 + j ] = true ; } if ( ( jj_la1_5 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 160 + j ] = true ; } if ( ( jj_la1_6 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 192 + j ] = true ; } if ( ( jj_la1_7 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 224 + j ] = true ; } if ( ( jj_la1_8 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 256 + j ] = true ; } } } } for ( int i = 0 ; i < 279 ; i ++ ) { if ( la1tokens [ i ] ) { jj_expentry = new int [ 1 ] ; jj_expentry [ 0 ] = i ; jj_expentries . add ( jj_expentry ) ; } } jj_endpos = 0 ; jj_rescan_token ( ) ; jj_add_error_token ( 0 , 0 ) ; int [ ] [ ] exptokseq = new int [ jj_expentries . size ( ) ] [ ] ; for ( int i = 0 ; i < jj_expentries . size ( ) ; i ++ ) { exptokseq [ i ] = jj_expentries . get ( i ) ; } return new ParseException ( token , exptokseq , tokenImage ) ;


signature:
public class OrientVertex { /** * ( Internal only ) Returns the field name used for the relationship .
 * @ param iDirection Direction between IN , OUT or BOTH
 * @ param iClassName Class name if any
 * @ param useVertexFieldsForEdgeLabels Graph setting about using the edge label as vertex ' s field */
public static String getConnectionFieldName ( final Direction iDirection , final String iClassName , final boolean useVertexFieldsForEdgeLabels ) { } }

implementation:
if ( iDirection == null || iDirection == Direction . BOTH ) throw new IllegalArgumentException ( "Direction not valid" ) ; if ( useVertexFieldsForEdgeLabels ) { // PREFIX " out _ " or " in _ " TO THE FIELD NAME
final String prefix = iDirection == Direction . OUT ? CONNECTION_OUT_PREFIX : CONNECTION_IN_PREFIX ; if ( iClassName == null || iClassName . isEmpty ( ) || iClassName . equals ( OrientEdgeType . CLASS_NAME ) ) return prefix ; return prefix + iClassName ; } else // " out " or " in "
return iDirection == Direction . OUT ? OrientBaseGraph . CONNECTION_OUT : OrientBaseGraph . CONNECTION_IN ;


signature:
public class OrientVertex { /** * ( Internal only ) */
public static String getInverseConnectionFieldName ( final String iFieldName , final boolean useVertexFieldsForEdgeLabels ) { } }

implementation:
if ( useVertexFieldsForEdgeLabels ) { if ( iFieldName . startsWith ( CONNECTION_OUT_PREFIX ) ) { if ( iFieldName . length ( ) == CONNECTION_OUT_PREFIX . length ( ) ) // " OUT " CASE
return CONNECTION_IN_PREFIX ; return CONNECTION_IN_PREFIX + iFieldName . substring ( CONNECTION_OUT_PREFIX . length ( ) ) ; } else if ( iFieldName . startsWith ( CONNECTION_IN_PREFIX ) ) { if ( iFieldName . length ( ) == CONNECTION_IN_PREFIX . length ( ) ) // " IN " CASE
return CONNECTION_OUT_PREFIX ; return CONNECTION_OUT_PREFIX + iFieldName . substring ( CONNECTION_IN_PREFIX . length ( ) ) ; } else throw new IllegalArgumentException ( "Cannot find reverse connection name for field " + iFieldName ) ; } if ( iFieldName . equals ( OrientBaseGraph . CONNECTION_OUT ) ) return OrientBaseGraph . CONNECTION_IN ; else if ( iFieldName . equals ( OrientBaseGraph . CONNECTION_IN ) ) return OrientBaseGraph . CONNECTION_OUT ; throw new IllegalArgumentException ( "Cannot find reverse connection name for field " + iFieldName ) ;


signature:
public class OrientVertex { /** * ( Internal only ) */
public static void replaceLinks ( final ODocument iVertex , final String iFieldName , final OIdentifiable iVertexToRemove , final OIdentifiable iNewVertex ) { } }

implementation:
if ( iVertex == null ) return ; final Object fieldValue = iVertexToRemove != null ? iVertex . field ( iFieldName ) : iVertex . removeField ( iFieldName ) ; if ( fieldValue == null ) return ; if ( fieldValue instanceof OIdentifiable ) { // SINGLE RECORD
if ( iVertexToRemove != null ) { if ( ! fieldValue . equals ( iVertexToRemove ) ) { return ; } iVertex . field ( iFieldName , iNewVertex ) ; } } else if ( fieldValue instanceof ORidBag ) { // COLLECTION OF RECORDS : REMOVE THE ENTRY
final ORidBag bag = ( ORidBag ) fieldValue ; boolean found = false ; final Iterator < OIdentifiable > it = bag . rawIterator ( ) ; while ( it . hasNext ( ) ) { if ( it . next ( ) . equals ( iVertexToRemove ) ) { // REMOVE THE OLD ENTRY
found = true ; it . remove ( ) ; } } if ( found ) // ADD THE NEW ONE
bag . add ( iNewVertex ) ; } else if ( fieldValue instanceof Collection ) { final Collection col = ( Collection ) fieldValue ; if ( col . remove ( iVertexToRemove ) ) col . add ( iNewVertex ) ; } iVertex . save ( ) ;


signature:
public class OrientVertex { /** * ( Internal only ) */
protected static OrientEdge getEdge ( final OrientBaseGraph graph , final ODocument doc , String fieldName , final OPair < Direction , String > connection , final Object fieldValue , final OIdentifiable iTargetVertex , final String [ ] iLabels ) { } }

implementation:
final OrientEdge toAdd ; final ODocument fieldRecord = ( ( OIdentifiable ) fieldValue ) . getRecord ( ) ; if ( fieldRecord == null ) return null ; OClass klass = ODocumentInternal . getImmutableSchemaClass ( fieldRecord ) ; if ( klass == null && ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) != null ) { ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) . getMetadata ( ) . reload ( ) ; klass = fieldRecord . getSchemaClass ( ) ; } if ( klass . isVertexType ( ) ) { if ( iTargetVertex != null && ! iTargetVertex . equals ( fieldValue ) ) return null ; // DIRECT VERTEX , CREATE A DUMMY EDGE BETWEEN VERTICES
if ( connection . getKey ( ) == Direction . OUT ) toAdd = graph . getEdgeInstance ( doc , fieldRecord , connection . getValue ( ) ) ; else toAdd = graph . getEdgeInstance ( fieldRecord , doc , connection . getValue ( ) ) ; } else if ( klass . isEdgeType ( ) ) { // EDGE
if ( iTargetVertex != null ) { Object targetVertex = OrientEdge . getConnection ( fieldRecord , connection . getKey ( ) . opposite ( ) ) ; if ( ! iTargetVertex . equals ( targetVertex ) ) return null ; } toAdd = graph . getEdge ( fieldRecord ) ; } else throw new IllegalStateException ( "Invalid content found in " + fieldName + " field: " + fieldRecord ) ; return toAdd ;


signature:
public class OrientVertex { /** * ( Blueprints Extension ) Executes the command predicate against current vertex . Use OSQLPredicate to execute SQL . Example : < code >
 * Iterable < OrientVertex > friendsOfFriends = ( Iterable < OrientVertex > ) luca . execute ( new OSQLPredicate ( " out ( ) . out ( ' Friend ' ) . out ( ' Friend ' ) " ) ) ;
 * < / code >
 * @ param iPredicate Predicate to evaluate . Use OSQLPredicate to use SQL */
public Object execute ( final OCommandPredicate iPredicate ) { } }

implementation: final Object result = iPredicate . evaluate ( rawElement . getRecord ( ) , null , null ) ; if ( result instanceof OAutoConvertToRecord ) ( ( OAutoConvertToRecord ) result ) . setAutoConvertToRecord ( true ) ; return result ;


signature:
public class OrientVertex { /** * Returns all the Property names as Set of String . out , in and label are not returned as properties even if are part of the
 * underlying document because are considered internal properties . */
@ Override public Set < String > getPropertyKeys ( ) { } }

implementation: final OrientBaseGraph graph = setCurrentGraphInThreadLocal ( ) ; final ODocument doc = getRecord ( ) ; final Set < String > result = new HashSet < String > ( ) ; for ( String field : doc . fieldNames ( ) ) if ( graph != null && settings . isUseVertexFieldsForEdgeLabels ( ) ) { if ( ! field . startsWith ( CONNECTION_OUT_PREFIX ) && ! field . startsWith ( CONNECTION_IN_PREFIX ) ) result . add ( field ) ; } else if ( ! field . equals ( OrientBaseGraph . CONNECTION_OUT ) && ! field . equals ( OrientBaseGraph . CONNECTION_IN ) ) result . add ( field ) ; return result ;


signature:
public class OrientVertex { /** * Returns a lazy iterable instance against vertices .
 * @ param iDirection The direction between OUT , IN or BOTH
 * @ param iLabels Optional varargs of Strings representing edge label to consider */
@ Override public Iterable < Vertex > getVertices ( final Direction iDirection , final String ... iLabels ) { } }

implementation:
setCurrentGraphInThreadLocal ( ) ; OrientBaseGraph . getEdgeClassNames ( getGraph ( ) , iLabels ) ; OrientBaseGraph . encodeClassNames ( iLabels ) ; final ODocument doc = getRecord ( ) ; final OMultiCollectionIterator < Vertex > iterable = new OMultiCollectionIterator < Vertex > ( ) ; for ( OTriple < String , Direction , String > connectionField : getConnectionFields ( iDirection , iLabels ) ) { String fieldName = connectionField . getKey ( ) ; OPair < Direction , String > connection = connectionField . getValue ( ) ; final Object fieldValue = doc . rawField ( fieldName ) ; if ( fieldValue != null ) if ( fieldValue instanceof OIdentifiable ) { addSingleVertex ( doc , iterable , fieldName , connection , fieldValue , iLabels ) ; } else if ( fieldValue instanceof Collection < ? > ) { Collection < ? > coll = ( Collection < ? > ) fieldValue ; if ( coll . size ( ) == 1 ) { // SINGLE ITEM : AVOID CALLING ITERATOR
if ( coll instanceof ORecordLazyMultiValue ) addSingleVertex ( doc , iterable , fieldName , connection , ( ( ORecordLazyMultiValue ) coll ) . rawIterator ( ) . next ( ) , iLabels ) ; else if ( coll instanceof List < ? > ) addSingleVertex ( doc , iterable , fieldName , connection , ( ( List < ? > ) coll ) . get ( 0 ) , iLabels ) ; else addSingleVertex ( doc , iterable , fieldName , connection , coll . iterator ( ) . next ( ) , iLabels ) ; } else { // CREATE LAZY Iterable AGAINST COLLECTION FIELD
if ( coll instanceof ORecordLazyMultiValue ) iterable . add ( new OrientVertexIterator ( this , coll , ( ( ORecordLazyMultiValue ) coll ) . rawIterator ( ) , connection , iLabels , coll . size ( ) ) ) ; else iterable . add ( new OrientVertexIterator ( this , coll , coll . iterator ( ) , connection , iLabels , - 1 ) ) ; } } else if ( fieldValue instanceof ORidBag ) { iterable . add ( new OrientVertexIterator ( this , fieldValue , ( ( ORidBag ) fieldValue ) . rawIterator ( ) , connection , iLabels , - 1 ) ) ; } } return iterable ;


signature:
public class OrientVertex { /** * Removes the current Vertex from the Graph . all the incoming and outgoing edges are automatically removed too . */
@ Override public void remove ( ) { } }

implementation:
checkClass ( ) ; final OrientBaseGraph graph = checkIfAttached ( ) ; graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; final ODocument doc = getRecord ( ) ; if ( doc == null ) throw ExceptionFactory . vertexWithIdDoesNotExist ( this . getId ( ) ) ; Map < String , List < ODocument > > treeRidbagEdgesToRemove = new HashMap < String , List < ODocument > > ( ) ; if ( ! graph . getRawGraph ( ) . getTransaction ( ) . isActive ( ) ) { for ( String fieldName : doc . fieldNames ( ) ) { final OPair < Direction , String > connection = getConnection ( Direction . BOTH , fieldName ) ; if ( connection == null ) // SKIP THIS FIELD
continue ; Object fv = doc . field ( fieldName ) ; if ( fv instanceof ORidBag && ! ( ( ORidBag ) fv ) . isEmbedded ( ) ) { List < ODocument > docs = new ArrayList < ODocument > ( ) ; for ( OIdentifiable id : ( ORidBag ) fv ) docs . add ( OrientBaseGraph . getDocument ( id , true ) ) ; treeRidbagEdgesToRemove . put ( fieldName , docs ) ; } } } // REMOVE THE VERTEX RECORD FIRST TO CATCH CME BEFORE EDGES ARE REMOVED
super . removeRecord ( ) ; // REMOVE THE VERTEX FROM MANUAL INDEXES
final Iterator < Index < ? extends Element > > it = graph . getIndices ( ) . iterator ( ) ; if ( it . hasNext ( ) ) { final Set < Edge > allEdges = new HashSet < Edge > ( ) ; for ( Edge e : getEdges ( Direction . BOTH ) ) allEdges . add ( e ) ; while ( it . hasNext ( ) ) { final Index < ? extends Element > index = it . next ( ) ; if ( Vertex . class . isAssignableFrom ( index . getIndexClass ( ) ) ) { OrientIndex < OrientVertex > idx = ( OrientIndex < OrientVertex > ) index ; idx . removeElement ( this ) ; } if ( Edge . class . isAssignableFrom ( index . getIndexClass ( ) ) ) { OrientIndex < OrientEdge > idx = ( OrientIndex < OrientEdge > ) index ; for ( Edge e : allEdges ) idx . removeElement ( ( OrientEdge ) e ) ; } } } for ( Map . Entry < String , List < ODocument > > entry : treeRidbagEdgesToRemove . entrySet ( ) ) { doc . removeField ( entry . getKey ( ) ) ; Iterator < ODocument > iter = entry . getValue ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { ODocument docEdge = iter . next ( ) ; OrientBaseGraph . deleteEdgeIfAny ( docEdge , false ) ; } } graph . removeEdgesInternal ( this , doc , null , true , settings . isUseVertexFieldsForEdgeLabels ( ) , settings . isAutoScaleEdgeType ( ) ) ;


signature:
public class OrientVertex { /** * Moves current vertex to another class / cluster . All edges are updated automatically .
 * @ param iClassName New class name to assign
 * @ param iClusterName Cluster name where to save the new vertex
 * @ return New vertex ' s identity
 * @ see # moveToClass ( String )
 * @ see # moveToCluster ( String ) */
public ORID moveTo ( final String iClassName , final String iClusterName ) { } }

implementation:
final OrientBaseGraph graph = getGraph ( ) ; if ( checkDeletedInTx ( ) ) graph . throwRecordNotFoundException ( getIdentity ( ) , "The vertex " + getIdentity ( ) + " has been deleted" ) ; final ORID oldIdentity = getIdentity ( ) . copy ( ) ; final ORecord oldRecord = oldIdentity . getRecord ( ) ; if ( oldRecord == null ) graph . throwRecordNotFoundException ( getIdentity ( ) , "The vertex " + getIdentity ( ) + " has been deleted" ) ; final ODocument doc = ( ( ODocument ) rawElement . getRecord ( ) ) . copy ( ) ; final Iterable < Edge > outEdges = getEdges ( Direction . OUT ) ; final Iterable < Edge > inEdges = getEdges ( Direction . IN ) ; // DELETE THE OLD RECORD FIRST TO AVOID ISSUES WITH UNIQUE CONSTRAINTS
copyRidBags ( oldRecord , doc ) ; removeEdgeLinks ( oldRecord ) ; oldRecord . delete ( ) ; if ( iClassName != null ) // OVERWRITE CLASS
doc . setClassName ( iClassName ) ; // SAVE THE NEW VERTEX
doc . setDirty ( ) ; // RESET IDENTITY
ORecordInternal . setIdentity ( doc , new ORecordId ( ) ) ; if ( iClusterName != null ) doc . save ( iClusterName ) ; else doc . save ( ) ; final ORID newIdentity = doc . getIdentity ( ) ; // CONVERT OUT EDGES
for ( Edge e : outEdges ) { final OrientEdge oe = ( OrientEdge ) e ; if ( oe . isLightweight ( ) ) { // REPLACE ALL REFS IN inVertex
final OrientVertex inV = oe . getVertex ( Direction . IN ) ; final String inFieldName = OrientVertex . getConnectionFieldName ( Direction . IN , oe . getLabel ( ) , graph . isUseVertexFieldsForEdgeLabels ( ) ) ; replaceLinks ( inV . getRecord ( ) , inFieldName , oldIdentity , newIdentity ) ; } else { // REPLACE WITH NEW VERTEX
oe . vOut = newIdentity ; oe . getRecord ( ) . field ( OrientBaseGraph . CONNECTION_OUT , newIdentity ) ; oe . save ( ) ; } } for ( Edge e : inEdges ) { final OrientEdge oe = ( OrientEdge ) e ; if ( oe . isLightweight ( ) ) { // REPLACE ALL REFS IN outVertex
final OrientVertex outV = oe . getVertex ( Direction . OUT ) ; final String outFieldName = OrientVertex . getConnectionFieldName ( Direction . OUT , oe . getLabel ( ) , graph . isUseVertexFieldsForEdgeLabels ( ) ) ; replaceLinks ( outV . getRecord ( ) , outFieldName , oldIdentity , newIdentity ) ; } else { // REPLACE WITH NEW VERTEX
oe . vIn = newIdentity ; oe . getRecord ( ) . field ( OrientBaseGraph . CONNECTION_IN , newIdentity ) ; oe . save ( ) ; } } // FINAL SAVE
doc . save ( ) ; return newIdentity ;


signature:
public class OrientVertex { /** * Creates an edge between current Vertex and a target Vertex setting label as Edge ' s label .
 * @ param label Edge ' s label or class
 * @ param inVertex Outgoing target vertex
 * @ return The new Edge created */
@ Override public Edge addEdge ( final String label , Vertex inVertex ) { } }

implementation:
if ( inVertex instanceof PartitionVertex ) // WRAPPED : GET THE BASE VERTEX
inVertex = ( ( PartitionVertex ) inVertex ) . getBaseVertex ( ) ; return addEdge ( label , ( OrientVertex ) inVertex , null , null , ( Object [ ] ) null ) ;


signature:
public class OrientVertex { /** * Creates an edge between current Vertex and a target Vertex setting label as Edge ' s label . iClassName is the Edge ' s class used
 * if different by label .
 * @ param label Edge ' s label or class
 * @ param inVertex Outgoing target vertex
 * @ param iClassName Edge ' s class name
 * @ return The new Edge created */
public OrientEdge addEdge ( final String label , final OrientVertex inVertex , final String iClassName ) { } }

implementation: return addEdge ( label , inVertex , iClassName , null , ( Object [ ] ) null ) ;


signature:
public class OrientVertex { /** * Creates an edge between current Vertex and a target Vertex setting label as Edge ' s label . The fields parameter is an Array of
 * fields to set on Edge upon creation . Fields must be a odd pairs of key / value or a single object as Map containing entries as
 * key / value pairs . iClusterName is the name of the cluster where to store the new Edge .
 * @ param label Edge ' s label or class
 * @ param inVertex Outgoing target vertex
 * @ param fields Fields must be a odd pairs of key / value or a single object as Map containing entries as key / value pairs
 * @ param iClassName Edge ' s class name
 * @ param iClusterName The cluster name where to store the edge record
 * @ return The new Edge created */
public OrientEdge addEdge ( String label , final OrientVertex inVertex , final String iClassName , final String iClusterName , final Object ... fields ) { } }

implementation:
if ( inVertex == null ) throw new IllegalArgumentException ( "destination vertex is null" ) ; final OrientBaseGraph graph = getGraph ( ) ; if ( graph != null ) return graph . addEdgeInternal ( this , label , inVertex , iClassName , iClusterName , fields ) ; // IN MEMORY CHANGES ONLY : USE NOTX CLASS
return OrientGraphNoTx . addEdgeInternal ( null , this , label , inVertex , iClassName , iClusterName , fields ) ;


signature:
public class OrientVertex { /** * ( Blueprints Extension ) Returns the number of edges connected to the current Vertex .
 * @ param iDirection The direction between OUT , IN or BOTH
 * @ param iLabels Optional labels as Strings to consider
 * @ return A long with the total edges found */
public long countEdges ( final Direction iDirection , final String ... iLabels ) { } }

implementation:
checkIfAttached ( ) ; long counter = 0 ; OrientBaseGraph . getEdgeClassNames ( getGraph ( ) , iLabels ) ; OrientBaseGraph . encodeClassNames ( iLabels ) ; if ( settings . isUseVertexFieldsForEdgeLabels ( ) || iLabels == null || iLabels . length == 0 ) { // VERY FAST
final ODocument doc = getRecord ( ) ; for ( String fieldName : doc . fieldNames ( ) ) { final OPair < Direction , String > connection = getConnection ( iDirection , fieldName , iLabels ) ; if ( connection == null ) // SKIP THIS FIELD
continue ; final Object fieldValue = doc . field ( fieldName ) ; if ( fieldValue != null ) if ( fieldValue instanceof Collection < ? > ) counter += ( ( Collection < ? > ) fieldValue ) . size ( ) ; else if ( fieldValue instanceof Map < ? , ? > ) counter += ( ( Map < ? , ? > ) fieldValue ) . size ( ) ; else if ( fieldValue instanceof ORidBag ) { counter += ( ( ORidBag ) fieldValue ) . size ( ) ; } else { counter ++ ; } } } else { // SLOWER : BROWSE & FILTER
for ( Edge e : getEdges ( iDirection , iLabels ) ) if ( e != null ) counter ++ ; } return counter ;


signature:
public class OrientVertex { /** * Returns the edges connected to the current Vertex . If you are interested on just counting the edges use @ countEdges that it ' s
 * more efficient for this use case .
 * @ param iDirection The direction between OUT , IN or BOTH
 * @ param iLabels Optional labels as Strings to consider
 * @ return */
@ Override public Iterable < Edge > getEdges ( final Direction iDirection , final String ... iLabels ) { } }

implementation: return getEdges ( null , iDirection , iLabels ) ;


signature:
public class OrientVertex { /** * ( Blueprints Extension ) Returns all the edges from the current Vertex to another one .
 * @ param iDestination The target vertex
 * @ param iDirection The direction between OUT , IN or BOTH
 * @ param iLabels Optional labels as Strings to consider
 * @ return */
public Iterable < Edge > getEdges ( final OrientVertex iDestination , final Direction iDirection , final String ... iLabels ) { } }

implementation:
setCurrentGraphInThreadLocal ( ) ; final ODocument doc = getRecord ( ) ; OrientBaseGraph . getEdgeClassNames ( getGraph ( ) , iLabels ) ; OrientBaseGraph . encodeClassNames ( iLabels ) ; final OMultiCollectionIterator < Edge > iterable = new OMultiCollectionIterator < Edge > ( ) . setEmbedded ( true ) ; for ( OTriple < String , Direction , String > connectionField : getConnectionFields ( iDirection , iLabels ) ) { String fieldName = connectionField . getKey ( ) ; OPair < Direction , String > connection = connectionField . getValue ( ) ; final Object fieldValue = doc . rawField ( fieldName ) ; if ( fieldValue != null ) { final OIdentifiable destinationVId = iDestination != null ? ( OIdentifiable ) iDestination . getId ( ) : null ; if ( fieldValue instanceof OIdentifiable ) { addSingleEdge ( doc , iterable , fieldName , connection , fieldValue , destinationVId , iLabels ) ; } else if ( fieldValue instanceof Collection < ? > ) { Collection < ? > coll = ( Collection < ? > ) fieldValue ; if ( coll . size ( ) == 1 ) { // SINGLE ITEM : AVOID CALLING ITERATOR
if ( coll instanceof ORecordLazyMultiValue ) addSingleEdge ( doc , iterable , fieldName , connection , ( ( ORecordLazyMultiValue ) coll ) . rawIterator ( ) . next ( ) , destinationVId , iLabels ) ; else if ( coll instanceof List < ? > ) addSingleEdge ( doc , iterable , fieldName , connection , ( ( List < ? > ) coll ) . get ( 0 ) , destinationVId , iLabels ) ; else addSingleEdge ( doc , iterable , fieldName , connection , coll . iterator ( ) . next ( ) , destinationVId , iLabels ) ; } else { // CREATE LAZY Iterable AGAINST COLLECTION FIELD
if ( coll instanceof ORecordLazyMultiValue ) { iterable . add ( new OrientEdgeIterator ( this , iDestination , coll , ( ( ORecordLazyMultiValue ) coll ) . rawIterator ( ) , connection , iLabels , coll . size ( ) ) ) ; } else iterable . add ( new OrientEdgeIterator ( this , iDestination , coll , coll . iterator ( ) , connection , iLabels , - 1 ) ) ; } } else if ( fieldValue instanceof ORidBag ) { iterable . add ( new OrientEdgeIterator ( this , iDestination , fieldValue , ( ( ORidBag ) fieldValue ) . rawIterator ( ) , connection , iLabels , ( ( ORidBag ) fieldValue ) . size ( ) ) ) ; } } } return iterable ;


signature:
public class OrientVertex { /** * ( Blueprints Extension ) Returns the Vertex ' s label . By default OrientDB binds the Blueprints Label concept to Vertex Class . To
 * disable this feature execute this at database level < code > alter database custom useClassForVertexLabel = false < / code > */
@ Override public String getLabel ( ) { } }

implementation:
setCurrentGraphInThreadLocal ( ) ; if ( settings . isUseClassForVertexLabel ( ) ) { final String clsName = getRecord ( ) . getClassName ( ) ; if ( ! OrientVertexType . CLASS_NAME . equals ( clsName ) ) // RETURN THE CLASS NAME
return clsName ; } return getRecord ( ) . field ( OrientElement . LABEL_FIELD_NAME ) ;


signature:
public class OrientVertex { /** * ( Blueprints Extension ) Returns the Vertex type as OrientVertexType object . */
@ Override public OrientVertexType getType ( ) { } }

implementation: final OrientBaseGraph graph = getGraph ( ) ; return new OrientVertexType ( graph , getRecord ( ) . getSchemaClass ( ) ) ;


signature:
public class OrientVertex { /** * Used to extract the class name from the vertex ' s field .
 * @ param iDirection Direction of connection
 * @ param iFieldName Full field name
 * @ return Class of the connection if any */
public String getConnectionClass ( final Direction iDirection , final String iFieldName ) { } }

implementation: if ( iDirection == Direction . OUT ) { if ( iFieldName . length ( ) > CONNECTION_OUT_PREFIX . length ( ) ) return iFieldName . substring ( CONNECTION_OUT_PREFIX . length ( ) ) ; } else if ( iDirection == Direction . IN ) { if ( iFieldName . length ( ) > CONNECTION_IN_PREFIX . length ( ) ) return iFieldName . substring ( CONNECTION_IN_PREFIX . length ( ) ) ; } return OrientEdgeType . CLASS_NAME ;


signature:
public class OrientVertex { /** * Determines if a field is a connections or not .
 * @ param iDirection Direction to check
 * @ param iFieldName Field name
 * @ param iClassNames Optional array of class names
 * @ return The found direction if any */
protected OPair < Direction , String > getConnection ( final Direction iDirection , final String iFieldName , String ... iClassNames ) { } }

implementation:
if ( iClassNames != null && iClassNames . length == 1 && iClassNames [ 0 ] . equalsIgnoreCase ( "E" ) ) // DEFAULT CLASS , TREAT IT AS NO CLASS / LABEL
iClassNames = null ; final OrientBaseGraph graph = getGraph ( ) ; if ( iDirection == Direction . OUT || iDirection == Direction . BOTH ) { if ( settings . isUseVertexFieldsForEdgeLabels ( ) ) { // FIELDS THAT STARTS WITH " out _ "
if ( iFieldName . startsWith ( CONNECTION_OUT_PREFIX ) ) { String connClass = getConnectionClass ( Direction . OUT , iFieldName ) ; if ( iClassNames == null || iClassNames . length == 0 ) return new OPair < Direction , String > ( Direction . OUT , connClass ) ; // CHECK AGAINST ALL THE CLASS NAMES
OrientEdgeType edgeType = graph . getEdgeType ( connClass ) ; if ( edgeType != null ) { for ( String clsName : iClassNames ) { if ( edgeType . isSubClassOf ( clsName ) ) return new OPair < Direction , String > ( Direction . OUT , connClass ) ; } } } } else if ( iFieldName . equals ( OrientBaseGraph . CONNECTION_OUT ) ) // CHECK FOR " out "
return new OPair < Direction , String > ( Direction . OUT , null ) ; } if ( iDirection == Direction . IN || iDirection == Direction . BOTH ) { if ( settings . isUseVertexFieldsForEdgeLabels ( ) ) { // FIELDS THAT STARTS WITH " in _ "
if ( iFieldName . startsWith ( CONNECTION_IN_PREFIX ) ) { String connClass = getConnectionClass ( Direction . IN , iFieldName ) ; if ( iClassNames == null || iClassNames . length == 0 ) return new OPair < Direction , String > ( Direction . IN , connClass ) ; // CHECK AGAINST ALL THE CLASS NAMES
OrientEdgeType edgeType = graph . getEdgeType ( connClass ) ; if ( edgeType != null ) { for ( String clsName : iClassNames ) { if ( edgeType . isSubClassOf ( clsName ) ) return new OPair < Direction , String > ( Direction . IN , connClass ) ; } } } } else if ( iFieldName . equals ( OrientBaseGraph . CONNECTION_IN ) ) // CHECK FOR " in "
return new OPair < Direction , String > ( Direction . IN , null ) ; } // NOT FOUND
return null ;


signature:
public class OrientVertex { /** * Returns all the possible fields names to look for .
 * @ param iDirection Direction to check
 * @ param iClassNames Optional array of class names
 * @ return The array of field names */
private List < OTriple < String , Direction , String > > getConnectionFields ( final Direction iDirection , String ... iClassNames ) { } }

implementation:
final ODocument doc = getRecord ( ) ; List < OTriple < String , Direction , String > > result = new ArrayList < > ( ) ; if ( settings . isUseVertexFieldsForEdgeLabels ( ) ) { if ( iClassNames == null || iClassNames . length == 0 || ( iClassNames . length == 1 && iClassNames [ 0 ] . equalsIgnoreCase ( "E" ) ) ) { for ( String fieldName : doc . fieldNames ( ) ) { final OPair < Direction , String > connection = getConnection ( iDirection , fieldName , iClassNames ) ; if ( connection != null ) result . add ( new OTriple < String , Direction , String > ( fieldName , connection . getKey ( ) , connection . getValue ( ) ) ) ; } } else { OSchema schema = getGraph ( ) . getRawGraph ( ) . getMetadata ( ) . getSchema ( ) ; Set < String > allClassNames = new HashSet < String > ( ) ; for ( String className : iClassNames ) { allClassNames . add ( className ) ; OClass clazz = schema . getClass ( className ) ; if ( clazz != null ) { Collection < OClass > subClasses = clazz . getAllSubclasses ( ) ; for ( OClass subClass : subClasses ) { allClassNames . add ( subClass . getName ( ) ) ; } } } for ( String className : allClassNames ) { switch ( iDirection ) { case OUT : result . add ( new OTriple < String , Direction , String > ( CONNECTION_OUT_PREFIX + className , Direction . OUT , className ) ) ; break ; case IN : result . add ( new OTriple < String , Direction , String > ( CONNECTION_IN_PREFIX + className , Direction . IN , className ) ) ; break ; case BOTH : result . add ( new OTriple < String , Direction , String > ( CONNECTION_OUT_PREFIX + className , Direction . OUT , className ) ) ; result . add ( new OTriple < String , Direction , String > ( CONNECTION_IN_PREFIX + className , Direction . IN , className ) ) ; break ; } } } } else { if ( iDirection == Direction . OUT ) result . add ( new OTriple < String , Direction , String > ( OrientBaseGraph . CONNECTION_OUT , Direction . OUT , null ) ) ; else if ( iDirection == Direction . IN ) result . add ( new OTriple < String , Direction , String > ( OrientBaseGraph . CONNECTION_IN , Direction . IN , null ) ) ; else { result . add ( new OTriple < String , Direction , String > ( OrientBaseGraph . CONNECTION_OUT , Direction . OUT , null ) ) ; result . add ( new OTriple < String , Direction , String > ( OrientBaseGraph . CONNECTION_IN , Direction . IN , null ) ) ; } } // EARLY FETCH ALL THE FIELDS THAT MATTERS
String [ ] fieldNames = new String [ result . size ( ) ] ; int i = 0 ; for ( OTriple < String , Direction , String > connectionField : result ) fieldNames [ i ++ ] = connectionField . getKey ( ) ; doc . deserializeFields ( fieldNames ) ; return result ;


signature:
public class ODatabaseImport { /** * just read collection so import process can continue */
private void processBrokenRids ( Set < ORID > brokenRids ) throws IOException , ParseException { } }

implementation: if ( exporterVersion >= 12 ) { listener . onMessage ( "Reading of set of RIDs of records which were detected as broken during database export\n" ) ; jsonReader . readNext ( OJSONReader . BEGIN_COLLECTION ) ; while ( true ) { jsonReader . readNext ( OJSONReader . NEXT_IN_ARRAY ) ; final ORecordId recordId = new ORecordId ( jsonReader . getValue ( ) ) ; brokenRids . add ( recordId ) ; if ( jsonReader . lastChar ( ) == ']' ) break ; } } if ( migrateLinks ) { if ( exporterVersion >= 12 ) listener . onMessage ( brokenRids . size ( ) + " were detected as broken during database export, links on those records will be removed from" + " result database" ) ; migrateLinksInImportedDocuments ( brokenRids ) ; }


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

implementation:
if ( clazz == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; ODatabaseDocumentInternal db = getDatabase ( ) ; final List < Object > edges = new ArrayList < Object > ( ) ; Set < OIdentifiable > fromIds = null ; Set < OIdentifiable > toIds = null ; db . begin ( ) ; try { fromIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , from , context , iArgs ) ; toIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , to , context , iArgs ) ; // CREATE EDGES
for ( OIdentifiable from : fromIds ) { final OVertex fromVertex = toVertex ( from ) ; if ( fromVertex == null ) throw new OCommandExecutionException ( "Source vertex '" + from + "' does not exist" ) ; for ( OIdentifiable to : toIds ) { final OVertex toVertex ; if ( from . equals ( to ) ) { toVertex = fromVertex ; } else { toVertex = toVertex ( to ) ; } if ( toVertex == null ) { throw new OCommandExecutionException ( "Source vertex '" + to + "' does not exist" ) ; } if ( fields != null ) // EVALUATE FIELDS
for ( final OPair < String , Object > f : fields ) { if ( f . getValue ( ) instanceof OSQLFunctionRuntime ) { f . setValue ( ( ( OSQLFunctionRuntime ) f . getValue ( ) ) . getValue ( to , null , context ) ) ; } else if ( f . getValue ( ) instanceof OSQLFilterItem ) { f . setValue ( ( ( OSQLFilterItem ) f . getValue ( ) ) . getValue ( to , null , context ) ) ; } } OEdge edge = null ; if ( content != null ) { if ( fields != null ) // MERGE CONTENT WITH FIELDS
fields . addAll ( OPair . convertFromMap ( content . toMap ( ) ) ) ; else fields = OPair . convertFromMap ( content . toMap ( ) ) ; } edge = fromVertex . addEdge ( toVertex , edgeLabel ) ; if ( fields != null && ! fields . isEmpty ( ) ) { OSQLHelper . bindParameters ( edge . getRecord ( ) , fields , new OCommandParameters ( iArgs ) , context ) ; } edge . save ( clusterName ) ; fromVertex . save ( ) ; toVertex . save ( ) ; edges . add ( edge ) ; if ( batch > 0 && edges . size ( ) % batch == 0 ) { db . commit ( ) ; db . begin ( ) ; } } } } finally { db . commit ( ) ; } if ( edges . isEmpty ( ) ) { if ( fromIds . isEmpty ( ) ) throw new OCommandExecutionException ( "No edge has been created because no source vertices" ) ; else if ( toIds . isEmpty ( ) ) throw new OCommandExecutionException ( "No edge has been created because no target vertices" ) ; throw new OCommandExecutionException ( "No edge has been created between " + fromIds + " and " + toIds ) ; } return edges ;


signature:
public class OConsoleApplication { /** * Returns a map of all console method and the object they can be called on .
 * @ return Map & lt ; Method , Object & gt ; */
protected Map < Method , Object > getConsoleMethods ( ) { } }

implementation:
if ( methods != null ) return methods ; // search for declared command collections
final Iterator < OConsoleCommandCollection > ite = ServiceLoader . load ( OConsoleCommandCollection . class ) . iterator ( ) ; final Collection < Object > candidates = new ArrayList < Object > ( ) ; candidates . add ( this ) ; while ( ite . hasNext ( ) ) { try { // make a copy and set it ' s context
final OConsoleCommandCollection cc = ite . next ( ) . getClass ( ) . newInstance ( ) ; cc . setContext ( this ) ; candidates . add ( cc ) ; } catch ( InstantiationException ex ) { Logger . getLogger ( OConsoleApplication . class . getName ( ) ) . log ( Level . WARNING , ex . getMessage ( ) ) ; } catch ( IllegalAccessException ex ) { Logger . getLogger ( OConsoleApplication . class . getName ( ) ) . log ( Level . WARNING , ex . getMessage ( ) ) ; } } methods = new TreeMap < Method , Object > ( new Comparator < Method > ( ) { public int compare ( Method o1 , Method o2 ) { final ConsoleCommand ann1 = o1 . getAnnotation ( ConsoleCommand . class ) ; final ConsoleCommand ann2 = o2 . getAnnotation ( ConsoleCommand . class ) ; if ( ann1 != null && ann2 != null ) { if ( ann1 . priority ( ) != ann2 . priority ( ) ) // PRIORITY WINS
return ann1 . priority ( ) - ann2 . priority ( ) ; } int res = o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; if ( res == 0 ) res = o1 . toString ( ) . compareTo ( o2 . toString ( ) ) ; return res ; } } ) ; for ( final Object candidate : candidates ) { final Method [ ] classMethods = candidate . getClass ( ) . getMethods ( ) ; for ( Method m : classMethods ) { if ( Modifier . isAbstract ( m . getModifiers ( ) ) || Modifier . isStatic ( m . getModifiers ( ) ) || ! Modifier . isPublic ( m . getModifiers ( ) ) ) { continue ; } if ( m . getReturnType ( ) != Void . TYPE ) { continue ; } methods . put ( m , candidate ) ; } } return methods ;


signature:
public class ODistributedAbstractPlugin { /** * Executes the request on local node . In case of error returns the Exception itself */
@ Override public Object executeOnLocalNode ( final ODistributedRequestId reqId , final ORemoteTask task , final ODatabaseDocumentInternal database ) { } }

implementation:
if ( database != null && ! ( database . getStorage ( ) instanceof ODistributedStorage ) ) throw new ODistributedException ( "Distributed storage was not installed for database '" + database . getName ( ) + "'. Implementation found: " + database . getStorage ( ) . getClass ( ) . getName ( ) ) ; final ODistributedAbstractPlugin manager = this ; return OScenarioThreadLocal . executeAsDistributed ( new Callable < Object > ( ) { @ Override public Object call ( ) throws Exception { try { final Object result = task . execute ( reqId , serverInstance , manager , database ) ; if ( result instanceof Throwable && ! ( result instanceof OException ) ) // EXCEPTION
ODistributedServerLog . debug ( this , nodeName , getNodeNameById ( reqId . getNodeId ( ) ) , DIRECTION . IN , "Error on executing request %d (%s) on local node: " , ( Throwable ) result , reqId , task ) ; else { // OK
final String sourceNodeName = task . getNodeSource ( ) ; if ( database != null ) { final ODistributedDatabaseImpl ddb = getMessageService ( ) . getDatabase ( database . getName ( ) ) ; if ( ddb != null && ! ( result instanceof Throwable ) && task instanceof OAbstractReplicatedTask && ! task . isIdempotent ( ) ) { // UPDATE LSN WITH LAST OPERATION
ddb . setLSN ( sourceNodeName , ( ( OAbstractReplicatedTask ) task ) . getLastLSN ( ) , true ) ; // UPDATE LSN WITH LAST LOCAL OPERATION
ddb . setLSN ( getLocalNodeName ( ) , ( ( OAbstractPaginatedStorage ) database . getStorage ( ) . getUnderlying ( ) ) . getLSN ( ) , true ) ; } } } return result ; } catch ( InterruptedException e ) { // IGNORE IT
ODistributedServerLog . debug ( this , nodeName , getNodeNameById ( reqId . getNodeId ( ) ) , DIRECTION . IN , "Interrupted execution on executing distributed request %s on local node: %s" , e , reqId , task ) ; return e ; } catch ( Exception e ) { if ( ! ( e instanceof OException ) ) ODistributedServerLog . error ( this , nodeName , getNodeNameById ( reqId . getNodeId ( ) ) , DIRECTION . IN , "Error on executing distributed request %s on local node: %s" , e , reqId , task ) ; return e ; } } } ) ;


signature:
public class ODistributedAbstractPlugin { /** * Returns the available nodes ( not offline ) and clears the node list by removing the offline nodes . */
@ Override public int getAvailableNodes ( final Collection < String > iNodes , final String databaseName ) { } }

implementation: for ( Iterator < String > it = iNodes . iterator ( ) ; it . hasNext ( ) ; ) { final String node = it . next ( ) ; if ( ! isNodeAvailable ( node , databaseName ) ) it . remove ( ) ; } return iNodes . size ( ) ;


signature:
public class ODistributedAbstractPlugin { /** * Returns the nodes with the requested status . */
@ Override public int getNodesWithStatus ( final Collection < String > iNodes , final String databaseName , final DB_STATUS ... statuses ) { } }

implementation: for ( Iterator < String > it = iNodes . iterator ( ) ; it . hasNext ( ) ; ) { final String node = it . next ( ) ; if ( ! isNodeStatusEqualsTo ( node , databaseName , statuses ) ) it . remove ( ) ; } return iNodes . size ( ) ;


signature:
public class ODistributedAbstractPlugin { /** * Installs a database from the network . */
protected void installDatabaseFromNetwork ( final String dbPath , final String databaseName , final ODistributedDatabaseImpl distrDatabase , final String iNode , final ODistributedDatabaseChunk firstChunk , final boolean delta , final File uniqueClustersBackupDirectory , final OModifiableDistributedConfiguration cfg ) { } }

implementation:
final String fileName = Orient . getTempPath ( ) + "install_" + databaseName + "_server" + getLocalNodeId ( ) + ".zip" ; final String localNodeName = nodeName ; ODistributedServerLog . info ( this , localNodeName , iNode , DIRECTION . IN , "Copying remote database '%s' to: %s" , databaseName , fileName ) ; final File file = new File ( fileName ) ; if ( file . exists ( ) ) file . delete ( ) ; try { file . getParentFile ( ) . mkdirs ( ) ; file . createNewFile ( ) ; } catch ( IOException e ) { throw OException . wrapException ( new ODistributedException ( "Error on creating temp database file to install locally" ) , e ) ; } // DELETE ANY PREVIOUS . COMPLETED FILE
final File completedFile = new File ( file . getAbsolutePath ( ) + ".completed" ) ; if ( completedFile . exists ( ) ) completedFile . delete ( ) ; final AtomicReference < ODistributedMomentum > momentum = new AtomicReference < ODistributedMomentum > ( ) ; OSyncReceiver receiver = new OSyncReceiver ( this , databaseName , firstChunk , momentum , fileName , iNode , dbPath , file ) ; try { Thread t = new Thread ( receiver ) ; t . setUncaughtExceptionHandler ( new OUncaughtExceptionHandler ( ) ) ; t . start ( ) ; } catch ( Exception e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , "Error on transferring database '%s' to '%s'" , e , databaseName , fileName ) ; throw OException . wrapException ( new ODistributedException ( "Error on transferring database" ) , e ) ; } final ODatabaseDocumentInternal db = installDatabaseOnLocalNode ( databaseName , dbPath , iNode , fileName , delta , uniqueClustersBackupDirectory , cfg , firstChunk . incremental , firstChunk . walSegment , firstChunk . walPosition , receiver ) ; if ( db == null ) return ; // OVERWRITE THE MOMENTUM FROM THE ORIGINAL SERVER AND ADD LAST LOCAL LSN
try { distrDatabase . getSyncConfiguration ( ) . load ( ) ; distrDatabase . getSyncConfiguration ( ) . setLastLSN ( localNodeName , ( ( OLocalPaginatedStorage ) db . getStorage ( ) . getUnderlying ( ) ) . getLSN ( ) , false ) ; } catch ( IOException e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , "Error on loading %s file for database '%s'" , e , DISTRIBUTED_SYNC_JSON_FILENAME , databaseName ) ; } try { distrDatabase . setOnline ( ) ; } finally { db . activateOnCurrentThread ( ) ; db . close ( ) ; } try { rebalanceClusterOwnership ( nodeName , db , cfg , false ) ; } catch ( Exception e ) { // HANDLE IT AS WARNING
ODistributedServerLog . warn ( this , nodeName , null , DIRECTION . NONE , "Error on re-balancing the cluster for database '%s'" , e , databaseName ) ; // NOT CRITICAL , CONTINUE
}