Input: It s possible that the extension is already present . In that case this method does nothing . [CODESPLIT] private void addMessagingActiveMQExtension ( OperationContext context , Map < PathAddress , ModelNode > migrationOperations , boolean describe ) { Resource root = context . readResourceFromRoot ( PathAddress . EMPTY_ADDRESS , false ) ; if ( root . getChildrenNames ( EXTENSION ) . contains ( MESSAGING_ACTIVEMQ_EXTENSION ) ) { // extension is already added, do nothing return ; } PathAddress extensionAddress = pathAddress ( EXTENSION , MESSAGING_ACTIVEMQ_EXTENSION ) ; OperationEntry addEntry = context . getRootResourceRegistration ( ) . getOperationEntry ( extensionAddress , ADD ) ; ModelNode addOperation = createAddOperation ( extensionAddress ) ; addOperation . get ( MODULE ) . set ( MESSAGING_ACTIVEMQ_MODULE ) ; if ( describe ) { migrationOperations . put ( extensionAddress , addOperation ) ; } else { context . addStep ( context . getResult ( ) . get ( extensionAddress . toString ( ) ) , addOperation , addEntry . getOperationHandler ( ) , MODEL ) ; } }


Input: Check if the name of the parameter is allowed for the given resourceType . [CODESPLIT] private boolean parameterIsAllowed ( String name , String resourceType ) { switch ( resourceType ) { case REMOTE_ACCEPTOR : case HTTP_ACCEPTOR : case REMOTE_CONNECTOR : case HTTP_CONNECTOR : // WFLY-5667 - for now remove only use-nio. Revisit this code when Artemis offers an API // to know which parameters are ignored. if ( "use-nio" . equals ( name ) ) { return false ; } else { return true ; } default : // accept any parameter for other resources. return true ; } }


Input: For generic acceptor and connectors migrate their factory - class attribute if they are using the default Netty ones . [CODESPLIT] private void migrateGenericTransport ( ModelNode addOperation ) { String factoryClass = addOperation . get ( FACTORY_CLASS . getName ( ) ) . asString ( ) ; final String newFactoryClass ; switch ( factoryClass ) { case HORNETQ_NETTY_ACCEPTOR_FACTORY : newFactoryClass = ARTEMIS_NETTY_ACCEPTOR_FACTORY ; break ; case HORNETQ_NETTY_CONNECTOR_FACTORY : newFactoryClass = ARTEMIS_NETTY_CONNECTOR_FACTORY ; break ; default : newFactoryClass = factoryClass ; } addOperation . get ( FACTORY_CLASS . getName ( ) ) . set ( newFactoryClass ) ; }


Input: Discard from a node and set it to a new node if the attribute is defined . Use the { [CODESPLIT] private void setAndDiscard ( ModelNode setNode , ModelNode discardNode , AttributeDefinition legacyAttributeDefinition , String newAttributeName ) { ModelNode attribute = discardNode . get ( legacyAttributeDefinition . getName ( ) ) ; if ( attribute . isDefined ( ) ) { setNode . get ( newAttributeName ) . set ( attribute ) ; discardNode . remove ( legacyAttributeDefinition . getName ( ) ) ; } }


Input: { [CODESPLIT] @ Override public void writeContent ( XMLExtendedStreamWriter writer , SubsystemMarshallingContext context ) throws XMLStreamException { context . startSubsystemElement ( Namespace . CURRENT . getUriString ( ) , false ) ; ModelNode eeSubSystem = context . getModelNode ( ) ; GlobalModulesDefinition . INSTANCE . marshallAsElement ( eeSubSystem , writer ) ; EeSubsystemRootResource . EAR_SUBDEPLOYMENTS_ISOLATED . marshallAsElement ( eeSubSystem , writer ) ; EeSubsystemRootResource . SPEC_DESCRIPTOR_PROPERTY_REPLACEMENT . marshallAsElement ( eeSubSystem , writer ) ; EeSubsystemRootResource . JBOSS_DESCRIPTOR_PROPERTY_REPLACEMENT . marshallAsElement ( eeSubSystem , writer ) ; EeSubsystemRootResource . ANNOTATION_PROPERTY_REPLACEMENT . marshallAsElement ( eeSubSystem , writer ) ; writeConcurrentElement ( writer , eeSubSystem ) ; writeDefaultBindingsElement ( writer , eeSubSystem ) ; writer . writeEndElement ( ) ; }


Input: Processes the passed { @link org . jboss . metadata . ejb . spec . SessionBeanMetaData } and creates appropriate { @link org . jboss . as . ejb3 . component . session . SessionBeanComponentDescription } out of it . The { @link org . jboss . as . ejb3 . component . session . SessionBeanComponentDescription } is then added to the { @link org . jboss . as . ee . component . EEModuleDescription module description } available in the deployment unit of the passed { @link DeploymentPhaseContext phaseContext } [CODESPLIT] @ Override protected void processBeanMetaData ( final SessionBeanMetaData sessionBean , final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; // get the module description final EEModuleDescription moduleDescription = deploymentUnit . getAttachment ( org . jboss . as . ee . component . Attachments . EE_MODULE_DESCRIPTION ) ; final String beanName = sessionBean . getName ( ) ; ComponentDescription bean = moduleDescription . getComponentByName ( beanName ) ; if ( appclient ) { if ( bean == null ) { for ( final ComponentDescription component : deploymentUnit . getAttachmentList ( Attachments . ADDITIONAL_RESOLVABLE_COMPONENTS ) ) { if ( component . getComponentName ( ) . equals ( beanName ) ) { bean = component ; break ; } } } } if ( ! ( bean instanceof SessionBeanComponentDescription ) ) { //TODO: this is a hack to deal with descriptor merging //if this is a GenericBeanMetadata it may actually represent an MDB return ; } SessionBeanComponentDescription sessionBeanDescription = ( SessionBeanComponentDescription ) bean ; sessionBeanDescription . setDeploymentDescriptorEnvironment ( new DeploymentDescriptorEnvironment ( "java:comp/env/" , sessionBean ) ) ; // mapped-name sessionBeanDescription . setMappedName ( sessionBean . getMappedName ( ) ) ; // local business interface views final BusinessLocalsMetaData businessLocals = sessionBean . getBusinessLocals ( ) ; if ( businessLocals != null && ! businessLocals . isEmpty ( ) ) { sessionBeanDescription . addLocalBusinessInterfaceViews ( businessLocals ) ; } final String local = sessionBean . getLocal ( ) ; if ( local != null ) { sessionBeanDescription . addEjbLocalObjectView ( local ) ; } final String remote = sessionBean . getRemote ( ) ; if ( remote != null ) { sessionBeanDescription . addEjbObjectView ( remote ) ; } // remote business interface views final BusinessRemotesMetaData businessRemotes = sessionBean . getBusinessRemotes ( ) ; if ( businessRemotes != null && ! businessRemotes . isEmpty ( ) ) { sessionBeanDescription . addRemoteBusinessInterfaceViews ( businessRemotes ) ; } // process EJB3.1 specific session bean description if ( sessionBean instanceof SessionBean31MetaData ) { this . processSessionBean31 ( ( SessionBean31MetaData ) sessionBean , sessionBeanDescription ) ; } }


Input: { [CODESPLIT] public void deploy ( final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { // deploy any persistence providers found in deployment PersistenceProviderHandler . deploy ( phaseContext , platform ) ; // start each PU service (except the PUs with property Configuration.JPA_CONTAINER_CLASS_TRANSFORMER = false) PersistenceUnitServiceHandler . deploy ( phaseContext , true , platform ) ; }


Input: Attempt to cancel the corresponding invocation . [CODESPLIT] public boolean cancel ( boolean setFlag ) { final AtomicInteger stateRef = this . stateRef ; int oldVal , newVal ; do { oldVal = stateRef . get ( ) ; if ( oldVal == ST_WAITING ) { newVal = ST_CANCELLED ; } else if ( oldVal == ST_CANCELLED ) { if ( ! setFlag ) { return true ; } newVal = ST_CANCELLED_FLAG_SET ; } else if ( oldVal == ST_CANCELLED_FLAG_SET ) { // do nothing return true ; } else if ( oldVal == ST_STARTED ) { if ( ! setFlag ) { return false ; } newVal = ST_STARTED_FLAG_SET ; } else { assert oldVal == ST_STARTED_FLAG_SET ; return false ; } } while ( ! stateRef . compareAndSet ( oldVal , newVal ) ) ; return newVal == ST_CANCELLED || newVal == ST_CANCELLED_FLAG_SET ; }


Input: Attempt to determine whether the invocation should proceed or whether it should be cancelled . This method should only be called once per flag instance . [CODESPLIT] public boolean runIfNotCancelled ( ) { final AtomicInteger stateRef = this . stateRef ; int oldVal ; do { oldVal = stateRef . get ( ) ; if ( oldVal == ST_CANCELLED || oldVal == ST_CANCELLED_FLAG_SET ) { return false ; } else if ( oldVal != ST_WAITING ) { throw Assert . unreachableCode ( ) ; } } while ( ! stateRef . compareAndSet ( oldVal , ST_STARTED ) ) ; return true ; }


Input: Change the type . It checks for compatibility between the change of type . [CODESPLIT] protected void setTypeInternal ( final OType iType ) { getDatabase ( ) . checkSecurity ( ORule . ResourceGeneric . SCHEMA , ORole . PERMISSION_UPDATE ) ; acquireSchemaWriteLock ( ) ; try { if ( iType == globalRef . getType ( ) ) // NO CHANGES return ; if ( ! iType . getCastable ( ) . contains ( globalRef . getType ( ) ) ) throw new IllegalArgumentException ( "Cannot change property type from " + globalRef . getType ( ) + " to " + iType ) ; this . globalRef = owner . owner . findOrCreateGlobalProperty ( this . globalRef . getName ( ) , iType ) ; } finally { releaseSchemaWriteLock ( ) ; } }


Input: DO NOT DELETE THIS METHOD IT IS USED IN ENTERPRISE STORAGE <p > Copies content of page into passed in byte array . [CODESPLIT] @ SuppressWarnings ( "unused" ) public static void getPageData ( final ByteBuffer buffer , final byte [ ] data , final int offset , final int length ) { buffer . position ( 0 ) ; buffer . get ( data , offset , length ) ; }


Input: DO NOT DELETE THIS METHOD IT IS USED IN ENTERPRISE STORAGE <p > Get value of LSN from the passed in offset in byte array . [CODESPLIT] @ SuppressWarnings ( "unused" ) public static OLogSequenceNumber getLogSequenceNumber ( final int offset , final byte [ ] data ) { final long segment = OLongSerializer . INSTANCE . deserializeNative ( data , offset + WAL_SEGMENT_OFFSET ) ; final long position = OLongSerializer . INSTANCE . deserializeNative ( data , offset + WAL_POSITION_OFFSET ) ; return new OLogSequenceNumber ( segment , position ) ; }


Input:
/ * Tries to clone any Java object by using 3 techniques : - instanceof ( most verbose but faster performance ) - reflection ( medium performance ) - serialization ( applies for any object type but has a performance overhead ) [CODESPLIT] @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public static Object cloneObject ( final Object objectToClone , final Object previousClone ) { // ***************************************************************************************************************************************
 // 1. Class by class cloning (only clones known types)
 // ***************************************************************************************************************************************
 // Clone any Map (shallow clone should be enough at this level)
 if ( objectToClone instanceof Map ) { Map recycledMap = ( Map ) previousClone ; if ( recycledMap == null ) recycledMap = new HashMap ( ) ; else recycledMap . clear ( ) ; recycledMap . putAll ( ( Map < ? , ? > ) objectToClone ) ; return recycledMap ; // Clone any collection (shallow clone should be enough at this level)
 } else if ( objectToClone instanceof Collection ) { Collection recycledCollection = ( Collection ) previousClone ; if ( recycledCollection == null ) recycledCollection = new ArrayList ( ) ; else recycledCollection . clear ( ) ; recycledCollection . addAll ( ( Collection < ? > ) objectToClone ) ; return recycledCollection ; // Clone String
 } else if ( objectToClone instanceof String ) { return objectToClone ; } else if ( objectToClone instanceof Number ) { return objectToClone ; // Clone Date
 } else if ( objectToClone instanceof Date ) { return ( Date ) ( ( Date ) objectToClone ) . clone ( ) ; } else { // ***************************************************************************************************************************************
 // 2. Polymorphic clone (by reflection, looks for a clone() method in hierarchy and invoke it)
 // ***************************************************************************************************************************************
 try { Object newClone ; for ( Class < ? > obj = objectToClone . getClass ( ) ; ! obj . equals ( Object . class ) ; obj = obj . getSuperclass ( ) ) { Method m [ ] = obj . getDeclaredMethods ( ) ; for ( int i = 0 ; i < m . length ; i ++ ) { if ( m [ i ] . getName ( ) . equals ( "clone" ) ) { m [ i ] . setAccessible ( true ) ; newClone = m [ i ] . invoke ( objectToClone ) ; System . out . println ( objectToClone . getClass ( ) + " cloned by Reflection. Performance can be improved by adding the class to the list of known types" ) ; return newClone ; } } } throw new Exception ( "Method clone not found" ) ; // ***************************************************************************************************************************************
 // 3. Polymorphic clone (Deep cloning by Serialization)
 // ***************************************************************************************************************************************
 } catch ( Exception e1 ) { try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream ( ) { public synchronized byte [ ] toByteArray ( ) { return buf ; } } ; final ObjectOutputStream out = new ObjectOutputStream ( bytes ) ; out . writeObject ( objectToClone ) ; out . close ( ) ; final ObjectInputStream in = new ObjectInputStream ( new ByteArrayInputStream ( bytes . toByteArray ( ) ) ) ; System . out . println ( objectToClone . getClass ( ) + " cloned by Serialization. Performance can be improved by adding the class to the list of known types" ) ; return in . readObject ( ) ; // ***************************************************************************************************************************************
 // 4. Impossible to clone
 // ***************************************************************************************************************************************
 } catch ( Exception e2 ) { OLogManager . instance ( ) . error ( null , "[GremlinHelper] error on cloning object %s, previous %s" , e2 , objectToClone , previousClone ) ; return null ; } } } }


Input: Input the JSON stream data into the graph . More control over how data is streamed is provided by this method . [CODESPLIT] public void inputGraph ( final String filename , int bufferSize , final Set < String > edgePropertyKeys , final Set < String > vertexPropertyKeys ) throws IOException { final File file = new File ( filename ) ; if ( ! file . exists ( ) ) throw new ODatabaseImportException ( "File '" + filename + "' not found" ) ; inputSize = file . length ( ) ; final FileInputStream fis = new FileInputStream ( filename ) ; try { inputGraph ( fis , bufferSize , edgePropertyKeys , vertexPropertyKeys ) ; } finally { fis . close ( ) ; } }


Input: Input the JSON stream data into the graph . More control over how data is streamed is provided by this method . [CODESPLIT] public void inputGraph ( final InputStream jsonInputStream , int bufferSize , final Set < String > edgePropertyKeys , final Set < String > vertexPropertyKeys ) throws IOException { final JsonParser jp = jsonFactory . createJsonParser ( jsonInputStream ) ; // if this is a transactional localGraph then we're buffering final BatchGraph batchGraph = BatchGraph . wrap ( graph , bufferSize ) ; final ElementFactory elementFactory = new GraphElementFactory ( batchGraph ) ; OGraphSONUtility graphson = new OGraphSONUtility ( GraphSONMode . NORMAL , elementFactory , vertexPropertyKeys , edgePropertyKeys ) ; long importedVertices = 0 ; long importedEdges = 0 ; while ( jp . nextToken ( ) != JsonToken . END_OBJECT ) { final String fieldname = jp . getCurrentName ( ) == null ? "" : jp . getCurrentName ( ) ; if ( fieldname . equals ( GraphSONTokens . MODE ) ) { jp . nextToken ( ) ; final GraphSONMode mode = GraphSONMode . valueOf ( jp . getText ( ) ) ; graphson = new OGraphSONUtility ( mode , elementFactory , vertexPropertyKeys , edgePropertyKeys ) ; } else if ( fieldname . equals ( GraphSONTokens . VERTICES ) ) { jp . nextToken ( ) ; while ( jp . nextToken ( ) != JsonToken . END_ARRAY ) { final JsonNode node = jp . readValueAsTree ( ) ; graphson . vertexFromJson ( node ) ; importedVertices ++ ; printStatus ( jp , importedVertices , importedEdges ) ; if ( importedVertices % 1000 == 0 ) ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getLocalCache ( ) . invalidate ( ) ; } } else if ( fieldname . equals ( GraphSONTokens . EDGES ) ) { jp . nextToken ( ) ; while ( jp . nextToken ( ) != JsonToken . END_ARRAY ) { final JsonNode node = jp . readValueAsTree ( ) ; final Vertex inV = batchGraph . getVertex ( OGraphSONUtility . getTypedValueFromJsonNode ( node . get ( GraphSONTokens . _IN_V ) ) ) ; final Vertex outV = batchGraph . getVertex ( OGraphSONUtility . getTypedValueFromJsonNode ( node . get ( GraphSONTokens . _OUT_V ) ) ) ; graphson . edgeFromJson ( node , outV , inV ) ; importedEdges ++ ; printStatus ( jp , importedVertices , importedEdges ) ; if ( importedEdges % 1000 == 0 ) ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getLocalCache ( ) . invalidate ( ) ; } } } jp . close ( ) ; batchGraph . commit ( ) ; }


Input: Creates an instance of { @link OIndexDefinition } for automatic index . [CODESPLIT] public static OIndexDefinition createIndexDefinition ( final OClass oClass , final List < String > fieldNames , final List < OType > types , List < OCollate > collates , String indexKind , String algorithm ) { checkTypes ( oClass , fieldNames , types ) ; if ( fieldNames . size ( ) == 1 ) return createSingleFieldIndexDefinition ( oClass , fieldNames . get ( 0 ) , types . get ( 0 ) , collates == null ? null : collates . get ( 0 ) , indexKind , algorithm ) ; else return createMultipleFieldIndexDefinition ( oClass , fieldNames , types , collates , indexKind , algorithm ) ; }


Input: Extract field name from <property > [ by key|value ] field format . [CODESPLIT] public static String extractFieldName ( final String fieldDefinition ) { String [ ] fieldNameParts = FILED_NAME_PATTERN . split ( fieldDefinition ) ; if ( fieldNameParts . length == 0 ) { throw new IllegalArgumentException ( "Illegal field name format, should be '<property> [by key|value]' but was '" + fieldDefinition + ' ' ) ; } if ( fieldNameParts . length == 3 && "by" . equalsIgnoreCase ( fieldNameParts [ 1 ] ) ) return fieldNameParts [ 0 ] ; if ( fieldNameParts . length == 1 ) return fieldDefinition ; StringBuilder result = new StringBuilder ( ) ; result . append ( fieldNameParts [ 0 ] ) ; for ( int i = 1 ; i < fieldNameParts . length ; i ++ ) { result . append ( " " ) ; result . append ( fieldNameParts [ i ] ) ; } return result . toString ( ) ; }


Input: tests if current expression is an indexed funciton AND that function can also be executed without using the index [CODESPLIT] public boolean canExecuteIndexedFunctionWithoutIndex ( OFromClause target , OCommandContext context , OBinaryCompareOperator operator , Object right ) { if ( this . identifier == null ) { return false ; } return identifier . canExecuteIndexedFunctionWithoutIndex ( target , context , operator , right ) ; }


Input: estimates how many items of this class will be returned applying this filter [CODESPLIT] public long estimate ( OClass oClass , long threshold , OCommandContext ctx ) { long count = oClass . count ( ) ; if ( count > 1 ) { count = count / 2 ; } if ( count < threshold ) { return count ; } long indexesCount = 0l ; List < OAndBlock > flattenedConditions = flatten ( ) ; Set < OIndex < ? > > indexes = oClass . getIndexes ( ) ; for ( OAndBlock condition : flattenedConditions ) { List < OBinaryCondition > indexedFunctConditions = condition . getIndexedFunctionConditions ( oClass , ( ODatabaseDocumentInternal ) ctx . getDatabase ( ) ) ; long conditionEstimation = Long . MAX_VALUE ; if ( indexedFunctConditions != null ) { for ( OBinaryCondition cond : indexedFunctConditions ) { OFromClause from = new OFromClause ( - 1 ) ; OFromItem item = new OFromItem ( - 1 ) ; from . item = item ; from . item . setIdentifier ( new OIdentifier ( oClass . getName ( ) ) ) ; long newCount = cond . estimateIndexed ( from , ctx ) ; if ( newCount < conditionEstimation ) { conditionEstimation = newCount ; } } } else { Map < String , Object > conditions = getEqualityOperations ( condition , ctx ) ; for ( OIndex index : indexes ) { if ( index . getType ( ) . equals ( OClass . INDEX_TYPE . FULLTEXT . name ( ) ) || index . getType ( ) . equals ( OClass . INDEX_TYPE . FULLTEXT_HASH_INDEX . name ( ) ) ) { continue ; } List < String > indexedFields = index . getDefinition ( ) . getFields ( ) ; int nMatchingKeys = 0 ; for ( String indexedField : indexedFields ) { if ( conditions . containsKey ( indexedField ) ) { nMatchingKeys ++ ; } else { break ; } } if ( nMatchingKeys > 0 ) { long newCount = estimateFromIndex ( index , conditions , nMatchingKeys ) ; if ( newCount < conditionEstimation ) { conditionEstimation = newCount ; } } } } if ( conditionEstimation > count ) { return count ; } indexesCount += conditionEstimation ; } return Math . min ( indexesCount , count ) ; }


Input: Recursive method used to find all classes in a given directory and subdirs . [CODESPLIT] private static List < Class < ? > > findClasses ( final File iDirectory , String iPackageName , ClassLoader iClassLoader ) throws ClassNotFoundException { final List < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; if ( ! iDirectory . exists ( ) ) return classes ; iPackageName += "." + iDirectory . getName ( ) ; String className ; final File [ ] files = iDirectory . listFiles ( ) ; if ( files != null ) for ( File file : files ) { if ( file . isDirectory ( ) ) { if ( file . getName ( ) . contains ( "." ) ) continue ; classes . addAll ( findClasses ( file , iPackageName , iClassLoader ) ) ; } else if ( file . getName ( ) . endsWith ( CLASS_EXTENSION ) ) { className = file . getName ( ) . substring ( 0 , file . getName ( ) . length ( ) - CLASS_EXTENSION . length ( ) ) ; classes . add ( Class . forName ( iPackageName + ' ' + className , true , iClassLoader ) ) ; } } return classes ; }


Input: Filters discovered classes to see if they implement a given interface . [CODESPLIT] public static List < Class < ? > > getClassessOfInterface ( String thePackage , Class < ? > theInterface , final ClassLoader iClassLoader ) { List < Class < ? > > classList = new ArrayList < Class < ? > > ( ) ; try { for ( Class < ? > discovered : getClassesFor ( thePackage , iClassLoader ) ) { if ( Arrays . asList ( discovered . getInterfaces ( ) ) . contains ( theInterface ) ) { classList . add ( discovered ) ; } } } catch ( ClassNotFoundException ex ) { OLogManager . instance ( ) . error ( null , "Error finding classes" , ex ) ; } return classList ; }


Input: Returns the declared generic types of a class . [CODESPLIT] public static Type [ ] getGenericTypes ( final Class < ? > iClass ) { final Type genericType = iClass . getGenericInterfaces ( ) [ 0 ] ; if ( genericType != null && genericType instanceof ParameterizedType ) { final ParameterizedType pt = ( ParameterizedType ) genericType ; if ( pt . getActualTypeArguments ( ) != null && pt . getActualTypeArguments ( ) . length > 1 ) return pt . getActualTypeArguments ( ) ; } return null ; }


Input: Returns the generic class of multi - value objects . [CODESPLIT] public static Class < ? > getGenericMultivalueType ( final Field p ) { if ( p . getType ( ) instanceof Class < ? > ) { final Type genericType = p . getGenericType ( ) ; if ( genericType != null && genericType instanceof ParameterizedType ) { final ParameterizedType pt = ( ParameterizedType ) genericType ; if ( pt . getActualTypeArguments ( ) != null && pt . getActualTypeArguments ( ) . length > 0 ) { if ( ( ( Class < ? > ) pt . getRawType ( ) ) . isAssignableFrom ( Map . class ) ) { if ( pt . getActualTypeArguments ( ) [ 1 ] instanceof Class < ? > ) { return ( Class < ? > ) pt . getActualTypeArguments ( ) [ 1 ] ; } else if ( pt . getActualTypeArguments ( ) [ 1 ] instanceof ParameterizedType ) return ( Class < ? > ) ( ( ParameterizedType ) pt . getActualTypeArguments ( ) [ 1 ] ) . getRawType ( ) ; } else if ( pt . getActualTypeArguments ( ) [ 0 ] instanceof Class < ? > ) { return ( Class < ? > ) pt . getActualTypeArguments ( ) [ 0 ] ; } else if ( pt . getActualTypeArguments ( ) [ 0 ] instanceof ParameterizedType ) return ( Class < ? > ) ( ( ParameterizedType ) pt . getActualTypeArguments ( ) [ 0 ] ) . getRawType ( ) ; } } else if ( p . getType ( ) . isArray ( ) ) return p . getType ( ) . getComponentType ( ) ; } return null ; }


Input: Checks if a class is a Java type : Map Collection arrays Number ( extensions and primitives ) String Boolean .. [CODESPLIT] public static boolean isJavaType ( Class < ? > clazz ) { if ( clazz . isPrimitive ( ) ) return true ; else if ( clazz . getName ( ) . startsWith ( "java.lang" ) ) return true ; else if ( clazz . getName ( ) . startsWith ( "java.util" ) ) return true ; else if ( clazz . isArray ( ) ) return true ; return false ; }


Input: Execute a method . [CODESPLIT] public Object execute ( final Object iThis , final OIdentifiable iCurrentRecord , final Object iCurrentResult , final OCommandContext iContext ) { if ( iThis == null ) return null ; if ( configuredParameters != null ) { // RESOLVE VALUES USING THE CURRENT RECORD for ( int i = 0 ; i < configuredParameters . length ; ++ i ) { runtimeParameters [ i ] = configuredParameters [ i ] ; if ( method . evaluateParameters ( ) ) { if ( configuredParameters [ i ] instanceof OSQLFilterItemField ) { runtimeParameters [ i ] = ( ( OSQLFilterItemField ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; if ( runtimeParameters [ i ] == null && iCurrentResult instanceof OIdentifiable ) // LOOK INTO THE CURRENT RESULT runtimeParameters [ i ] = ( ( OSQLFilterItemField ) configuredParameters [ i ] ) . getValue ( ( OIdentifiable ) iCurrentResult , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OSQLMethodRuntime ) runtimeParameters [ i ] = ( ( OSQLMethodRuntime ) configuredParameters [ i ] ) . execute ( iThis , iCurrentRecord , iCurrentResult , iContext ) ; else if ( configuredParameters [ i ] instanceof OSQLFunctionRuntime ) runtimeParameters [ i ] = ( ( OSQLFunctionRuntime ) configuredParameters [ i ] ) . execute ( iCurrentRecord , iCurrentRecord , iCurrentResult , iContext ) ; else if ( configuredParameters [ i ] instanceof OSQLFilterItemVariable ) { runtimeParameters [ i ] = ( ( OSQLFilterItemVariable ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; if ( runtimeParameters [ i ] == null && iCurrentResult instanceof OIdentifiable ) // LOOK INTO THE CURRENT RESULT runtimeParameters [ i ] = ( ( OSQLFilterItemVariable ) configuredParameters [ i ] ) . getValue ( ( OIdentifiable ) iCurrentResult , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OCommandSQL ) { try { runtimeParameters [ i ] = ( ( OCommandSQL ) configuredParameters [ i ] ) . setContext ( iContext ) . execute ( ) ; } catch ( OCommandExecutorNotFoundException ignore ) { // TRY WITH SIMPLE CONDITION final String text = ( ( OCommandSQL ) configuredParameters [ i ] ) . getText ( ) ; final OSQLPredicate pred = new OSQLPredicate ( text ) ; runtimeParameters [ i ] = pred . evaluate ( iCurrentRecord instanceof ORecord ? ( ORecord ) iCurrentRecord : null , ( ODocument ) iCurrentResult , iContext ) ; // REPLACE ORIGINAL PARAM configuredParameters [ i ] = pred ; } } else if ( configuredParameters [ i ] instanceof OSQLPredicate ) runtimeParameters [ i ] = ( ( OSQLPredicate ) configuredParameters [ i ] ) . evaluate ( iCurrentRecord . getRecord ( ) , ( iCurrentRecord instanceof ODocument ? ( ODocument ) iCurrentResult : null ) , iContext ) ; else if ( configuredParameters [ i ] instanceof String ) { if ( configuredParameters [ i ] . toString ( ) . startsWith ( "\"" ) || configuredParameters [ i ] . toString ( ) . startsWith ( "'" ) ) runtimeParameters [ i ] = OIOUtils . getStringContent ( configuredParameters [ i ] ) ; } } } if ( method . getMaxParams ( ) == - 1 || method . getMaxParams ( ) > 0 ) { if ( runtimeParameters . length < method . getMinParams ( ) || ( method . getMaxParams ( ) > - 1 && runtimeParameters . length > method . getMaxParams ( ) ) ) throw new OCommandExecutionException ( "Syntax error: function '" + method . getName ( ) + "' needs " + ( method . getMinParams ( ) == method . getMaxParams ( ) ? method . getMinParams ( ) : method . getMinParams ( ) + "-" + method . getMaxParams ( ) ) + " argument(s) while has been received " + runtimeParameters . length ) ; } } final Object functionResult = method . execute ( iThis , iCurrentRecord , iContext , iCurrentResult , runtimeParameters ) ; return transformValue ( iCurrentRecord , iContext , functionResult ) ; }


Input: This is executed on non - indexed fields . [CODESPLIT] @ Override public Object evaluateRecord ( final OIdentifiable iRecord , ODocument iCurrentResult , final OSQLFilterCondition iCondition , final Object iLeft , final Object iRight , OCommandContext iContext , final ODocumentSerializer serializer ) { if ( iLeft == null || iRight == null ) return false ; return iLeft . toString ( ) . indexOf ( iRight . toString ( ) ) > - 1 ; }


Input: Derives the type of a field in a document . [CODESPLIT] protected OType deriveFieldType ( ODocument iRecord , String fieldName , OType requestedFieldType ) { // Schema defined types can not be ignored if ( iRecord . getSchemaClass ( ) . existsProperty ( fieldName ) ) { return iRecord . getSchemaClass ( ) . getProperty ( fieldName ) . getType ( ) ; } // New type if ( requestedFieldType != null ) { return requestedFieldType ; } // Existing type (not fixed by the schema) return iRecord . fieldType ( fieldName ) ; }


Input: Execute the command . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( role == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not yet been parsed" ) ; role . revoke ( resource , privilege ) ; role . save ( ) ; return role ; }


Input: Pushes record to cache . Identifier of record used as access key [CODESPLIT] public void updateRecord ( final ORecord record ) { if ( record . getIdentity ( ) . getClusterId ( ) != excludedCluster && record . getIdentity ( ) . isValid ( ) && ! record . isDirty ( ) && ! ORecordVersionHelper . isTombstone ( record . getVersion ( ) ) ) { if ( underlying . get ( record . getIdentity ( ) ) != record ) underlying . put ( record ) ; } }


Input: Looks up for record in cache by it s identifier . Optionally look up in secondary cache and update primary with found record [CODESPLIT] public ORecord findRecord ( final ORID rid ) { ORecord record ; record = underlying . get ( rid ) ; if ( record != null ) Orient . instance ( ) . getProfiler ( ) . updateCounter ( CACHE_HIT , "Record found in Level1 Cache" , 1L , "db.*.cache.level1.cache.found" ) ; else Orient . instance ( ) . getProfiler ( ) . updateCounter ( CACHE_MISS , "Record not found in Level1 Cache" , 1L , "db.*.cache.level1.cache.notFound" ) ; return record ; }


Input: Execute the REMOVE INDEX . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( name == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; if ( name . equals ( "*" ) ) { long totalIndexed = 0 ; for ( OIndex < ? > idx : getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . getIndexes ( ) ) { getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( idx . getName ( ) ) ; totalIndexed ++ ; } return totalIndexed ; } else getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( name ) ; return 1 ; }


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


Input: { [CODESPLIT] @ Override public T deserializeFromByteBufferObject ( ByteBuffer buffer ) { final byte typeId = buffer . get ( ) ; init ( typeId ) ; return ( T ) binarySerializer . deserializeFromByteBufferObject ( buffer ) ; }


Input: { [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer ) { final byte serializerId = buffer . get ( ) ; init ( serializerId ) ; return OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE + binarySerializer . getObjectSizeInByteBuffer ( buffer ) ; }


Input: { [CODESPLIT] @ Override public T deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final byte typeId = walChanges . getByteValue ( buffer , offset ++ ) ; init ( typeId ) ; return ( T ) binarySerializer . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ; }


Input: { [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE + binarySerializer . getObjectSizeInByteBuffer ( buffer , walChanges , OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE + offset ) ; }


Input: Creates the database ( if it does not exist ) and initializes batch operations . Call this once before starting to create vertices and edges . [CODESPLIT] public void begin ( ) { walActive = OGlobalConfiguration . USE_WAL . getValueAsBoolean ( ) ; if ( walActive ) OGlobalConfiguration . USE_WAL . setValue ( false ) ; if ( averageEdgeNumberPerNode > 0 ) { OGlobalConfiguration . RID_BAG_EMBEDDED_DEFAULT_SIZE . setValue ( averageEdgeNumberPerNode ) ; OGlobalConfiguration . RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD . setValue ( bonsaiThreshold ) ; } db = new ODatabaseDocumentTx ( dbUrl ) ; if ( db . exists ( ) ) { db . open ( userName , password ) ; } else { db . create ( ) ; } if ( this . useLightWeigthEdges == null ) { final List < OStorageEntryConfiguration > custom = ( List < OStorageEntryConfiguration > ) db . get ( ODatabase . ATTRIBUTES . CUSTOM ) ; for ( OStorageEntryConfiguration c : custom ) { if ( c . name . equalsIgnoreCase ( "useLightweightEdges" ) ) { this . useLightWeigthEdges = Boolean . parseBoolean ( c . value ) ; break ; } } if ( this . useLightWeigthEdges == null ) { this . useLightWeigthEdges = true ; } } createBaseSchema ( ) ; out = estimatedEntries > 0 ? new HashMap < Long , List < Object > > ( estimatedEntries ) : new HashMap < Long , List < Object > > ( ) ; in = estimatedEntries > 0 ? new HashMap < Long , List < Object > > ( estimatedEntries ) : new HashMap < Long , List < Object > > ( ) ; OClass vClass = db . getMetadata ( ) . getSchema ( ) . getClass ( this . vertexClass ) ; int [ ] existingClusters = vClass . getClusterIds ( ) ; for ( int c = existingClusters . length ; c <= parallel ; c ++ ) { vClass . addCluster ( vClass . getName ( ) + "_" + c ) ; } clusterIds = vClass . getClusterIds ( ) ; lastClusterPositions = new long [ clusterIds . length ] ; nextVerticesToCreate = new long [ clusterIds . length ] ; for ( int i = 0 ; i < clusterIds . length ; i ++ ) { int clusterId = clusterIds [ i ] ; try { nextVerticesToCreate [ i ] = i ; //THERE IS NO PUBLIC API FOR RETRIEVE THE LAST CLUSTER POSITION lastClusterPositions [ i ] = ( ( ODatabaseDocumentInternal ) db ) . getStorage ( ) . getClusterById ( clusterId ) . getLastPosition ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }


Input: Creates a new edge between two vertices . If vertices do not exist they will be created [CODESPLIT] public void createEdge ( final Long from , final Long to , Map < String , Object > properties ) { if ( settingProperties ) { throw new IllegalStateException ( "Cannot create new edges when already set properties on vertices" ) ; } if ( from < 0 ) { throw new IllegalArgumentException ( " Invalid vertex id: " + from ) ; } if ( to < 0 ) { throw new IllegalArgumentException ( " Invalid vertex id: " + to ) ; } if ( useLightWeigthEdges && ( properties == null || properties . size ( ) == 0 ) ) { last = last < from ? from : last ; last = last < to ? to : last ; putInList ( from , out , to ) ; putInList ( to , in , from ) ; } else { ODocument edgeDoc = new ODocument ( edgeClass ) ; edgeDoc . fromMap ( properties ) ; edgeDoc . field ( "out" , new ORecordId ( getClusterId ( from ) , getClusterPosition ( from ) ) ) ; edgeDoc . field ( "in" , new ORecordId ( getClusterId ( to ) , getClusterPosition ( to ) ) ) ; db . save ( edgeDoc ) ; ORecordId rid = ( ORecordId ) edgeDoc . getIdentity ( ) ; putInList ( from , out , rid ) ; putInList ( to , in , rid ) ; } }


Input: based on the cluster / server map and the query target this method tries to find an optimal strategy to execute the query on the cluster . [CODESPLIT] private void calculateShardingStrategy ( QueryPlanningInfo info , OCommandContext ctx ) { ODatabaseDocumentInternal db = ( ODatabaseDocumentInternal ) ctx . getDatabase ( ) ; info . distributedFetchExecutionPlans = new LinkedHashMap <> ( ) ; Map < String , Set < String > > clusterMap = db . getActiveClusterMap ( ) ; Set < String > queryClusters = calculateTargetClusters ( info , ctx ) ; if ( queryClusters == null || queryClusters . size ( ) == 0 ) { //no target String localNode = db . getLocalNodeName ( ) ; info . serverToClusters = new LinkedHashMap <> ( ) ; info . serverToClusters . put ( localNode , clusterMap . get ( localNode ) ) ; info . distributedFetchExecutionPlans . put ( localNode , new OSelectExecutionPlan ( ctx ) ) ; return ; } //    Set<String> serversWithAllTheClusers = getServersThatHasAllClusters(clusterMap, queryClusters); //    if (serversWithAllTheClusers.isEmpty()) { // sharded query Map < String , Set < String > > minimalSetOfNodes = getMinimalSetOfNodesForShardedQuery ( db . getLocalNodeName ( ) , clusterMap , queryClusters ) ; if ( minimalSetOfNodes == null ) { throw new OCommandExecutionException ( "Cannot execute sharded query" ) ; } info . serverToClusters = minimalSetOfNodes ; for ( String node : info . serverToClusters . keySet ( ) ) { info . distributedFetchExecutionPlans . put ( node , new OSelectExecutionPlan ( ctx ) ) ; } //    } else { //      // all on a node //      String targetNode = serversWithAllTheClusers.contains(db.getLocalNodeName()) ? //          db.getLocalNodeName() : //          serversWithAllTheClusers.iterator().next(); //      info.serverToClusters = new HashMap<>(); //      info.serverToClusters.put(targetNode, queryClusters); //    } }


Input: given a cluster map and a set of clusters involved in a query tries to calculate the minimum number of nodes that will have to be involved in the query execution with clusters involved for each node . [CODESPLIT] private Map < String , Set < String > > getMinimalSetOfNodesForShardedQuery ( String localNode , Map < String , Set < String > > clusterMap , Set < String > queryClusters ) { //approximate algorithm, the problem is NP-complete Map < String , Set < String > > result = new LinkedHashMap <> ( ) ; Set < String > uncovered = new HashSet <> ( ) ; uncovered . addAll ( queryClusters ) ; uncovered = uncovered . stream ( ) . filter ( x -> x != null ) . map ( x -> x . toLowerCase ( Locale . ENGLISH ) ) . collect ( Collectors . toSet ( ) ) ; //try local node first Set < String > nextNodeClusters = new HashSet <> ( ) ; Set < String > clustersForNode = clusterMap . get ( localNode ) ; if ( clustersForNode != null ) { nextNodeClusters . addAll ( clustersForNode ) ; } nextNodeClusters . retainAll ( uncovered ) ; if ( nextNodeClusters . size ( ) > 0 ) { result . put ( localNode , nextNodeClusters ) ; uncovered . removeAll ( nextNodeClusters ) ; } while ( uncovered . size ( ) > 0 ) { String nextNode = findItemThatCoversMore ( uncovered , clusterMap ) ; nextNodeClusters = new HashSet <> ( ) ; nextNodeClusters . addAll ( clusterMap . get ( nextNode ) ) ; nextNodeClusters . retainAll ( uncovered ) ; if ( nextNodeClusters . size ( ) == 0 ) { throw new OCommandExecutionException ( "Cannot execute a sharded query: clusters [" + uncovered . stream ( ) . collect ( Collectors . joining ( ", " ) ) + "] are not present on any node" + "\n [" + clusterMap . entrySet ( ) . stream ( ) . map ( x -> "" + x . getKey ( ) + ":(" + x . getValue ( ) . stream ( ) . collect ( Collectors . joining ( "," ) ) + ")" ) . collect ( Collectors . joining ( ", " ) ) + "]" ) ; } result . put ( nextNode , nextNodeClusters ) ; uncovered . removeAll ( nextNodeClusters ) ; } return result ; }


Input: @param clusterMap the cluster map for current sharding configuration @param queryClusters the clusters that are target of the query [CODESPLIT] private Set < String > getServersThatHasAllClusters ( Map < String , Set < String > > clusterMap , Set < String > queryClusters ) { Set < String > remainingServers = clusterMap . keySet ( ) ; for ( String cluster : queryClusters ) { for ( Map . Entry < String , Set < String > > serverConfig : clusterMap . entrySet ( ) ) { if ( ! serverConfig . getValue ( ) . contains ( cluster ) ) { remainingServers . remove ( serverConfig . getKey ( ) ) ; } } } return remainingServers ; }


Input: tries to calculate which clusters will be impacted by this query [CODESPLIT] private Set < String > calculateTargetClusters ( QueryPlanningInfo info , OCommandContext ctx ) { if ( info . target == null ) { return Collections . EMPTY_SET ; } Set < String > result = new HashSet <> ( ) ; ODatabase db = ctx . getDatabase ( ) ; OFromItem item = info . target . getItem ( ) ; if ( item . getRids ( ) != null && item . getRids ( ) . size ( ) > 0 ) { if ( item . getRids ( ) . size ( ) == 1 ) { OInteger cluster = item . getRids ( ) . get ( 0 ) . getCluster ( ) ; if ( cluster . getValue ( ) . longValue ( ) > ORID . CLUSTER_MAX ) { throw new OCommandExecutionException ( "Invalid cluster Id:" + cluster + ". Max allowed value = " + ORID . CLUSTER_MAX ) ; } result . add ( db . getClusterNameById ( cluster . getValue ( ) . intValue ( ) ) ) ; } else { for ( ORid rid : item . getRids ( ) ) { OInteger cluster = rid . getCluster ( ) ; result . add ( db . getClusterNameById ( cluster . getValue ( ) . intValue ( ) ) ) ; } } return result ; } else if ( item . getInputParams ( ) != null && item . getInputParams ( ) . size ( ) > 0 ) { if ( ( ( ODatabaseInternal ) ctx . getDatabase ( ) ) . isSharded ( ) ) { throw new UnsupportedOperationException ( "Sharded query with input parameter as a target is not supported yet" ) ; } return null ; } else if ( item . getCluster ( ) != null ) { String name = item . getCluster ( ) . getClusterName ( ) ; if ( name == null ) { name = db . getClusterNameById ( item . getCluster ( ) . getClusterNumber ( ) ) ; } if ( name != null ) { result . add ( name ) ; return result ; } else { return null ; } } else if ( item . getClusterList ( ) != null ) { for ( OCluster cluster : item . getClusterList ( ) . toListOfClusters ( ) ) { String name = cluster . getClusterName ( ) ; if ( name == null ) { name = db . getClusterNameById ( cluster . getClusterNumber ( ) ) ; } if ( name != null ) { result . add ( name ) ; } } return result ; } else if ( item . getIndex ( ) != null ) { String indexName = item . getIndex ( ) . getIndexName ( ) ; OIndex < ? > idx = db . getMetadata ( ) . getIndexManager ( ) . getIndex ( indexName ) ; if ( idx == null ) { throw new OCommandExecutionException ( "Index " + indexName + " does not exist" ) ; } result . addAll ( idx . getClusters ( ) ) ; if ( result . isEmpty ( ) ) { return null ; } return result ; } else if ( item . getInputParam ( ) != null ) { if ( ( ( ODatabaseInternal ) ctx . getDatabase ( ) ) . isSharded ( ) ) { throw new UnsupportedOperationException ( "Sharded query with input parameter as a target is not supported yet" ) ; } return null ; } else if ( item . getIdentifier ( ) != null ) { String className = item . getIdentifier ( ) . getStringValue ( ) ; OClass clazz = getSchemaFromContext ( ctx ) . getClass ( className ) ; if ( clazz == null ) { clazz = getSchemaFromContext ( ctx ) . getView ( className ) ; } if ( clazz == null ) { return null ; } int [ ] clusterIds = clazz . getPolymorphicClusterIds ( ) ; for ( int clusterId : clusterIds ) { String clusterName = db . getClusterNameById ( clusterId ) ; if ( clusterName != null ) { result . add ( clusterName ) ; } } return result ; } return null ; }


Input: for backward compatibility translate distinct ( foo ) to DISTINCT foo . This method modifies the projection itself . [CODESPLIT] protected static OProjection translateDistinct ( OProjection projection ) { if ( projection != null && projection . getItems ( ) . size ( ) == 1 ) { if ( isDistinct ( projection . getItems ( ) . get ( 0 ) ) ) { projection = projection . copy ( ) ; OProjectionItem item = projection . getItems ( ) . get ( 0 ) ; OFunctionCall function = ( ( OBaseExpression ) item . getExpression ( ) . getMathExpression ( ) ) . getIdentifier ( ) . getLevelZero ( ) . getFunctionCall ( ) ; OExpression exp = function . getParams ( ) . get ( 0 ) ; OProjectionItem resultItem = new OProjectionItem ( - 1 ) ; resultItem . setAlias ( item . getAlias ( ) ) ; resultItem . setExpression ( exp . copy ( ) ) ; OProjection result = new OProjection ( - 1 ) ; result . setItems ( new ArrayList <> ( ) ) ; result . setDistinct ( true ) ; result . getItems ( ) . add ( resultItem ) ; return result ; } } return projection ; }


Input: checks if a projection is a distinct ( expr ) . In new executor the distinct () function is not supported so distinct ( expr ) is translated to DISTINCT expr [CODESPLIT] private static boolean isDistinct ( OProjectionItem item ) { if ( item . getExpression ( ) == null ) { return false ; } if ( item . getExpression ( ) . getMathExpression ( ) == null ) { return false ; } if ( ! ( item . getExpression ( ) . getMathExpression ( ) instanceof OBaseExpression ) ) { return false ; } OBaseExpression base = ( OBaseExpression ) item . getExpression ( ) . getMathExpression ( ) ; if ( base . getIdentifier ( ) == null ) { return false ; } if ( base . getModifier ( ) != null ) { return false ; } if ( base . getIdentifier ( ) . getLevelZero ( ) == null ) { return false ; } OFunctionCall function = base . getIdentifier ( ) . getLevelZero ( ) . getFunctionCall ( ) ; if ( function == null ) { return false ; } return function . getName ( ) . getStringValue ( ) . equalsIgnoreCase ( "distinct" ) ; }


Input: returns true if the query is minimal ie . no WHERE condition no SKIP / LIMIT no UNWIND no GROUP / ORDER BY no LET [CODESPLIT] private boolean isMinimalQuery ( QueryPlanningInfo info ) { return info . projectionAfterOrderBy == null && info . globalLetClause == null && info . perRecordLetClause == null && info . whereClause == null && info . flattenedWhereClause == null && info . groupBy == null && info . orderBy == null && info . unwind == null && info . skip == null ; }


Input: splits LET clauses in global ( executed once ) and local ( executed once per record ) [CODESPLIT] private static void splitLet ( QueryPlanningInfo info , OCommandContext ctx ) { if ( info . perRecordLetClause != null && info . perRecordLetClause . getItems ( ) != null ) { Iterator < OLetItem > iterator = info . perRecordLetClause . getItems ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { OLetItem item = iterator . next ( ) ; if ( item . getExpression ( ) != null && item . getExpression ( ) . isEarlyCalculated ( ctx ) ) { iterator . remove ( ) ; addGlobalLet ( info , item . getVarName ( ) , item . getExpression ( ) ) ; } else if ( item . getQuery ( ) != null && ! item . getQuery ( ) . refersToParent ( ) ) { iterator . remove ( ) ; addGlobalLet ( info , item . getVarName ( ) , item . getQuery ( ) ) ; } } } }


Input: re - writes a list of flat AND conditions moving left all the equality operations [CODESPLIT] private static List < OAndBlock > moveFlattededEqualitiesLeft ( List < OAndBlock > flattenedWhereClause ) { if ( flattenedWhereClause == null ) { return null ; } List < OAndBlock > result = new ArrayList <> ( ) ; for ( OAndBlock block : flattenedWhereClause ) { List < OBooleanExpression > equalityExpressions = new ArrayList <> ( ) ; List < OBooleanExpression > nonEqualityExpressions = new ArrayList <> ( ) ; OAndBlock newBlock = block . copy ( ) ; for ( OBooleanExpression exp : newBlock . getSubBlocks ( ) ) { if ( exp instanceof OBinaryCondition ) { if ( ( ( OBinaryCondition ) exp ) . getOperator ( ) instanceof OEqualsCompareOperator ) { equalityExpressions . add ( exp ) ; } else { nonEqualityExpressions . add ( exp ) ; } } else { nonEqualityExpressions . add ( exp ) ; } } OAndBlock newAnd = new OAndBlock ( - 1 ) ; newAnd . getSubBlocks ( ) . addAll ( equalityExpressions ) ; newAnd . getSubBlocks ( ) . addAll ( nonEqualityExpressions ) ; result . add ( newAnd ) ; } return result ; }


Input: creates additional projections for ORDER BY [CODESPLIT] private static void addOrderByProjections ( QueryPlanningInfo info ) { if ( info . orderApplied || info . expand || info . unwind != null || info . orderBy == null || info . orderBy . getItems ( ) . size ( ) == 0 || info . projection == null || info . projection . getItems ( ) == null || ( info . projection . getItems ( ) . size ( ) == 1 && info . projection . getItems ( ) . get ( 0 ) . isAll ( ) ) ) { return ; } OOrderBy newOrderBy = info . orderBy == null ? null : info . orderBy . copy ( ) ; List < OProjectionItem > additionalOrderByProjections = calculateAdditionalOrderByProjections ( info . projection . getAllAliases ( ) , newOrderBy ) ; if ( additionalOrderByProjections . size ( ) > 0 ) { info . orderBy = newOrderBy ; //the ORDER BY has changed } if ( additionalOrderByProjections . size ( ) > 0 ) { info . projectionAfterOrderBy = new OProjection ( - 1 ) ; info . projectionAfterOrderBy . setItems ( new ArrayList <> ( ) ) ; for ( String alias : info . projection . getAllAliases ( ) ) { info . projectionAfterOrderBy . getItems ( ) . add ( projectionFromAlias ( new OIdentifier ( alias ) ) ) ; } for ( OProjectionItem item : additionalOrderByProjections ) { if ( info . preAggregateProjection != null ) { info . preAggregateProjection . getItems ( ) . add ( item ) ; info . aggregateProjection . getItems ( ) . add ( projectionFromAlias ( item . getAlias ( ) ) ) ; info . projection . getItems ( ) . add ( projectionFromAlias ( item . getAlias ( ) ) ) ; } else { info . projection . getItems ( ) . add ( item ) ; } } } }


Input: given a list of aliases ( present in the existing projections ) calculates a list of additional projections to add to the existing projections to allow ORDER BY calculation . The sorting clause will be modified with new replaced aliases [CODESPLIT] private static List < OProjectionItem > calculateAdditionalOrderByProjections ( Set < String > allAliases , OOrderBy orderBy ) { List < OProjectionItem > result = new ArrayList <> ( ) ; int nextAliasCount = 0 ; if ( orderBy != null && orderBy . getItems ( ) != null || ! orderBy . getItems ( ) . isEmpty ( ) ) { for ( OOrderByItem item : orderBy . getItems ( ) ) { if ( ! allAliases . contains ( item . getAlias ( ) ) ) { OProjectionItem newProj = new OProjectionItem ( - 1 ) ; if ( item . getAlias ( ) != null ) { newProj . setExpression ( new OExpression ( new OIdentifier ( item . getAlias ( ) ) , item . getModifier ( ) ) ) ; } else if ( item . getRecordAttr ( ) != null ) { ORecordAttribute attr = new ORecordAttribute ( - 1 ) ; attr . setName ( item . getRecordAttr ( ) ) ; newProj . setExpression ( new OExpression ( attr , item . getModifier ( ) ) ) ; } else if ( item . getRid ( ) != null ) { OExpression exp = new OExpression ( - 1 ) ; exp . setRid ( item . getRid ( ) . copy ( ) ) ; newProj . setExpression ( exp ) ; } OIdentifier newAlias = new OIdentifier ( "_$$$ORDER_BY_ALIAS$$$_" + ( nextAliasCount ++ ) ) ; newProj . setAlias ( newAlias ) ; item . setAlias ( newAlias . getStringValue ( ) ) ; item . setModifier ( null ) ; result . add ( newProj ) ; } } } return result ; }


Input: splits projections in three parts ( pre - aggregate aggregate and final ) to efficiently manage aggregations [CODESPLIT] private static void splitProjectionsForGroupBy ( QueryPlanningInfo info , OCommandContext ctx ) { if ( info . projection == null ) { return ; } OProjection preAggregate = new OProjection ( - 1 ) ; preAggregate . setItems ( new ArrayList <> ( ) ) ; OProjection aggregate = new OProjection ( - 1 ) ; aggregate . setItems ( new ArrayList <> ( ) ) ; OProjection postAggregate = new OProjection ( - 1 ) ; postAggregate . setItems ( new ArrayList <> ( ) ) ; boolean isSplitted = false ; //split for aggregate projections AggregateProjectionSplit result = new AggregateProjectionSplit ( ) ; for ( OProjectionItem item : info . projection . getItems ( ) ) { result . reset ( ) ; if ( isAggregate ( item ) ) { isSplitted = true ; OProjectionItem post = item . splitForAggregation ( result , ctx ) ; OIdentifier postAlias = item . getProjectionAlias ( ) ; postAlias = new OIdentifier ( postAlias , true ) ; post . setAlias ( postAlias ) ; postAggregate . getItems ( ) . add ( post ) ; aggregate . getItems ( ) . addAll ( result . getAggregate ( ) ) ; preAggregate . getItems ( ) . addAll ( result . getPreAggregate ( ) ) ; } else { preAggregate . getItems ( ) . add ( item ) ; //also push the alias forward in the chain OProjectionItem aggItem = new OProjectionItem ( - 1 ) ; aggItem . setExpression ( new OExpression ( item . getProjectionAlias ( ) ) ) ; aggregate . getItems ( ) . add ( aggItem ) ; postAggregate . getItems ( ) . add ( aggItem ) ; } } //bind split projections to the execution planner if ( isSplitted ) { info . preAggregateProjection = preAggregate ; if ( info . preAggregateProjection . getItems ( ) == null || info . preAggregateProjection . getItems ( ) . size ( ) == 0 ) { info . preAggregateProjection = null ; } info . aggregateProjection = aggregate ; if ( info . aggregateProjection . getItems ( ) == null || info . aggregateProjection . getItems ( ) . size ( ) == 0 ) { info . aggregateProjection = null ; } info . projection = postAggregate ; addGroupByExpressionsToProjections ( info ) ; } }


Input: if GROUP BY is performed on an expression that is not explicitly in the pre - aggregate projections then that expression has to be put in the pre - aggregate ( only here in subsequent steps it s removed ) [CODESPLIT] private static void addGroupByExpressionsToProjections ( QueryPlanningInfo info ) { if ( info . groupBy == null || info . groupBy . getItems ( ) == null || info . groupBy . getItems ( ) . size ( ) == 0 ) { return ; } OGroupBy newGroupBy = new OGroupBy ( - 1 ) ; int i = 0 ; for ( OExpression exp : info . groupBy . getItems ( ) ) { if ( exp . isAggregate ( ) ) { throw new OCommandExecutionException ( "Cannot group by an aggregate function" ) ; } boolean found = false ; if ( info . preAggregateProjection != null ) { for ( String alias : info . preAggregateProjection . getAllAliases ( ) ) { //if it's a simple identifier and it's the same as one of the projections in the query, //then the projection itself is used for GROUP BY without recalculating; in all the other cases, it is evaluated separately if ( alias . equals ( exp . getDefaultAlias ( ) . getStringValue ( ) ) && exp . isBaseIdentifier ( ) ) { found = true ; newGroupBy . getItems ( ) . add ( exp ) ; break ; } } } if ( ! found ) { OProjectionItem newItem = new OProjectionItem ( - 1 ) ; newItem . setExpression ( exp ) ; OIdentifier groupByAlias = new OIdentifier ( "_$$$GROUP_BY_ALIAS$$$_" + ( i ++ ) ) ; newItem . setAlias ( groupByAlias ) ; if ( info . preAggregateProjection == null ) { info . preAggregateProjection = new OProjection ( - 1 ) ; } if ( info . preAggregateProjection . getItems ( ) == null ) { info . preAggregateProjection . setItems ( new ArrayList <> ( ) ) ; } info . preAggregateProjection . getItems ( ) . add ( newItem ) ; newGroupBy . getItems ( ) . add ( new OExpression ( groupByAlias ) ) ; } info . groupBy = newGroupBy ; } }


Input: translates subqueries to LET statements [CODESPLIT] private static void extractSubQueries ( QueryPlanningInfo info ) { SubQueryCollector collector = new SubQueryCollector ( ) ; if ( info . perRecordLetClause != null ) { info . perRecordLetClause . extractSubQueries ( collector ) ; } int i = 0 ; int j = 0 ; for ( Map . Entry < OIdentifier , OStatement > entry : collector . getSubQueries ( ) . entrySet ( ) ) { OIdentifier alias = entry . getKey ( ) ; OStatement query = entry . getValue ( ) ; if ( query . refersToParent ( ) ) { addRecordLevelLet ( info , alias , query , j ++ ) ; } else { addGlobalLet ( info , alias , query , i ++ ) ; } } collector . reset ( ) ; if ( info . whereClause != null ) { info . whereClause . extractSubQueries ( collector ) ; } if ( info . projection != null ) { info . projection . extractSubQueries ( collector ) ; } if ( info . orderBy != null ) { info . orderBy . extractSubQueries ( collector ) ; } if ( info . groupBy != null ) { info . groupBy . extractSubQueries ( collector ) ; } for ( Map . Entry < OIdentifier , OStatement > entry : collector . getSubQueries ( ) . entrySet ( ) ) { OIdentifier alias = entry . getKey ( ) ; OStatement query = entry . getValue ( ) ; if ( query . refersToParent ( ) ) { addRecordLevelLet ( info , alias , query ) ; } else { addGlobalLet ( info , alias , query ) ; } } }


Input: checks if this RID is from one of these clusters [CODESPLIT] private boolean isFromClusters ( ORid rid , Set < String > filterClusters , ODatabase database ) { if ( filterClusters == null ) { throw new IllegalArgumentException ( ) ; } String clusterName = database . getClusterNameById ( rid . getCluster ( ) . getValue ( ) . intValue ( ) ) ; return filterClusters . contains ( clusterName ) ; }


Input: tries to use an index for sorting only . Also adds the fetch step to the execution plan [CODESPLIT] private boolean handleClassWithIndexForSortOnly ( OSelectExecutionPlan plan , OIdentifier queryTarget , Set < String > filterClusters , QueryPlanningInfo info , OCommandContext ctx , boolean profilingEnabled ) { OSchema schema = getSchemaFromContext ( ctx ) ; OClass clazz = schema . getClass ( queryTarget . getStringValue ( ) ) ; if ( clazz == null ) { clazz = schema . getView ( queryTarget . getStringValue ( ) ) ; if ( clazz == null ) { throw new OCommandExecutionException ( "Class not found: " + queryTarget ) ; } } for ( OIndex idx : clazz . getIndexes ( ) . stream ( ) . filter ( i -> i . supportsOrderedIterations ( ) ) . filter ( i -> i . getDefinition ( ) != null ) . collect ( Collectors . toList ( ) ) ) { List < String > indexFields = idx . getDefinition ( ) . getFields ( ) ; if ( indexFields . size ( ) < info . orderBy . getItems ( ) . size ( ) ) { continue ; } boolean indexFound = true ; String orderType = null ; for ( int i = 0 ; i < info . orderBy . getItems ( ) . size ( ) ; i ++ ) { OOrderByItem orderItem = info . orderBy . getItems ( ) . get ( i ) ; if ( orderItem . getCollate ( ) != null ) { return false ; } String indexField = indexFields . get ( i ) ; if ( i == 0 ) { orderType = orderItem . getType ( ) ; } else { if ( orderType == null || ! orderType . equals ( orderItem . getType ( ) ) ) { indexFound = false ; break ; //ASC/DESC interleaved, cannot be used with index. } } if ( ! ( indexField . equals ( orderItem . getAlias ( ) ) || isInOriginalProjection ( indexField , orderItem . getAlias ( ) ) ) ) { indexFound = false ; break ; } } if ( indexFound && orderType != null ) { plan . chain ( new FetchFromIndexValuesStep ( idx , orderType . equals ( OOrderByItem . ASC ) , ctx , profilingEnabled ) ) ; int [ ] filterClusterIds = null ; if ( filterClusters != null ) { filterClusterIds = filterClusters . stream ( ) . map ( name -> ctx . getDatabase ( ) . getClusterIdByName ( name ) ) . mapToInt ( i -> i ) . toArray ( ) ; } plan . chain ( new GetValueFromIndexEntryStep ( ctx , filterClusterIds , profilingEnabled ) ) ; if ( info . serverToClusters . size ( ) == 1 ) { info . orderApplied = true ; } return true ; } } return false ; }


Input: checks if a class is the top of a diamond hierarchy [CODESPLIT] private boolean isDiamondHierarchy ( OClass clazz ) { Set < OClass > traversed = new HashSet <> ( ) ; List < OClass > stack = new ArrayList <> ( ) ; stack . add ( clazz ) ; while ( ! stack . isEmpty ( ) ) { OClass current = stack . remove ( 0 ) ; traversed . add ( current ) ; for ( OClass sub : current . getSubclasses ( ) ) { if ( traversed . contains ( sub ) ) { return true ; } stack . add ( sub ) ; traversed . add ( sub ) ; } } return false ; }


Input: returns TRUE if all the order clauses are ASC FALSE if all are DESC null otherwise [CODESPLIT] private Boolean getOrderDirection ( QueryPlanningInfo info ) { if ( info . orderBy == null ) { return null ; } String result = null ; for ( OOrderByItem item : info . orderBy . getItems ( ) ) { if ( result == null ) { result = item . getType ( ) == null ? OOrderByItem . ASC : item . getType ( ) ; } else { String newType = item . getType ( ) == null ? OOrderByItem . ASC : item . getType ( ) ; if ( ! newType . equals ( result ) ) { return null ; } } } return result == null || result . equals ( OOrderByItem . ASC ) ; }


Input: checks whether the condition has CONTAINSANY or similar expressions that require multiple index evaluations [CODESPLIT] private boolean requiresMultipleIndexLookups ( OAndBlock keyCondition ) { for ( OBooleanExpression oBooleanExpression : keyCondition . getSubBlocks ( ) ) { if ( ! ( oBooleanExpression instanceof OBinaryCondition ) ) { return true ; } } return false ; }


Input: given a flat AND block and a set of indexes returns the best index to be used to process it with the complete description on how to use it [CODESPLIT] private IndexSearchDescriptor findBestIndexFor ( OCommandContext ctx , Set < OIndex < ? > > indexes , OAndBlock block , OClass clazz ) { //get all valid index descriptors List < IndexSearchDescriptor > descriptors = indexes . stream ( ) . filter ( x -> x . getInternal ( ) . canBeUsedInEqualityOperators ( ) ) . map ( index -> buildIndexSearchDescriptor ( ctx , index , block , clazz ) ) . filter ( Objects :: nonNull ) . filter ( x -> x . keyCondition != null ) . filter ( x -> x . keyCondition . getSubBlocks ( ) . size ( ) > 0 ) . collect ( Collectors . toList ( ) ) ; List < IndexSearchDescriptor > fullTextIndexDescriptors = indexes . stream ( ) . filter ( idx -> idx . getType ( ) . equalsIgnoreCase ( "FULLTEXT" ) ) . filter ( idx -> ! idx . getAlgorithm ( ) . equalsIgnoreCase ( "LUCENE" ) ) . map ( idx -> buildIndexSearchDescriptorForFulltext ( ctx , idx , block , clazz ) ) . filter ( Objects :: nonNull ) . filter ( x -> x . keyCondition != null ) . filter ( x -> x . keyCondition . getSubBlocks ( ) . size ( ) > 0 ) . collect ( Collectors . toList ( ) ) ; descriptors . addAll ( fullTextIndexDescriptors ) ; //remove the redundant descriptors (eg. if I have one on [a] and one on [a, b], the first one is redundant, just discard it) descriptors = removePrefixIndexes ( descriptors ) ; //sort by cost List < OPair < Integer , IndexSearchDescriptor > > sortedDescriptors = descriptors . stream ( ) . map ( x -> ( OPair < Integer , IndexSearchDescriptor > ) new OPair ( x . cost ( ctx ) , x ) ) . sorted ( ) . collect ( Collectors . toList ( ) ) ; //get only the descriptors with the lowest cost descriptors = sortedDescriptors . isEmpty ( ) ? Collections . emptyList ( ) : sortedDescriptors . stream ( ) . filter ( x -> x . key . equals ( sortedDescriptors . get ( 0 ) . key ) ) . map ( x -> x . value ) . collect ( Collectors . toList ( ) ) ; //sort remaining by the number of indexed fields descriptors = descriptors . stream ( ) . sorted ( Comparator . comparingInt ( x -> x . keyCondition . getSubBlocks ( ) . size ( ) ) ) . collect ( Collectors . toList ( ) ) ; //get the one that has more indexed fields return descriptors . isEmpty ( ) ? null : descriptors . get ( descriptors . size ( ) - 1 ) ; }


Input: finds prefix conditions for a given condition eg . if the condition is on [ a b ] and in the list there is another condition on [ a ] or on [ a b ] then that condition is returned . [CODESPLIT] private List < IndexSearchDescriptor > findPrefixes ( IndexSearchDescriptor desc , List < IndexSearchDescriptor > descriptors ) { List < IndexSearchDescriptor > result = new ArrayList <> ( ) ; for ( IndexSearchDescriptor item : descriptors ) { if ( isPrefixOf ( item , desc ) ) { result . add ( item ) ; } } return result ; }


Input: returns true if the first argument is a prefix for the second argument eg . if the first argument is [ a ] and the second argument is [ a b ] [CODESPLIT] private boolean isPrefixOf ( IndexSearchDescriptor item , IndexSearchDescriptor desc ) { List < OBooleanExpression > left = item . keyCondition . getSubBlocks ( ) ; List < OBooleanExpression > right = desc . keyCondition . getSubBlocks ( ) ; if ( left . size ( ) > right . size ( ) ) { return false ; } for ( int i = 0 ; i < left . size ( ) ; i ++ ) { if ( ! left . get ( i ) . equals ( right . get ( i ) ) ) { return false ; } } return true ; }


Input: given an index and a flat AND block returns a descriptor on how to process it with an index ( index index key and additional filters to apply after index fetch [CODESPLIT] private IndexSearchDescriptor buildIndexSearchDescriptor ( OCommandContext ctx , OIndex < ? > index , OAndBlock block , OClass clazz ) { List < String > indexFields = index . getDefinition ( ) . getFields ( ) ; OBinaryCondition keyCondition = new OBinaryCondition ( - 1 ) ; OIdentifier key = new OIdentifier ( "key" ) ; keyCondition . setLeft ( new OExpression ( key ) ) ; boolean allowsRange = allowsRangeQueries ( index ) ; boolean found = false ; OAndBlock blockCopy = block . copy ( ) ; Iterator < OBooleanExpression > blockIterator ; OAndBlock indexKeyValue = new OAndBlock ( - 1 ) ; IndexSearchDescriptor result = new IndexSearchDescriptor ( ) ; result . idx = index ; result . keyCondition = indexKeyValue ; for ( String indexField : indexFields ) { blockIterator = blockCopy . getSubBlocks ( ) . iterator ( ) ; boolean breakHere = false ; boolean indexFieldFound = false ; while ( blockIterator . hasNext ( ) ) { OBooleanExpression singleExp = blockIterator . next ( ) ; if ( singleExp instanceof OBinaryCondition ) { OExpression left = ( ( OBinaryCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { OBinaryCompareOperator operator = ( ( OBinaryCondition ) singleExp ) . getOperator ( ) ; if ( ! ( ( OBinaryCondition ) singleExp ) . getRight ( ) . isEarlyCalculated ( ctx ) ) { continue ; //this cannot be used because the value depends on single record } if ( operator instanceof OEqualsCompareOperator ) { found = true ; indexFieldFound = true ; OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( operator ) ; condition . setRight ( ( ( OBinaryCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } else if ( operator instanceof OContainsKeyOperator && isMap ( clazz , indexField ) && isIndexByKey ( index , indexField ) ) { found = true ; indexFieldFound = true ; OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( operator ) ; condition . setRight ( ( ( OBinaryCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } else if ( allowsRange && operator . isRangeOperator ( ) ) { found = true ; indexFieldFound = true ; breakHere = true ; //this is last element, no other fields can be added to the key because this is a range condition OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( operator ) ; condition . setRight ( ( ( OBinaryCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; //look for the opposite condition, on the same field, for range queries (the other side of the range) while ( blockIterator . hasNext ( ) ) { OBooleanExpression next = blockIterator . next ( ) ; if ( createsRangeWith ( ( OBinaryCondition ) singleExp , next ) ) { result . additionalRangeCondition = ( OBinaryCondition ) next ; blockIterator . remove ( ) ; break ; } } break ; } } } } else if ( singleExp instanceof OContainsValueCondition && ( ( OContainsValueCondition ) singleExp ) . getExpression ( ) != null && isMap ( clazz , indexField ) && isIndexByValue ( index , indexField ) ) { OExpression left = ( ( OContainsValueCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { found = true ; indexFieldFound = true ; OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( new OContainsValueOperator ( - 1 ) ) ; condition . setRight ( ( ( OContainsValueCondition ) singleExp ) . getExpression ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } else if ( singleExp instanceof OContainsAnyCondition ) { OExpression left = ( ( OContainsAnyCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { if ( ! ( ( OContainsAnyCondition ) singleExp ) . getRight ( ) . isEarlyCalculated ( ctx ) ) { continue ; //this cannot be used because the value depends on single record } found = true ; indexFieldFound = true ; OContainsAnyCondition condition = new OContainsAnyCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRight ( ( ( OContainsAnyCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } else if ( singleExp instanceof OInCondition ) { OExpression left = ( ( OInCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { if ( ( ( OInCondition ) singleExp ) . getRightMathExpression ( ) != null ) { if ( ! ( ( OInCondition ) singleExp ) . getRightMathExpression ( ) . isEarlyCalculated ( ctx ) ) { continue ; //this cannot be used because the value depends on single record } found = true ; indexFieldFound = true ; OInCondition condition = new OInCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRightMathExpression ( ( ( OInCondition ) singleExp ) . getRightMathExpression ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } else if ( ( ( OInCondition ) singleExp ) . getRightParam ( ) != null ) { found = true ; indexFieldFound = true ; OInCondition condition = new OInCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRightParam ( ( ( OInCondition ) singleExp ) . getRightParam ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } } } if ( breakHere || ! indexFieldFound ) { break ; } } if ( result . keyCondition . getSubBlocks ( ) . size ( ) < index . getDefinition ( ) . getFields ( ) . size ( ) && ! index . supportsOrderedIterations ( ) ) { //hash indexes do not support partial key match return null ; } if ( found ) { result . remainingCondition = blockCopy ; return result ; } return null ; }


Input: given a full text index and a flat AND block returns a descriptor on how to process it with an index ( index index key and additional filters to apply after index fetch [CODESPLIT] private IndexSearchDescriptor buildIndexSearchDescriptorForFulltext ( OCommandContext ctx , OIndex < ? > index , OAndBlock block , OClass clazz ) { List < String > indexFields = index . getDefinition ( ) . getFields ( ) ; OBinaryCondition keyCondition = new OBinaryCondition ( - 1 ) ; OIdentifier key = new OIdentifier ( "key" ) ; keyCondition . setLeft ( new OExpression ( key ) ) ; boolean found = false ; OAndBlock blockCopy = block . copy ( ) ; Iterator < OBooleanExpression > blockIterator ; OAndBlock indexKeyValue = new OAndBlock ( - 1 ) ; IndexSearchDescriptor result = new IndexSearchDescriptor ( ) ; result . idx = index ; result . keyCondition = indexKeyValue ; for ( String indexField : indexFields ) { blockIterator = blockCopy . getSubBlocks ( ) . iterator ( ) ; boolean breakHere = false ; boolean indexFieldFound = false ; while ( blockIterator . hasNext ( ) ) { OBooleanExpression singleExp = blockIterator . next ( ) ; if ( singleExp instanceof OContainsTextCondition ) { OExpression left = ( ( OContainsTextCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { found = true ; indexFieldFound = true ; OContainsTextCondition condition = new OContainsTextCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRight ( ( ( OContainsTextCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } } if ( breakHere || ! indexFieldFound ) { break ; } } if ( result . keyCondition . getSubBlocks ( ) . size ( ) < index . getDefinition ( ) . getFields ( ) . size ( ) && ! index . supportsOrderedIterations ( ) ) { //hash indexes do not support partial key match return null ; } if ( found ) { result . remainingCondition = blockCopy ; return result ; } return null ; }


Input: aggregates multiple index conditions that refer to the same key search [CODESPLIT] private List < IndexSearchDescriptor > commonFactor ( List < IndexSearchDescriptor > indexSearchDescriptors ) { //index, key condition, additional filter (to aggregate in OR) Map < OIndex , Map < IndexCondPair , OOrBlock > > aggregation = new HashMap <> ( ) ; for ( IndexSearchDescriptor item : indexSearchDescriptors ) { Map < IndexCondPair , OOrBlock > filtersForIndex = aggregation . get ( item . idx ) ; if ( filtersForIndex == null ) { filtersForIndex = new HashMap <> ( ) ; aggregation . put ( item . idx , filtersForIndex ) ; } IndexCondPair extendedCond = new IndexCondPair ( item . keyCondition , item . additionalRangeCondition ) ; OOrBlock existingAdditionalConditions = filtersForIndex . get ( extendedCond ) ; if ( existingAdditionalConditions == null ) { existingAdditionalConditions = new OOrBlock ( - 1 ) ; filtersForIndex . put ( extendedCond , existingAdditionalConditions ) ; } existingAdditionalConditions . getSubBlocks ( ) . add ( item . remainingCondition ) ; } List < IndexSearchDescriptor > result = new ArrayList <> ( ) ; for ( Map . Entry < OIndex , Map < IndexCondPair , OOrBlock > > item : aggregation . entrySet ( ) ) { for ( Map . Entry < IndexCondPair , OOrBlock > filters : item . getValue ( ) . entrySet ( ) ) { result . add ( new IndexSearchDescriptor ( item . getKey ( ) , filters . getKey ( ) . mainCondition , filters . getKey ( ) . additionalRange , filters . getValue ( ) ) ) ; } } return result ; }


Input: Creates a new instance of the requested strategy . Since strategies are stateless if an existing instance already exists then it s returned . [CODESPLIT] public ODocumentFieldHandlingStrategy create ( int strategy ) { Optional < ODocumentFieldHandlingStrategy > registered = ODocumentFieldHandlingStrategyRegistry . getInstance ( ) . getStrategy ( strategy ) ; if ( registered . isPresent ( ) ) { return registered . get ( ) ; } Map < OType , ODocumentFieldOTypeHandlingStrategy > typeHandlingStrategies = new HashMap < OType , ODocumentFieldOTypeHandlingStrategy > ( ) ; switch ( strategy ) { case SINGLE_ORECORD_BYTES : typeHandlingStrategies . put ( OType . BINARY , new ODocumentSingleRecordBytesOTypeHandlingStrategy ( ) ) ; break ; case SPLIT_ORECORD_BYTES : typeHandlingStrategies . put ( OType . BINARY , new ODocumentSplitRecordBytesOTypeHandlingStrategy ( ) ) ; break ; case SIMPLE : default : break ; } ODocumentSmartFieldHandlingStrategy strategyInstance = new ODocumentSmartFieldHandlingStrategy ( typeHandlingStrategies ) ; ODocumentFieldHandlingStrategyRegistry . getInstance ( ) . registerStrategy ( strategy , strategyInstance ) ; return strategyInstance ; }


Input:
Re - Create any object if the class has a public constructor that accepts a String as unique parameter . [CODESPLIT] public Object fromStream ( final String iStream ) { if ( iStream == null || iStream . length ( ) == 0 ) // NULL VALUE
 return null ; OSerializableStream instance = null ; int propertyPos = iStream . indexOf ( ' ' ) ; int pos = iStream . indexOf ( OStringSerializerEmbedded . SEPARATOR ) ; if ( pos < 0 || propertyPos > - 1 && pos > propertyPos ) { instance = new ODocument ( ) ; pos = - 1 ; } else { final String className = iStream . substring ( 0 , pos ) ; try { final Class < ? > clazz = Class . forName ( className ) ; instance = ( OSerializableStream ) clazz . newInstance ( ) ; } catch ( Exception e ) { final String message = "Error on unmarshalling content. Class: " + className ; OLogManager . instance ( ) . error ( this , message , e ) ; throw OException . wrapException ( new OSerializationException ( message ) , e ) ; } } instance . fromStream ( Base64 . getDecoder ( ) . decode ( iStream . substring ( pos + 1 ) ) ) ; return instance ; }


Input: Serialize the class name size + class name + object content [CODESPLIT] public StringBuilder toStream ( final StringBuilder iOutput , Object iValue ) { if ( iValue != null ) { if ( ! ( iValue instanceof OSerializableStream ) ) throw new OSerializationException ( "Cannot serialize the object since it's not implements the OSerializableStream interface" ) ; OSerializableStream stream = ( OSerializableStream ) iValue ; iOutput . append ( iValue . getClass ( ) . getName ( ) ) ; iOutput . append ( OStringSerializerEmbedded . SEPARATOR ) ; iOutput . append ( Base64 . getEncoder ( ) . encodeToString ( stream . toStream ( ) ) ) ; } return iOutput ; }


Input: Execute a function . [CODESPLIT] public Object execute ( final Object iThis , final OIdentifiable iCurrentRecord , final Object iCurrentResult , final OCommandContext iContext ) { // RESOLVE VALUES USING THE CURRENT RECORD for ( int i = 0 ; i < configuredParameters . length ; ++ i ) { runtimeParameters [ i ] = configuredParameters [ i ] ; if ( configuredParameters [ i ] instanceof OSQLFilterItemField ) { runtimeParameters [ i ] = ( ( OSQLFilterItemField ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OSQLFunctionRuntime ) runtimeParameters [ i ] = ( ( OSQLFunctionRuntime ) configuredParameters [ i ] ) . execute ( iThis , iCurrentRecord , iCurrentResult , iContext ) ; else if ( configuredParameters [ i ] instanceof OSQLFilterItemVariable ) { runtimeParameters [ i ] = ( ( OSQLFilterItemVariable ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OCommandSQL ) { try { runtimeParameters [ i ] = ( ( OCommandSQL ) configuredParameters [ i ] ) . setContext ( iContext ) . execute ( ) ; } catch ( OCommandExecutorNotFoundException ignore ) { // TRY WITH SIMPLE CONDITION final String text = ( ( OCommandSQL ) configuredParameters [ i ] ) . getText ( ) ; final OSQLPredicate pred = new OSQLPredicate ( text ) ; runtimeParameters [ i ] = pred . evaluate ( iCurrentRecord instanceof ORecord ? ( ORecord ) iCurrentRecord : null , ( ODocument ) iCurrentResult , iContext ) ; // REPLACE ORIGINAL PARAM configuredParameters [ i ] = pred ; } } else if ( configuredParameters [ i ] instanceof OSQLPredicate ) runtimeParameters [ i ] = ( ( OSQLPredicate ) configuredParameters [ i ] ) . evaluate ( iCurrentRecord . getRecord ( ) , ( iCurrentRecord instanceof ODocument ? ( ODocument ) iCurrentResult : null ) , iContext ) ; else if ( configuredParameters [ i ] instanceof String ) { if ( configuredParameters [ i ] . toString ( ) . startsWith ( "\"" ) || configuredParameters [ i ] . toString ( ) . startsWith ( "'" ) ) runtimeParameters [ i ] = OIOUtils . getStringContent ( configuredParameters [ i ] ) ; } } if ( function . getMaxParams ( ) == - 1 || function . getMaxParams ( ) > 0 ) { if ( runtimeParameters . length < function . getMinParams ( ) || ( function . getMaxParams ( ) > - 1 && runtimeParameters . length > function . getMaxParams ( ) ) ) throw new OCommandExecutionException ( "Syntax error: function '" + function . getName ( ) + "' needs " + ( function . getMinParams ( ) == function . getMaxParams ( ) ? function . getMinParams ( ) : function . getMinParams ( ) + "-" + function . getMaxParams ( ) ) + " argument(s) while has been received " + runtimeParameters . length ) ; } final Object functionResult = function . execute ( iThis , iCurrentRecord , iCurrentResult , runtimeParameters , iContext ) ; if ( functionResult instanceof OAutoConvertToRecord ) // FORCE AVOIDING TO CONVERT IN RECORD ( ( OAutoConvertToRecord ) functionResult ) . setAutoConvertToRecord ( false ) ; return transformValue ( iCurrentRecord , iContext , functionResult ) ; }


Input: Checks if the user has the permission to access to the requested resource for the requested operation . [CODESPLIT] public ORole allow ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific , final int iOperation ) { if ( roles == null || roles . isEmpty ( ) ) { if ( document . field ( "roles" ) != null && ! ( ( Collection < OIdentifiable > ) document . field ( "roles" ) ) . isEmpty ( ) ) { final ODocument doc = document ; document = null ; fromStream ( doc ) ; } else throw new OSecurityAccessException ( document . getDatabase ( ) . getName ( ) , "User '" + document . field ( "name" ) + "' has no role defined" ) ; } final ORole role = checkIfAllowed ( resourceGeneric , resourceSpecific , iOperation ) ; if ( role == null ) throw new OSecurityAccessException ( document . getDatabase ( ) . getName ( ) , "User '" + document . field ( "name" ) + "' does not have permission to execute the operation '" + ORole . permissionToString ( iOperation ) + "' against the resource: " + resourceGeneric + "." + resourceSpecific ) ; return role ; }


Input: Checks if a rule was defined for the user . [CODESPLIT] public boolean isRuleDefined ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific ) { for ( ORole r : roles ) if ( r == null ) OLogManager . instance ( ) . warn ( this , "User '%s' has a null role, bypass it. Consider to fix this user roles before to continue" , getName ( ) ) ; else if ( r . hasRule ( resourceGeneric , resourceSpecific ) ) return true ; return false ; }


Input: Create a compact string with all the relevant information . [CODESPLIT] public static String getCompactServerStatus ( final ODistributedServerManager manager , final ODocument distribCfg ) { final StringBuilder buffer = new StringBuilder ( ) ; final Collection < ODocument > members = distribCfg . field ( "members" ) ; if ( members != null ) { buffer . append ( members . size ( ) ) ; buffer . append ( ":[" ) ; int memberCount = 0 ; for ( ODocument m : members ) { if ( m == null ) continue ; if ( memberCount ++ > 0 ) buffer . append ( "," ) ; final String serverName = m . field ( "name" ) ; buffer . append ( serverName ) ; buffer . append ( ( Object ) m . field ( "status" ) ) ; final Collection < String > databases = m . field ( "databases" ) ; if ( databases != null ) { buffer . append ( "{" ) ; int dbCount = 0 ; for ( String dbName : databases ) { final ODistributedConfiguration dbCfg = manager . getDatabaseConfiguration ( dbName , false ) ; if ( dbCfg == null ) continue ; if ( dbCount ++ > 0 ) buffer . append ( "," ) ; buffer . append ( dbName ) ; buffer . append ( "=" ) ; buffer . append ( manager . getDatabaseStatus ( serverName , dbName ) ) ; buffer . append ( " (" ) ; buffer . append ( dbCfg . getServerRole ( serverName ) ) ; buffer . append ( ")" ) ; } buffer . append ( "}" ) ; } } buffer . append ( "]" ) ; } return buffer . toString ( ) ; }


Input: Protecte system database from being replicated [CODESPLIT] protected void initSystemDatabase ( ) { final ODocument defaultCfg = getStorage ( OSystemDatabase . SYSTEM_DB_NAME ) . loadDatabaseConfiguration ( getDefaultDatabaseConfigFile ( ) ) ; defaultCfg . field ( "autoDeploy" , false ) ; final OModifiableDistributedConfiguration sysCfg = new OModifiableDistributedConfiguration ( defaultCfg ) ; sysCfg . removeServer ( "<NEW_NODE>" ) ; messageService . registerDatabase ( OSystemDatabase . SYSTEM_DB_NAME , sysCfg ) ; sysCfg . addNewNodeInServerList ( getLocalNodeName ( ) ) ; }


Input: Initializes all the available server s databases as distributed . [CODESPLIT] protected void loadLocalDatabases ( ) { final List < String > dbs = new ArrayList < String > ( serverInstance . getAvailableStorageNames ( ) . keySet ( ) ) ; Collections . sort ( dbs ) ; for ( final String databaseName : dbs ) { if ( messageService . getDatabase ( databaseName ) == null ) { ODistributedServerLog . info ( this , nodeName , null , DIRECTION . NONE , "Opening database '%s'..." , databaseName ) ; // INIT THE STORAGE final ODistributedStorage stg = getStorage ( databaseName ) ; executeInDistributedDatabaseLock ( databaseName , 60000 , null , new OCallable < Object , OModifiableDistributedConfiguration > ( ) { @ Override public Object call ( OModifiableDistributedConfiguration cfg ) { ODistributedServerLog . info ( this , nodeName , null , DIRECTION . NONE , "Current node started as %s for database '%s'" , cfg . getServerRole ( nodeName ) , databaseName ) ; final ODistributedDatabaseImpl ddb = messageService . registerDatabase ( databaseName , cfg ) ; ddb . resume ( ) ; // 1ST NODE TO HAVE THE DATABASE cfg . addNewNodeInServerList ( nodeName ) ; // COLLECT ALL THE CLUSTERS WITH REMOVED NODE AS OWNER reassignClustersOwnership ( nodeName , databaseName , cfg , true ) ; try { ddb . getSyncConfiguration ( ) . setLastLSN ( nodeName , ( ( OAbstractPaginatedStorage ) stg . getUnderlying ( ) ) . getLSN ( ) , false ) ; } catch ( IOException e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , "Error on saving distributed LSN for database '%s' (err=%s)." , databaseName , e . getMessage ( ) ) ; } ddb . setOnline ( ) ; return null ; } } ) ; } } }


Input: Removes the node map entry . [CODESPLIT] @ Override public void memberRemoved ( final MembershipEvent iEvent ) { try { updateLastClusterChange ( ) ; if ( iEvent . getMember ( ) == null ) return ; final String nodeLeftName = getNodeName ( iEvent . getMember ( ) ) ; if ( nodeLeftName == null ) return ; removeServer ( nodeLeftName , true ) ; } catch ( HazelcastInstanceNotActiveException | RetryableHazelcastException e ) { OLogManager . instance ( ) . error ( this , "Hazelcast is not running" , e ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Error on removing the server '%s'" , e , getNodeName ( iEvent . getMember ( ) ) ) ; } }


Input: Elects a new server as coordinator . The election browse the ordered server list . [CODESPLIT] @ Override public String electNewLockManager ( ) { if ( hazelcastInstance == null ) throw new HazelcastInstanceNotActiveException ( ) ; final ILock lock = hazelcastInstance . getLock ( "orientdb.lockManagerElection" ) ; lock . lock ( ) ; try { // TRY ALL THE SERVERS IN ORDER (ALL THE SERVERS HAVE THE SAME LIST) String lockManagerServer = getLockManagerRequester ( ) . getServer ( ) ; // PROTECT FROM DOUBLE LOCK MANAGER ELECTION IN CASE OF REMOVE OF LOCK MANAGER if ( lockManagerServer != null && getActiveServers ( ) . contains ( lockManagerServer ) ) return lockManagerServer ; final String originalLockManager = lockManagerServer ; ODistributedServerLog . debug ( this , nodeName , originalLockManager , DIRECTION . OUT , "lock '%s' is unreachable, electing a new lock..." , originalLockManager ) ; int lockManagerServerId = - 1 ; if ( lockManagerServer != null && registeredNodeByName . containsKey ( lockManagerServer ) ) lockManagerServerId = registeredNodeByName . get ( lockManagerServer ) ; String newServer = null ; int currIndex = lockManagerServerId ; for ( int i = 0 ; i < registeredNodeById . size ( ) ; ++ i ) { currIndex ++ ; if ( currIndex >= registeredNodeById . size ( ) ) // RESTART FROM THE FIRST currIndex = 0 ; newServer = registeredNodeById . get ( currIndex ) ; if ( newServer == null ) throw new OConfigurationException ( "Found null server at index " + currIndex + " of server list " + registeredNodeById ) ; if ( newServer . equalsIgnoreCase ( getLocalNodeName ( ) ) || activeNodes . containsKey ( newServer ) ) { // TODO: IMPROVE ELECTION BY CHECKING AL THE NODES AGREE ON IT ODistributedServerLog . debug ( this , nodeName , newServer , DIRECTION . OUT , "Trying to elected server '%s' as new lock (old=%s)..." , newServer , originalLockManager ) ; try { getLockManagerRequester ( ) . setServer ( newServer ) ; configurationMap . put ( CONFIG_LOCKMANAGER , getLockManagerRequester ( ) . getServer ( ) ) ; ODistributedServerLog . info ( this , nodeName , newServer , DIRECTION . OUT , "Elected server '%s' as new lock (old=%s)" , newServer , originalLockManager ) ; break ; } catch ( Exception e ) { // NO SERVER RESPONDED, THE SERVER COULD BE ISOLATED, GO AHEAD WITH THE NEXT IN THE LIST ODistributedServerLog . info ( this , nodeName , newServer , DIRECTION . OUT , "Error on electing server '%s' as new lock (error: %s)" , newServer , e ) ; } } } return newServer ; } finally { lock . unlock ( ) ; } }


Input: ASSIGN THE LOCK MANAGER AT STARTUP [CODESPLIT] private void assignLockManagerFromCluster ( ) { String lockManagerServer = null ; while ( lockManagerServer == null ) { if ( activeNodes . size ( ) == 1 ) { // ONLY CURRENT NODE ONLINE, SET IT AS INITIAL LOCK MANAGER lockManagerServer = nodeName ; if ( configurationMap . putIfAbsent ( CONFIG_LOCKMANAGER , lockManagerServer ) == null ) break ; } else { lockManagerServer = ( String ) configurationMap . get ( CONFIG_LOCKMANAGER ) ; if ( lockManagerServer != null && lockManagerServer . equals ( nodeName ) ) { // LAST LOCK MANAGER WAS CURRENT NODE? TRY TO FORCE A NEW ELECTION OLogManager . instance ( ) . info ( this , "Found lock as current node, even if it was offline. Forcing a new election..." ) ; getLockManagerRequester ( ) . setServer ( lockManagerServer ) ; lockManagerServer = electNewLockManager ( ) ; break ; } if ( lockManagerServer != null ) break ; } try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { break ; } } getLockManagerRequester ( ) . setServer ( lockManagerServer ) ; OLogManager . instance ( ) . info ( this , "Distributed Lock Manager server is '%s'" , lockManagerServer ) ; }


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


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


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


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


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


Input: Commits the micro - transaction if it s a top - level micro - transaction . [CODESPLIT] public void commit ( ) { if ( ! active ) throw error ( "Inactive micro-transaction on commit" ) ; if ( level < 1 ) throw error ( "Unbalanced micro-transaction, level = " + level ) ; -- level ; if ( level == 0 ) { active = false ; doCommit ( ) ; } }


Input: Rollbacks the micro - transaction if it s a top - level micro - transaction . [CODESPLIT] public void rollback ( ) { if ( ! active ) throw error ( "Inactive micro-transaction on rollback" ) ; if ( level < 1 ) throw error ( "Unbalanced micro-transaction, level = " + level ) ; -- level ; if ( level == 0 ) { active = false ; doRollback ( ) ; } }


Input: Updates the record identity after its successful commit . [CODESPLIT] public void updateIdentityAfterRecordCommit ( final ORID oldRid , final ORID newRid ) { if ( oldRid . equals ( newRid ) ) return ; // no change, ignore // XXX: Identity update may mutate the index keys, so we have to identify and reinsert potentially affected index keys to keep // the OTransactionIndexChanges.changesPerKey in a consistent state. final List < KeyChangesUpdateRecord > keyRecordsToReinsert = new ArrayList <> ( ) ; final OIndexManager indexManager = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) ; for ( Map . Entry < String , OTransactionIndexChanges > entry : indexOperations . entrySet ( ) ) { final OIndex < ? > index = indexManager . getIndex ( entry . getKey ( ) ) ; if ( index == null ) throw new OTransactionException ( "Cannot find index '" + entry . getValue ( ) + "' while committing transaction" ) ; final Dependency [ ] fieldRidDependencies = getIndexFieldRidDependencies ( index ) ; if ( ! isIndexMayDependOnRids ( fieldRidDependencies ) ) continue ; final OTransactionIndexChanges indexChanges = entry . getValue ( ) ; for ( final Iterator < OTransactionIndexChangesPerKey > iterator = indexChanges . changesPerKey . values ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { final OTransactionIndexChangesPerKey keyChanges = iterator . next ( ) ; if ( isIndexKeyMayDependOnRid ( keyChanges . key , oldRid , fieldRidDependencies ) ) { keyRecordsToReinsert . add ( new KeyChangesUpdateRecord ( keyChanges , indexChanges ) ) ; iterator . remove ( ) ; } } } // Update the identity. final ORecordOperation rec = resolveRecordOperation ( oldRid ) ; if ( rec != null ) { updatedRids . put ( newRid . copy ( ) , oldRid . copy ( ) ) ; if ( ! rec . getRecord ( ) . getIdentity ( ) . equals ( newRid ) ) { ORecordInternal . onBeforeIdentityChanged ( rec . getRecord ( ) ) ; final ORecordId recordId = ( ORecordId ) rec . getRecord ( ) . getIdentity ( ) ; if ( recordId == null ) { ORecordInternal . setIdentity ( rec . getRecord ( ) , new ORecordId ( newRid ) ) ; } else { recordId . setClusterPosition ( newRid . getClusterPosition ( ) ) ; recordId . setClusterId ( newRid . getClusterId ( ) ) ; } ORecordInternal . onAfterIdentityChanged ( rec . getRecord ( ) ) ; } } // Reinsert the potentially affected index keys. for ( KeyChangesUpdateRecord record : keyRecordsToReinsert ) record . indexChanges . changesPerKey . put ( record . keyChanges . key , record . keyChanges ) ; // Update the indexes. final List < OTransactionRecordIndexOperation > transactionIndexOperations = recordIndexOperations . get ( translateRid ( oldRid ) ) ; if ( transactionIndexOperations != null ) { for ( final OTransactionRecordIndexOperation indexOperation : transactionIndexOperations ) { OTransactionIndexChanges indexEntryChanges = indexOperations . get ( indexOperation . index ) ; if ( indexEntryChanges == null ) continue ; final OTransactionIndexChangesPerKey keyChanges ; if ( indexOperation . key == null ) { keyChanges = indexEntryChanges . nullKeyChanges ; } else { keyChanges = indexEntryChanges . changesPerKey . get ( indexOperation . key ) ; } if ( keyChanges != null ) updateChangesIdentity ( oldRid , newRid , keyChanges ) ; } } }


Input: Updates the record cache after unsuccessful micro - transaction commit . [CODESPLIT] public void updateRecordCacheAfterRollback ( ) { final OLocalRecordCache databaseLocalCache = database . getLocalCache ( ) ; for ( ORecordOperation recordOperation : recordOperations . values ( ) ) databaseLocalCache . deleteRecord ( recordOperation . getRecord ( ) . getIdentity ( ) ) ; }


Input: Prepares the path for a file creation or replacement . If the file pointed by the path already exists it will be deleted a warning will be emitted to the log in this case . All absent directories along the path will be created . [CODESPLIT] public static void prepareForFileCreationOrReplacement ( Path path , Object requester , String operation ) throws IOException { if ( Files . deleteIfExists ( path ) ) OLogManager . instance ( ) . warn ( requester , "'%s' deleted while %s" , path , operation ) ; final Path parent = path . getParent ( ) ; if ( parent != null ) Files . createDirectories ( parent ) ; }


Input: Tries to move a file from the source to the target atomically . If atomic move is not possible falls back to regular move . [CODESPLIT] public static void atomicMoveWithFallback ( Path source , Path target , Object requester ) throws IOException { try { Files . move ( source , target , StandardCopyOption . ATOMIC_MOVE ) ; } catch ( AtomicMoveNotSupportedException ignore ) { OLogManager . instance ( ) . warn ( requester , "atomic file move is not possible, falling back to regular move (moving '%s' to '%s')" , source , target ) ; Files . move ( source , target ) ; } }


Input: splits this pattern into multiple [CODESPLIT] public List < Pattern > getDisjointPatterns ( ) { Map < PatternNode , String > reverseMap = new IdentityHashMap <> ( ) ; reverseMap . putAll ( this . aliasToNode . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( x -> x . getValue ( ) , x -> x . getKey ( ) ) ) ) ; List < Pattern > result = new ArrayList <> ( ) ; while ( ! reverseMap . isEmpty ( ) ) { Pattern pattern = new Pattern ( ) ; result . add ( pattern ) ; Map . Entry < PatternNode , String > nextNode = reverseMap . entrySet ( ) . iterator ( ) . next ( ) ; Set < PatternNode > toVisit = new HashSet <> ( ) ; toVisit . add ( nextNode . getKey ( ) ) ; while ( toVisit . size ( ) > 0 ) { PatternNode currentNode = toVisit . iterator ( ) . next ( ) ; toVisit . remove ( currentNode ) ; if ( reverseMap . containsKey ( currentNode ) ) { pattern . aliasToNode . put ( reverseMap . get ( currentNode ) , currentNode ) ; reverseMap . remove ( currentNode ) ; for ( PatternEdge x : currentNode . out ) { toVisit . add ( x . in ) ; } for ( PatternEdge x : currentNode . in ) { toVisit . add ( x . out ) ; } } } pattern . recalculateNumOfEdges ( ) ; } return result ; }