signature:
public class EJBClientContextIdentifierResolver { /** * { @ inheritDoc } */
@ Override public Object writeReplace ( Object object ) { } }

implementation: return EJBClient . isEJBProxy ( object ) ? new SerializableEJBProxy ( object ) : object ;


signature:
public class ConcurrentContext { /** * Adds a new factory .
 * @ param factory */
public synchronized void addFactory ( ContextHandleFactory factory ) { } }

implementation: final String factoryName = factory . getName ( ) ; if ( factoryMap . containsKey ( factoryName ) ) { throw EeLogger . ROOT_LOGGER . factoryAlreadyExists ( this , factoryName ) ; } factoryMap . put ( factoryName , factory ) ; final Comparator < ContextHandleFactory > comparator = new Comparator < ContextHandleFactory > ( ) { @ Override public int compare ( ContextHandleFactory o1 , ContextHandleFactory o2 ) { return Integer . compare ( o1 . getChainPriority ( ) , o2 . getChainPriority ( ) ) ; } } ; SortedSet < ContextHandleFactory > sortedSet = new TreeSet < > ( comparator ) ; sortedSet . addAll ( factoryMap . values ( ) ) ; factoryOrderedList = new ArrayList < > ( sortedSet ) ;


signature:
public class ConcurrentContext { /** * Saves the current invocation context on a chained context handle .
 * @ param contextService
 * @ param contextObjectProperties
 * @ return */
public SetupContextHandle saveContext ( ContextService contextService , Map < String , String > contextObjectProperties ) { } }

implementation: final List < SetupContextHandle > handles = new ArrayList < > ( factoryOrderedList . size ( ) ) ; for ( ContextHandleFactory factory : factoryOrderedList ) { handles . add ( factory . saveContext ( contextService , contextObjectProperties ) ) ; } return new ChainedSetupContextHandle ( this , handles ) ;


signature:
public class javaURLContextFactory { /** * { @ inheritDoc } */
public Object getObjectInstance ( Object obj , Name name , Context nameCtx , Hashtable < ? , ? > environment ) throws Exception { } }

implementation: return new NamingContext ( name != null ? name : new CompositeName ( "" ) , environment ) ;


signature:
public class BeanDeploymentArchiveImpl { /** * Adds multiple accessible { @ link BeanDeploymentArchive } s */
public void addBeanDeploymentArchives ( Collection < ? extends BeanDeploymentArchive > archives ) { } }

implementation: for ( BeanDeploymentArchive bda : archives ) { if ( bda != this ) { beanDeploymentArchives . add ( bda ) ; } }


signature:
public class BeanDeploymentArchiveImpl { /** * Determines if a class from this { @ link BeanDeploymentArchiveImpl } instance can access a class in the
 * { @ link BeanDeploymentArchive } instance represented by the specified < code > BeanDeploymentArchive < / code > parameter
 * according to the Java EE class accessibility requirements .
 * @ param target
 * @ return true if an only if a class this archive can access a class from the archive represented by the specified parameter */
public boolean isAccessible ( BeanDeploymentArchive target ) { } }

implementation:
if ( this == target ) { return true ; } BeanDeploymentArchiveImpl that = ( BeanDeploymentArchiveImpl ) target ; if ( that . getModule ( ) == null ) { /* * The target BDA is the bootstrap BDA - it bundles classes loaded by the bootstrap classloader .
 * Everyone can see the bootstrap classloader . */
return true ; } if ( module == null ) { /* * This BDA is the bootstrap BDA - it bundles classes loaded by the bootstrap classloader . We assume that a
 * bean whose class is loaded by the bootstrap classloader can only see other beans in the " bootstrap BDA " . */
return that . getModule ( ) == null ; } if ( module . equals ( that . getModule ( ) ) ) { return true ; } // basic check whether the module is our dependency
for ( DependencySpec dependency : module . getDependencies ( ) ) { if ( dependency instanceof ModuleDependencySpec ) { ModuleDependencySpec moduleDependency = ( ModuleDependencySpec ) dependency ; if ( moduleDependency . getIdentifier ( ) . equals ( that . getModule ( ) . getIdentifier ( ) ) ) { return true ; } // moduleDependency might be an alias - try to load it to get lined module
Module module = loadModule ( moduleDependency ) ; if ( module != null && module . getIdentifier ( ) . equals ( that . getModule ( ) . getIdentifier ( ) ) ) { return true ; } } } /* * full check - we try to load a class from the target bean archive and check whether its module
 * is the same as the one of the bean archive
 * See WFLY - 4250 for more info */
Iterator < String > iterator = target . getBeanClasses ( ) . iterator ( ) ; if ( iterator . hasNext ( ) ) { Class < ? > clazz = Reflections . loadClass ( iterator . next ( ) , module . getClassLoader ( ) ) ; if ( clazz != null ) { Module classModule = Module . forClass ( clazz ) ; return classModule != null && classModule . equals ( that . getModule ( ) ) ; } } return false ;


signature:
public class WebMigrateOperation { /** * Creates the security realm
 * @ param context
 * @ param migrationOperations
 * @ return */
private SSLInformation createSecurityRealm ( OperationContext context , Map < PathAddress , ModelNode > migrationOperations , ModelNode legacyModelAddOps , String connector , ModelNode legacyAddOp , List < String > warnings , boolean domainMode ) { } }

implementation:
// read all the info from the SSL definition
ModelNode keyAlias = legacyAddOp . get ( WebSSLDefinition . KEY_ALIAS . getName ( ) ) ; ModelNode password = legacyAddOp . get ( WebSSLDefinition . PASSWORD . getName ( ) ) ; ModelNode certificateKeyFile = legacyAddOp . get ( WebSSLDefinition . CERTIFICATE_KEY_FILE . getName ( ) ) ; ModelNode cipherSuite = legacyAddOp . get ( WebSSLDefinition . CIPHER_SUITE . getName ( ) ) ; ModelNode protocol = legacyAddOp . get ( WebSSLDefinition . PROTOCOL . getName ( ) ) ; ModelNode verifyClient = legacyAddOp . get ( WebSSLDefinition . VERIFY_CLIENT . getName ( ) ) ; ModelNode verifyDepth = legacyAddOp . get ( WebSSLDefinition . VERIFY_DEPTH . getName ( ) ) ; ModelNode certificateFile = legacyAddOp . get ( WebSSLDefinition . CERTIFICATE_FILE . getName ( ) ) ; ModelNode caCertificateFile = legacyAddOp . get ( WebSSLDefinition . CA_CERTIFICATE_FILE . getName ( ) ) ; ModelNode caCertificatePassword = legacyAddOp . get ( WebSSLDefinition . CA_CERTIFICATE_PASSWORD . getName ( ) ) ; ModelNode csRevocationURL = legacyAddOp . get ( WebSSLDefinition . CA_REVOCATION_URL . getName ( ) ) ; ModelNode trustStoreType = legacyAddOp . get ( WebSSLDefinition . TRUSTSTORE_TYPE . getName ( ) ) ; ModelNode keystoreType = legacyAddOp . get ( WebSSLDefinition . KEYSTORE_TYPE . getName ( ) ) ; ModelNode sessionCacheSize = legacyAddOp . get ( WebSSLDefinition . SESSION_CACHE_SIZE . getName ( ) ) ; ModelNode sessionTimeout = legacyAddOp . get ( WebSSLDefinition . SESSION_TIMEOUT . getName ( ) ) ; ModelNode sslProvider = legacyAddOp . get ( WebSSLDefinition . SSL_PROTOCOL . getName ( ) ) ; if ( verifyDepth . isDefined ( ) ) { warnings . add ( WebLogger . ROOT_LOGGER . couldNotMigrateResource ( WebSSLDefinition . VERIFY_DEPTH . getName ( ) , pathAddress ( legacyAddOp . get ( ADDRESS ) ) ) ) ; } if ( certificateFile . isDefined ( ) ) { warnings . add ( WebLogger . ROOT_LOGGER . couldNotMigrateResource ( WebSSLDefinition . CERTIFICATE_FILE . getName ( ) , pathAddress ( legacyAddOp . get ( ADDRESS ) ) ) ) ; } if ( sslProvider . isDefined ( ) ) { warnings . add ( WebLogger . ROOT_LOGGER . couldNotMigrateResource ( WebSSLDefinition . SSL_PROTOCOL . getName ( ) , pathAddress ( legacyAddOp . get ( ADDRESS ) ) ) ) ; } if ( csRevocationURL . isDefined ( ) ) { warnings . add ( WebLogger . ROOT_LOGGER . couldNotMigrateResource ( WebSSLDefinition . CA_REVOCATION_URL . getName ( ) , pathAddress ( legacyAddOp . get ( ADDRESS ) ) ) ) ; } String realmName ; PathAddress managementCoreService ; if ( domainMode ) { Set < String > hosts = new HashSet < > ( ) ; Resource hostResource = context . readResourceFromRoot ( pathAddress ( ) , false ) ; hosts . addAll ( hostResource . getChildrenNames ( HOST ) ) ; // now we need to find a unique name
// in domain mode different profiles could have different SSL configurations
// but the realms are not scoped to a profile
// if we hard coded a name migration would fail when migrating domains with multiple profiles
int counter = 1 ; realmName = REALM_NAME + counter ; while ( true ) { boolean hostOk = true ; for ( String host : hosts ) { Resource root = context . readResourceFromRoot ( pathAddress ( pathElement ( HOST , host ) , pathElement ( CORE_SERVICE , MANAGEMENT ) ) , false ) ; if ( root . getChildrenNames ( SECURITY_REALM ) . contains ( realmName ) ) { counter ++ ; realmName = REALM_NAME + counter ; hostOk = false ; break ; } } if ( hostOk ) { break ; } } for ( String host : hosts ) { createHostSSLConfig ( realmName , migrationOperations , keyAlias , password , certificateKeyFile , protocol , caCertificateFile , caCertificatePassword , trustStoreType , keystoreType , pathAddress ( pathElement ( HOST , host ) , pathElement ( CORE_SERVICE , MANAGEMENT ) ) ) ; } } else { managementCoreService = pathAddress ( CORE_SERVICE , MANAGEMENT ) ; // now we need to find a unique name
// in domain mode different profiles could have different SSL configurations
// but the realms are not scoped to a profile
// if we hard coded a name migration would fail when migrating domains with multiple profiles
int counter = 1 ; realmName = REALM_NAME + counter ; boolean ok = false ; do { Resource root = context . readResourceFromRoot ( managementCoreService , false ) ; if ( root . getChildrenNames ( SECURITY_REALM ) . contains ( realmName ) ) { counter ++ ; realmName = REALM_NAME + counter ; } else { ok = true ; } } while ( ! ok ) ; // we have a unique realm name
createHostSSLConfig ( realmName , migrationOperations , keyAlias , password , certificateKeyFile , protocol , caCertificateFile , caCertificatePassword , trustStoreType , keystoreType , managementCoreService ) ; } return new SSLInformation ( realmName , verifyClient , sessionCacheSize , sessionTimeout , protocol , cipherSuite ) ;


signature:
public class WebMigrateOperation { /** * We need to create the IO subsystem , if it does not already exist */
private void createIoSubsystem ( OperationContext context , Map < PathAddress , ModelNode > migrationOperations , PathAddress baseAddress ) { } }

implementation:
Resource root = context . readResourceFromRoot ( baseAddress , false ) ; if ( root . getChildrenNames ( SUBSYSTEM ) . contains ( IOExtension . SUBSYSTEM_NAME ) ) { // subsystem is already added , do nothing
return ; } // these addresses will be fixed later , no need to use the base address
PathAddress address = pathAddress ( pathElement ( SUBSYSTEM , IOExtension . SUBSYSTEM_NAME ) ) ; migrationOperations . put ( address , createAddOperation ( address ) ) ; address = pathAddress ( pathElement ( SUBSYSTEM , IOExtension . SUBSYSTEM_NAME ) , pathElement ( "worker" , "default" ) ) ; migrationOperations . put ( address , createAddOperation ( address ) ) ; address = pathAddress ( pathElement ( SUBSYSTEM , IOExtension . SUBSYSTEM_NAME ) , pathElement ( "buffer-pool" , "default" ) ) ; migrationOperations . put ( address , createAddOperation ( address ) ) ;


signature:
public class WebMigrateOperation { /** * create a handler for serving welcome content */
private void createWelcomeContentHandler ( Map < PathAddress , ModelNode > migrationOperations ) { } }

implementation: PathAddress address = pathAddress ( pathElement ( SUBSYSTEM , UndertowExtension . SUBSYSTEM_NAME ) , pathElement ( Constants . CONFIGURATION , Constants . HANDLER ) ) ; migrationOperations . put ( address , createAddOperation ( address ) ) ; address = pathAddress ( pathElement ( SUBSYSTEM , UndertowExtension . SUBSYSTEM_NAME ) , pathElement ( Constants . CONFIGURATION , Constants . HANDLER ) , pathElement ( Constants . FILE , "welcome-content" ) ) ; final ModelNode add = createAddOperation ( address ) ; add . get ( Constants . PATH ) . set ( new ModelNode ( new ValueExpression ( "${jboss.home.dir}/welcome-content" ) ) ) ; migrationOperations . put ( address , add ) ;


signature:
public class MessageDrivenComponentDescriptionFactory { /** * Returns the name of the resource adapter which will be used as the default RA for MDBs ( unless overridden by
 * the MDBs ) .
 * @ param serviceRegistry
 * @ return */
private String getDefaultResourceAdapterName ( final ServiceRegistry serviceRegistry ) { } }

implementation:
if ( appclient ) { // we must report the MDB , but we can ' t use any MDB / JCA facilities
return "n/a" ; } final ServiceController < DefaultResourceAdapterService > serviceController = ( ServiceController < DefaultResourceAdapterService > ) serviceRegistry . getRequiredService ( DefaultResourceAdapterService . DEFAULT_RA_NAME_SERVICE_NAME ) ; return serviceController . getValue ( ) . getDefaultResourceAdapterName ( ) ;


signature:
public class StrictMaxPool { /** * Get an instance without identity .
 * Can be used by finders , create - methods , and activation
 * @ return Context / w instance */
public T get ( ) { } }

implementation:
try { boolean acquired = semaphore . tryAcquire ( timeout , timeUnit ) ; if ( ! acquired ) throw EjbLogger . ROOT_LOGGER . failedToAcquirePermit ( timeout , timeUnit ) ; } catch ( InterruptedException e ) { throw EjbLogger . ROOT_LOGGER . acquireSemaphoreInterrupted ( ) ; } T bean = pool . poll ( ) ; if ( bean != null ) { // we found a bean instance in the pool , return it
return bean ; } try { // Pool is empty , create an instance
bean = create ( ) ; } finally { if ( bean == null ) { semaphore . release ( ) ; } } return bean ;


signature:
public class StrictMaxPool { /** * Return an instance after invocation .
 * Called in 2 cases :
 * a ) Done with finder method
 * b ) Just removed
 * @ param obj */
public void release ( T obj ) { } }

implementation: if ( ROOT_LOGGER . isTraceEnabled ( ) ) { ROOT_LOGGER . tracef ( "%s/%s Free instance: %s" , pool . size ( ) , maxSize , this ) ; } pool . add ( obj ) ; semaphore . release ( ) ;


signature:
public class InterfaceAnalysis { /** * Return a list of all the entries contained here . */
protected ArrayList getContainedEntries ( ) { } }

implementation: final ArrayList ret = new ArrayList ( constants . length + attributes . length + operations . length ) ; for ( int i = 0 ; i < constants . length ; ++ i ) ret . add ( constants [ i ] ) ; for ( int i = 0 ; i < attributes . length ; ++ i ) ret . add ( attributes [ i ] ) ; for ( int i = 0 ; i < operations . length ; ++ i ) ret . add ( operations [ i ] ) ; return ret ;


signature:
public class InterfaceAnalysis { /** * Analyse operations .
 * This will fill in the < code > operations < / code > array . */
protected void analyzeOperations ( ) throws RMIIIOPViolationException { } }

implementation: if ( ! cls . isInterface ( ) ) throw IIOPLogger . ROOT_LOGGER . notAnInterface ( cls . getName ( ) ) ; abstractInterface = RmiIdlUtil . isAbstractInterface ( cls ) ; calculateAllTypeIds ( ) ; int operationCount = 0 ; for ( int i = 0 ; i < methods . length ; ++ i ) if ( ( m_flags [ i ] & ( M_READ | M_WRITE | M_READONLY ) ) == 0 ) ++ operationCount ; operations = new OperationAnalysis [ operationCount ] ; operationCount = 0 ; for ( int i = 0 ; i < methods . length ; ++ i ) { if ( ( m_flags [ i ] & ( M_READ | M_WRITE | M_READONLY ) ) == 0 ) { operations [ operationCount ] = new OperationAnalysis ( methods [ i ] ) ; ++ operationCount ; } }


signature:
public class InterfaceAnalysis { /** * Calculate the map that maps IDL operation names to operation analyses .
 * Besides mapped operations , this map also contains the attribute
 * accessor and mutator operations . */
protected void calculateOperationAnalysisMap ( ) { } }

implementation:
operationAnalysisMap = new HashMap ( ) ; OperationAnalysis oa ; // Map the operations
for ( int i = 0 ; i < operations . length ; ++ i ) { oa = operations [ i ] ; operationAnalysisMap . put ( oa . getIDLName ( ) , oa ) ; } // Map the attributes
for ( int i = 0 ; i < attributes . length ; ++ i ) { AttributeAnalysis attr = attributes [ i ] ; oa = attr . getAccessorAnalysis ( ) ; // Not having an accessor analysis means that
// the attribute is not in a remote interface
if ( oa != null ) { operationAnalysisMap . put ( oa . getIDLName ( ) , oa ) ; oa = attr . getMutatorAnalysis ( ) ; if ( oa != null ) operationAnalysisMap . put ( oa . getIDLName ( ) , oa ) ; } }


signature:
public class InterfaceAnalysis { /** * Calculate the array containing all type ids of this interface ,
 * in the format that org . omg . CORBA . portable . Servant . _ all _ interfaces ( )
 * is expected to return . */
protected void calculateAllTypeIds ( ) { } }

implementation: if ( ! isRmiIdlRemoteInterface ( ) ) { allTypeIds = new String [ 0 ] ; } else { ArrayList a = new ArrayList ( ) ; InterfaceAnalysis [ ] intfs = getInterfaces ( ) ; for ( int i = 0 ; i < intfs . length ; ++ i ) { String [ ] ss = intfs [ i ] . getAllTypeIds ( ) ; for ( int j = 0 ; j < ss . length ; ++ j ) if ( ! a . contains ( ss [ j ] ) ) a . add ( ss [ j ] ) ; } allTypeIds = new String [ a . size ( ) + 1 ] ; allTypeIds [ 0 ] = getRepositoryId ( ) ; for ( int i = 1 ; i <= a . size ( ) ; ++ i ) allTypeIds [ i ] = ( String ) a . get ( a . size ( ) - i ) ; }


signature:
public class MetricCollector { /** * collect metrics from the resources */
public MetricRegistration collectResourceMetrics ( final Resource resource , ImmutableManagementResourceRegistration managementResourceRegistration , Function < PathAddress , PathAddress > resourceAddressResolver ) { } }

implementation: MetricRegistration registration = new MetricRegistration ( ) ; collectResourceMetrics0 ( resource , managementResourceRegistration , EMPTY_ADDRESS , resourceAddressResolver , registration ) ; return registration ;


signature:
public class EndpointPublisherImpl { /** * Prepare the ws Deployment and return a DeploymentUnit containing it
 * @ param context
 * @ param loader
 * @ param urlPatternToClassNameMap
 * @ param jbwmd
 * @ param metadata
 * @ param jbwsMetadata
 * @ return */
protected DeploymentUnit doPrepare ( String context , ClassLoader loader , Map < String , String > urlPatternToClassNameMap , JBossWebMetaData jbwmd , WebservicesMetaData metadata , JBossWebservicesMetaData jbwsMetadata ) { } }

implementation: ClassLoader origClassLoader = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; WSEndpointDeploymentUnit unit = new WSEndpointDeploymentUnit ( loader , context , urlPatternToClassNameMap , jbwmd , metadata , jbwsMetadata ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( ClassLoaderProvider . getDefaultProvider ( ) . getServerIntegrationClassLoader ( ) ) ; WSDeploymentBuilder . getInstance ( ) . build ( unit ) ; return unit ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( origClassLoader ) ; }


signature:
public class EndpointPublisherImpl { /** * Triggers the WS deployment aspects , which process the deployment and
 * install the endpoint services .
 * @ param target
 * @ param unit */
protected void doDeploy ( ServiceTarget target , DeploymentUnit unit ) { } }

implementation: List < DeploymentAspect > aspects = getDeploymentAspects ( ) ; ClassLoader origClassLoader = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; Deployment dep = null ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( ClassLoaderProvider . getDefaultProvider ( ) . getServerIntegrationClassLoader ( ) ) ; dep = unit . getAttachment ( WSAttachmentKeys . DEPLOYMENT_KEY ) ; dep . addAttachment ( ServiceTarget . class , target ) ; DeploymentAspectManager dam = new DeploymentAspectManagerImpl ( ) ; dam . setDeploymentAspects ( aspects ) ; dam . deploy ( dep ) ; } finally { if ( dep != null ) { dep . removeAttachment ( ServiceTarget . class ) ; } WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( origClassLoader ) ; }


signature:
public class EndpointPublisherImpl { /** * Publish the webapp for the WS deployment unit
 * @ param target
 * @ param unit
 * @ return
 * @ throws Exception */
protected Context doPublish ( ServiceTarget target , DeploymentUnit unit ) throws Exception { } }

implementation:
Deployment deployment = unit . getAttachment ( WSAttachmentKeys . DEPLOYMENT_KEY ) ; List < Endpoint > endpoints = deployment . getService ( ) . getEndpoints ( ) ; // If we ' re running in a Service , that will already have proper dependencies set on the installed endpoint services ,
// otherwise we need to explicitly wait for the endpoint services to be started before creating the webapp .
if ( ! runningInService ) { final ServiceRegistry registry = unit . getServiceRegistry ( ) ; final StabilityMonitor monitor = new StabilityMonitor ( ) ; for ( Endpoint ep : endpoints ) { final ServiceName serviceName = EndpointService . getServiceName ( unit , ep . getShortName ( ) ) ; monitor . addController ( registry . getRequiredService ( serviceName ) ) ; } try { monitor . awaitStability ( ) ; } finally { monitor . clear ( ) ; } } deployment . addAttachment ( WebDeploymentController . class , startWebApp ( host , unit ) ) ; // TODO simplify and use findChild later in destroy ( ) / stopWebApp ( )
return new Context ( unit . getAttachment ( WSAttachmentKeys . JBOSSWEB_METADATA_KEY ) . getContextRoot ( ) , endpoints ) ;


signature:
public class EndpointPublisherImpl { /** * Stops the webapp serving the provided ws deployment
 * @ param deployment
 * @ throws Exception */
protected void stopWebApp ( Deployment deployment ) throws Exception { } }

implementation: WebDeploymentController context ; try { context = deployment . getAttachment ( WebDeploymentController . class ) ; context . stop ( ) ; } catch ( Exception e ) { throw WSLogger . ROOT_LOGGER . stopContextPhaseFailed ( e ) ; } try { context . destroy ( ) ; } catch ( Exception e ) { throw WSLogger . ROOT_LOGGER . destroyContextPhaseFailed ( e ) ; }


signature:
public class WeldBootstrapService { /** * Starts the weld container
 * @ throws IllegalStateException if the container is already running */
public synchronized void start ( final StartContext context ) { } }

implementation:
if ( started ) { throw WeldLogger . ROOT_LOGGER . alreadyRunning ( "WeldContainer" ) ; } started = true ; WeldLogger . DEPLOYMENT_LOGGER . startingWeldService ( deploymentName ) ; // set up injected services
addWeldService ( SecurityServices . class , securityServicesSupplier . get ( ) ) ; TransactionServices transactionServices = weldTransactionServicesSupplier != null ? weldTransactionServicesSupplier . get ( ) : null ; if ( transactionServices != null ) { addWeldService ( TransactionServices . class , transactionServices ) ; } if ( ! deployment . getServices ( ) . contains ( ExecutorServices . class ) ) { addWeldService ( ExecutorServices . class , executorServicesSupplier . get ( ) ) ; } ModuleGroupSingletonProvider . addClassLoaders ( deployment . getModule ( ) . getClassLoader ( ) , deployment . getSubDeploymentClassLoaders ( ) ) ; ClassLoader oldTccl = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( deployment . getModule ( ) . getClassLoader ( ) ) ; bootstrap . startContainer ( deploymentName , environment , deployment ) ; WeldProvider . containerInitialized ( Container . instance ( deploymentName ) , getBeanManager ( ) , deployment ) ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( oldTccl ) ; } weldBootstrapServiceConsumer . accept ( this ) ;


signature:
public class WeldBootstrapService { /** * This is a no - op if { @ link WeldStartService # start ( StartContext ) } completes normally and the shutdown is performed in
 * { @ link WeldStartService # stop ( org . jboss . msc . service . StopContext ) } . */
public synchronized void stop ( final StopContext context ) { } }

implementation:
weldBootstrapServiceConsumer . accept ( null ) ; if ( started ) { // WeldStartService # stop ( ) not completed - attempt to perform the container cleanup
final Container container = Container . instance ( deploymentName ) ; if ( container != null && ! ContainerState . SHUTDOWN . equals ( container . getState ( ) ) ) { final ExecutorService executorService = serverExecutorSupplier . get ( ) ; final Runnable task = new Runnable ( ) { @ Override public void run ( ) { WeldLogger . DEPLOYMENT_LOGGER . debugf ( "Weld container cleanup for deployment %s" , deploymentName ) ; ClassLoader oldTccl = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( deployment . getModule ( ) . getClassLoader ( ) ) ; WeldProvider . containerShutDown ( container ) ; container . setState ( ContainerState . SHUTDOWN ) ; container . cleanup ( ) ; setStarted ( false ) ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( oldTccl ) ; ModuleGroupSingletonProvider . removeClassLoader ( deployment . getModule ( ) . getClassLoader ( ) ) ; context . complete ( ) ; } } } ; try { executorService . execute ( task ) ; } catch ( RejectedExecutionException e ) { task . run ( ) ; } finally { context . asynchronous ( ) ; } } }


signature:
public class WeldBootstrapService { /** * Gets the { @ link BeanManager } for a given bean deployment archive id .
 * @ throws IllegalStateException if the container is not running
 * @ throws IllegalArgumentException if the bean deployment archive id is not found */
public BeanManagerImpl getBeanManager ( String beanArchiveId ) { } }

implementation: if ( ! started ) { throw WeldLogger . ROOT_LOGGER . notStarted ( "WeldContainer" ) ; } BeanDeploymentArchive beanDeploymentArchive = beanDeploymentArchives . get ( beanArchiveId ) ; if ( beanDeploymentArchive == null ) { throw WeldLogger . ROOT_LOGGER . beanDeploymentNotFound ( beanArchiveId ) ; } return bootstrap . getManager ( beanDeploymentArchive ) ;


signature:
public class WeldBootstrapService { /** * Adds a { @ link Service } to the deployment . This method must not be called after the container has started */
public < T extends org . jboss . weld . bootstrap . api . Service > void addWeldService ( Class < T > type , T service ) { } }

implementation: deployment . addWeldService ( type , service ) ;


signature:
public class WSEndpointConfigMapping { /** * Registers endpoint and its config .
 * @ param endpointClass WS endpoint
 * @ param config Config with endpoint */
public void registerEndpointConfig ( final String endpointClass , final EndpointConfig config ) { } }

implementation: if ( ( endpointClass == null ) || ( config == null ) ) { throw new IllegalArgumentException ( ) ; } endpointConfigMap . put ( endpointClass , config ) ;


signature:
public class MessageDrivenComponentDescription { /** * Adds an interceptor to invoke the { @ link MessageDrivenBean # setMessageDrivenContext ( javax . ejb . MessageDrivenContext ) }
 * if the MDB implements the { @ link MessageDrivenBean } interface */
private void addSetMessageDrivenContextMethodInvocationInterceptor ( ) { } }

implementation:
// add the setMessageDrivenContext ( MessageDrivenContext ) method invocation interceptor for MDB
// implementing the javax . ejb . MessageDrivenBean interface
this . getConfigurators ( ) . add ( new ComponentConfigurator ( ) { @ Override public void configure ( DeploymentPhaseContext context , ComponentDescription description , ComponentConfiguration configuration ) throws DeploymentUnitProcessingException { if ( MessageDrivenBean . class . isAssignableFrom ( configuration . getComponentClass ( ) ) ) { configuration . addPostConstructInterceptor ( new ImmediateInterceptorFactory ( MessageDrivenBeanSetMessageDrivenContextInterceptor . INSTANCE ) , InterceptorOrder . ComponentPostConstruct . EJB_SET_CONTEXT_METHOD_INVOCATION_INTERCEPTOR ) ; } } } ) ;


signature:
public class EESecurityExtension { /** * { @ inheritDoc } */
@ Override public void initializeParsers ( final ExtensionParsingContext context ) { } }

implementation: context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , EESecurityExtension . NAMESPACE , new Supplier < XMLElementReader < List < ModelNode > > > ( ) { @ Override public XMLElementReader < List < ModelNode > > get ( ) { return parser ; } } ) ;


signature:
public class TimerTask { /** * Invokes the timeout method through the { @ link org . jboss . as . ejb3 . timerservice . spi . TimedObjectInvoker } corresponding
 * to the { @ link org . jboss . as . ejb3 . timerservice . TimerImpl } to which this { @ link TimerTask } belongs .
 * This method also sets other attributes on the { @ link org . jboss . as . ejb3 . timerservice . TimerImpl } including the
 * next timeout of the timer and the timer state .
 * Additionally , for calendar timers , this method even schedules the next timeout timer task
 * before calling the timeout method for the current timeout . */
@ Override public void run ( ) { } }

implementation:
ClassLoader old = WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( getClass ( ) ) ; try { final TimerImpl timer = timerService . getTimer ( timerId ) ; try { if ( cancelled ) { EJB3_TIMER_LOGGER . debugf ( "Timer task was cancelled for %s" , timer ) ; return ; } Date now = new Date ( ) ; EJB3_TIMER_LOGGER . debugf ( "Timer task invoked at: %s for timer %s" , now , timer ) ; // we lock the timer for this check , because if a cancel is in progress or a running timeout is about to finish
// and try to update the timer state after finish the inTimeout method ,
// we do not want to do the isActive check , but wait for the other transaction to finish
// one way or another
timer . lock ( ) ; try { // If a retry thread is in progress , we don ' t want to allow another
// interval to execute until the retry is complete . See JIRA - 1926.
if ( timer . isInRetry ( ) ) { EJB3_TIMER_LOGGER . skipInvokeTimeoutDuringRetry ( timer , now ) ; // compute the next timeout , See JIRA AS7-2995.
timer . setNextTimeout ( calculateNextTimeout ( timer ) ) ; timerService . persistTimer ( timer , false ) ; scheduleTimeoutIfRequired ( timer ) ; return ; } // Check whether the timer is running local
// If the recurring timer running longer than the interval is , we don ' t want to allow another
// execution until it is complete . See JIRA AS7-3119
if ( timer . getState ( ) == TimerState . IN_TIMEOUT || timer . getState ( ) == TimerState . RETRY_TIMEOUT ) { EJB3_TIMER_LOGGER . skipOverlappingInvokeTimeout ( timer , now ) ; if ( EJB3_TIMER_LOGGER . isDebugEnabled ( ) ) { // WFLY - 10542 log thread stack trace which is processing timer task in debug level to diagnose timer overlap
Thread otherThread = timer . getExecutingThread ( ) ; // can be null for clustered timers if the timer is executing on another node .
if ( otherThread != null ) { final StringBuilder debugMsg = new StringBuilder ( ) . append ( "Thread: " ) . append ( otherThread . getName ( ) ) . append ( " Id: " ) . append ( otherThread . getId ( ) ) . append ( " of group " ) . append ( otherThread . getThreadGroup ( ) ) . append ( " is in state: " ) . append ( otherThread . getState ( ) ) ; for ( StackTraceElement ste : otherThread . getStackTrace ( ) ) { debugMsg . append ( System . lineSeparator ( ) ) . append ( ste . toString ( ) ) ; } EJB3_TIMER_LOGGER . debugf ( debugMsg . toString ( ) ) ; } } Date newD = this . calculateNextTimeout ( timer ) ; timer . setNextTimeout ( newD ) ; timerService . persistTimer ( timer , false ) ; scheduleTimeoutIfRequired ( timer ) ; return ; } // Check whether we want to run the timer
if ( ! timerService . shouldRun ( timer ) ) { EJB3_TIMER_LOGGER . debugf ( "Skipping execution of timer for %s as it is being run on another node or the execution is suppressed by configuration" , timer . getTimedObjectId ( ) ) ; timer . setNextTimeout ( calculateNextTimeout ( timer ) ) ; scheduleTimeoutIfRequired ( timer ) ; return ; } if ( ! timer . isActive ( ) ) { EJB3_TIMER_LOGGER . debug ( "Timer is not active, skipping this scheduled execution at: " + now + "for " + timer ) ; return ; } // set the current date as the " previous run " of the timer .
timer . setPreviousRun ( new Date ( ) ) ; Date nextTimeout = this . calculateNextTimeout ( timer ) ; timer . setNextTimeout ( nextTimeout ) ; // change the state to mark it as in timeout method
timer . setTimerState ( TimerState . IN_TIMEOUT , Thread . currentThread ( ) ) ; // persist changes
timerService . persistTimer ( timer , false ) ; } finally { timer . unlock ( ) ; } try { // invoke timeout
this . callTimeout ( timer ) ; } catch ( Exception e ) { EJB3_TIMER_LOGGER . errorInvokeTimeout ( timer , e ) ; try { EJB3_TIMER_LOGGER . timerRetried ( timer ) ; retryTimeout ( timer ) ; } catch ( Exception retryException ) { // that ' s it , we can ' t do anything more . Let ' s just log the exception
// and return
EJB3_TIMER_LOGGER . errorDuringRetryTimeout ( timer , retryException ) ; } } finally { this . postTimeoutProcessing ( timer ) ; } } catch ( Exception e ) { EJB3_TIMER_LOGGER . exceptionRunningTimerTask ( timer , timedObjectId , e ) ; } } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( old ) ; }


signature:
public class TimerTask { /** * After a timeout failed the timer need to retried .
 * The method must lock the timer for state check and update but not during callTimeout run .
 * @ param timer timer to retry and state updates
 * @ throws Exception */
protected void retryTimeout ( TimerImpl timer ) throws Exception { } }

implementation: boolean callTimeout = false ; timer . lock ( ) ; try { if ( timer . isActive ( ) ) { EJB3_TIMER_LOGGER . retryingTimeout ( timer ) ; timer . setTimerState ( TimerState . RETRY_TIMEOUT , Thread . currentThread ( ) ) ; timerService . persistTimer ( timer , false ) ; callTimeout = true ; } else { EJB3_TIMER_LOGGER . timerNotActive ( timer ) ; } } finally { timer . unlock ( ) ; } if ( callTimeout ) { this . callTimeout ( timer ) ; }


signature:
public class TimerTask { /** * After running the timer calculate the new state or expire the timer and persist it if changed .
 * The method must lock the timer for state check and updates if overridden .
 * @ param timer timer to post processing and persist */
protected void postTimeoutProcessing ( TimerImpl timer ) throws InterruptedException { } }

implementation: timer . lock ( ) ; try { TimerState timerState = timer . getState ( ) ; if ( timerState != TimerState . CANCELED && timerState != TimerState . EXPIRED ) { if ( timer . getInterval ( ) == 0 ) { timerService . expireTimer ( timer ) ; } else { timer . setTimerState ( TimerState . ACTIVE , null ) ; } timerService . persistTimer ( timer , false ) ; } } finally { timer . unlock ( ) ; }


signature:
public class JSR77ManagementExtension { /** * { @ inheritDoc } */
@ Override public void initialize ( ExtensionContext context ) { } }

implementation:
final SubsystemRegistration subsystem = context . registerSubsystem ( SUBSYSTEM_NAME , CURRENT_MODEL_VERSION ) ; // Register the root subsystem resource .
final ManagementResourceRegistration rootResource = subsystem . registerSubsystemModel ( new JSR77ManagementRootResource ( context . getProcessType ( ) == ProcessType . APPLICATION_CLIENT ) ) ; // Mandatory describe operation
rootResource . registerOperationHandler ( GenericSubsystemDescribeHandler . DEFINITION , GenericSubsystemDescribeHandler . INSTANCE ) ; subsystem . registerXMLElementWriter ( parser ) ;


signature:
public class SecurityActions { /** * Get the declared methods
 * @ param c The class
 * @ return The methods */
static Method [ ] getDeclaredMethods ( final Class < ? > c ) { } }

implementation: if ( System . getSecurityManager ( ) == null ) return c . getDeclaredMethods ( ) ; return AccessController . doPrivileged ( new PrivilegedAction < Method [ ] > ( ) { public Method [ ] run ( ) { return c . getDeclaredMethods ( ) ; } } ) ;


signature:
public class SecurityActions { /** * Get the declared fields
 * @ param c The class
 * @ return The fields */
static Field [ ] getDeclaredFields ( final Class < ? > c ) { } }

implementation: if ( System . getSecurityManager ( ) == null ) return c . getDeclaredFields ( ) ; return AccessController . doPrivileged ( new PrivilegedAction < Field [ ] > ( ) { public Field [ ] run ( ) { return c . getDeclaredFields ( ) ; } } ) ;


signature:
public class SecurityActions { /** * Set accessibleo
 * @ param ao The object */
static void setAccessible ( final AccessibleObject ao ) { } }

implementation: if ( System . getSecurityManager ( ) == null ) ao . setAccessible ( true ) ; AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { ao . setAccessible ( true ) ; return null ; } } ) ;


signature:
public class SecurityActions { /** * Get the constructor
 * @ param c The class
 * @ param params The parameters
 * @ return The constructor
 * @ throws NoSuchMethodException If a matching method is not found . */
static Constructor < ? > getConstructor ( final Class < ? > c , final Class < ? > ... params ) throws NoSuchMethodException { } }

implementation: if ( System . getSecurityManager ( ) == null ) return c . getConstructor ( params ) ; Constructor < ? > result = AccessController . doPrivileged ( new PrivilegedAction < Constructor < ? > > ( ) { public Constructor < ? > run ( ) { try { return c . getConstructor ( params ) ; } catch ( NoSuchMethodException e ) { return null ; } } } ) ; if ( result != null ) return result ; throw new NoSuchMethodException ( ) ;


signature:
public class SecurityActions { /** * Get the method
 * @ param c The class
 * @ param name The name
 * @ param params The parameters
 * @ return The method
 * @ throws NoSuchMethodException If a matching method is not found . */
static Method getMethod ( final Class < ? > c , final String name , final Class < ? > ... params ) throws NoSuchMethodException { } }

implementation: if ( System . getSecurityManager ( ) == null ) return c . getMethod ( name , params ) ; Method result = AccessController . doPrivileged ( new PrivilegedAction < Method > ( ) { public Method run ( ) { try { return c . getMethod ( name , params ) ; } catch ( NoSuchMethodException e ) { return null ; } } } ) ; if ( result != null ) return result ; throw new NoSuchMethodException ( ) ;


signature:
public class MigrateOperation { /** * In domain mode , the subsystem are under / profile = XXX .
 * This method fixes the address by prepending the addresses ( that start with / subsystem ) with the current
 * operation parent so that is works both in standalone ( parent = EMPTY _ ADDRESS ) and domain mode
 * ( parent = / profile = XXX ) */
private void fixAddressesForDomainMode ( PathAddress parentAddress , Map < PathAddress , ModelNode > migrationOperations ) { } }

implementation:
// in standalone mode , do nothing
if ( parentAddress . size ( ) == 0 ) { return ; } // use a linked hash map to preserve operations order
Map < PathAddress , ModelNode > fixedMigrationOperations = new LinkedHashMap < > ( migrationOperations ) ; migrationOperations . clear ( ) ; for ( Map . Entry < PathAddress , ModelNode > entry : fixedMigrationOperations . entrySet ( ) ) { PathAddress fixedAddress = parentAddress . append ( entry . getKey ( ) ) ; entry . getValue ( ) . get ( ADDRESS ) . set ( fixedAddress . toModelNode ( ) ) ; migrationOperations . put ( fixedAddress , entry . getValue ( ) ) ; }


signature:
public class MigrateOperation { /** * It ' s possible that the extension is already present . In that case , this method does nothing . */
private void addMessagingActiveMQExtension ( OperationContext context , Map < PathAddress , ModelNode > migrationOperations , boolean describe ) { } }

implementation:
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 ) ; }


signature:
public class MigrateOperation { /** * Check if the name of the parameter is allowed for the given resourceType . */
private boolean parameterIsAllowed ( String name , String resourceType ) { } }

implementation:
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 ; }


signature:
public class MigrateOperation { /** * For generic acceptor and connectors , migrate their factory - class attribute
 * if they are using the default Netty ones . */
private void migrateGenericTransport ( ModelNode addOperation ) { } }

implementation: 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 ) ;


signature:
public class MigrateOperation { /** * Discard from a node and set it to a new node if the attribute is defined . Use the { @ code newAttributeName } as the messaging - activemq may
 * named differently its corresponding attribute . */
private void setAndDiscard ( ModelNode setNode , ModelNode discardNode , AttributeDefinition legacyAttributeDefinition , String newAttributeName ) { } }

implementation: ModelNode attribute = discardNode . get ( legacyAttributeDefinition . getName ( ) ) ; if ( attribute . isDefined ( ) ) { setNode . get ( newAttributeName ) . set ( attribute ) ; discardNode . remove ( legacyAttributeDefinition . getName ( ) ) ; }


signature:
public class EESubsystemXmlPersister { /** * { @ inheritDoc } */
@ Override public void writeContent ( XMLExtendedStreamWriter writer , SubsystemMarshallingContext context ) throws XMLStreamException { } }

implementation: 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 ( ) ;


signature:
public class SessionBeanXmlDescriptorProcessor { /** * 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 }
 * @ param sessionBean The session bean metadata
 * @ param phaseContext
 * @ throws DeploymentUnitProcessingException */
@ Override protected void processBeanMetaData ( final SessionBeanMetaData sessionBean , final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { } }

implementation:
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 ) ; }


signature:
public class PersistenceBeginInstallProcessor { /** * { @ inheritDoc } */
public void deploy ( final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { } }

implementation:
// 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 ) ;


signature:
public class CancellationFlag { /** * Attempt to cancel the corresponding invocation .
 * @ param setFlag { @ code true } to set the EJB context cancellation flag ( or equivalent ) , { @ code false } otherwise
 * @ return { @ code true } if the invocation was definitely cancelled , or { @ code false } if it was not cancelled or it could not be determined if it was cancelled */
public boolean cancel ( boolean setFlag ) { } }

implementation:
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 ;


signature:
public class CancellationFlag { /** * Attempt to determine whether the invocation should proceed or whether it should be cancelled . This method should only
 * be called once per flag instance .
 * @ return { @ code true } if the invocation should proceed , or { @ code false } if it was cancelled */
public boolean runIfNotCancelled ( ) { } }

implementation: 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 ;


signature:
public class OPropertyEmbedded { /** * Change the type . It checks for compatibility between the change of type .
 * @ param iType */
protected void setTypeInternal ( final OType iType ) { } }

implementation:
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 ( ) ; }


signature:
public class ODurablePage { /** * DO NOT DELETE THIS METHOD IT IS USED IN ENTERPRISE STORAGE
 * Copies content of page into passed in byte array .
 * @ param buffer Buffer from which data will be copied
 * @ param data Byte array to which data will be copied
 * @ param offset Offset of data inside page
 * @ param length Length of data to be copied */
@ SuppressWarnings ( "unused" ) public static void getPageData ( final ByteBuffer buffer , final byte [ ] data , final int offset , final int length ) { } }

implementation: buffer . position ( 0 ) ; buffer . get ( data , offset , length ) ;


signature:
public class ODurablePage { /** * DO NOT DELETE THIS METHOD IT IS USED IN ENTERPRISE STORAGE
 * Get value of LSN from the passed in offset in byte array .
 * @ param offset Offset inside of byte array from which LSN value will be read .
 * @ param data Byte array from which LSN value will be read . */
@ SuppressWarnings ( "unused" ) public static OLogSequenceNumber getLogSequenceNumber ( final int offset , final byte [ ] data ) { } }

implementation: 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 ) ;


signature:
public class OGremlinHelper { /** * 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 ) */
@ SuppressWarnings ( { } }

implementation:
"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 ; } } }


signature:
public class OGraphSONReader { /** * Input the JSON stream data into the graph . More control over how data is streamed is provided by this method .
 * @ param filename
 * name of a file of JSON data
 * @ param bufferSize
 * the amount of elements to hold in memory before committing a transactions ( only valid for TransactionalGraphs )
 * @ throws IOException
 * thrown when the JSON data is not correctly formatted */
public void inputGraph ( final String filename , int bufferSize , final Set < String > edgePropertyKeys , final Set < String > vertexPropertyKeys ) throws IOException { } }

implementation: 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 ( ) ; }


signature:
public class OGraphSONReader { /** * Input the JSON stream data into the graph . More control over how data is streamed is provided by this method .
 * @ param jsonInputStream
 * an InputStream of JSON data
 * @ param bufferSize
 * the amount of elements to hold in memory before committing a transactions ( only valid for TransactionalGraphs )
 * @ throws IOException
 * thrown when the JSON data is not correctly formatted */
public void inputGraph ( final InputStream jsonInputStream , int bufferSize , final Set < String > edgePropertyKeys , final Set < String > vertexPropertyKeys ) throws IOException { } }

implementation:
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 ( ) ;


signature:
public class OIndexDefinitionFactory { /** * Creates an instance of { @ link OIndexDefinition } for automatic index .
 * @ param oClass class which will be indexed
 * @ param fieldNames list of properties which will be indexed . Format should be ' < property > [ by key | value ] ' , use ' by key ' or ' by
 * value ' to describe how to index maps . By default maps indexed by key
 * @ param types types of indexed properties
 * @ param collates
 * @ param indexKind
 * @ param algorithm
 * @ return index definition instance */
public static OIndexDefinition createIndexDefinition ( final OClass oClass , final List < String > fieldNames , final List < OType > types , List < OCollate > collates , String indexKind , String algorithm ) { } }

implementation: 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 ) ;


signature:
public class OIndexDefinitionFactory { /** * Extract field name from ' < property > [ by key | value ] ' field format .
 * @ param fieldDefinition definition of field
 * @ return extracted property name */
public static String extractFieldName ( final String fieldDefinition ) { } }

implementation: 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 ( ) ;


signature:
public class OBaseExpression { /** * tests if current expression is an indexed funciton AND that function can also be executed without using the index
 * @ param target the query target
 * @ param context the execution context
 * @ param operator
 * @ param right
 * @ return true if current expression is an indexed funciton AND that function can also be executed without using the index , false
 * otherwise */
public boolean canExecuteIndexedFunctionWithoutIndex ( OFromClause target , OCommandContext context , OBinaryCompareOperator operator , Object right ) { } }

implementation: if ( this . identifier == null ) { return false ; } return identifier . canExecuteIndexedFunctionWithoutIndex ( target , context , operator , right ) ;


signature:
public class OWhereClause { /** * estimates how many items of this class will be returned applying this filter
 * @ param oClass
 * @ return an estimation of the number of records of this class returned applying this filter , 0 if and only if sure that no
 * records are returned */
public long estimate ( OClass oClass , long threshold , OCommandContext ctx ) { } }

implementation: 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 ) ;


signature:
public class OReflectionHelper { /** * Recursive method used to find all classes in a given directory and subdirs .
 * @ param iDirectory
 * The base directory
 * @ param iPackageName
 * The package name for classes found inside the base directory
 * @ return The classes
 * @ throws ClassNotFoundException */
private static List < Class < ? > > findClasses ( final File iDirectory , String iPackageName , ClassLoader iClassLoader ) throws ClassNotFoundException { } }

implementation: 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 ;


signature:
public class OReflectionHelper { /** * Filters discovered classes to see if they implement a given interface .
 * @ param thePackage
 * @ param theInterface
 * @ param iClassLoader
 * @ return The list of classes that implements the requested interface */
public static List < Class < ? > > getClassessOfInterface ( String thePackage , Class < ? > theInterface , final ClassLoader iClassLoader ) { } }

implementation: 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 ;


signature:
public class OReflectionHelper { /** * Returns the declared generic types of a class .
 * @ param iClass
 * Class to examine
 * @ return The array of Type if any , otherwise null */
public static Type [ ] getGenericTypes ( final Class < ? > iClass ) { } }

implementation: 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 ;


signature:
public class OReflectionHelper { /** * Returns the generic class of multi - value objects .
 * @ param p
 * Field to examine
 * @ return The Class < ? > of generic type if any , otherwise null */
public static Class < ? > getGenericMultivalueType ( final Field p ) { } }

implementation: 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 ;


signature:
public class OReflectionHelper { /** * Checks if a class is a Java type : Map , Collection , arrays , Number ( extensions and primitives ) , String , Boolean . .
 * @ param clazz
 * Class < ? > to examine
 * @ return true if clazz is Java type , false otherwise */
public static boolean isJavaType ( Class < ? > clazz ) { } }

implementation: 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 ;


signature:
public class OSQLMethodRuntime { /** * Execute a method .
 * @ param iCurrentRecord
 * Current record
 * @ param iCurrentResult
 * TODO
 * @ param iContext
 * @ return */
public Object execute ( final Object iThis , final OIdentifiable iCurrentRecord , final Object iCurrentResult , final OCommandContext iContext ) { } }

implementation:
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 ) ;


signature:
public class OQueryOperatorContainsText { /** * This is executed on non - indexed fields . */
@ Override public Object evaluateRecord ( final OIdentifiable iRecord , ODocument iCurrentResult , final OSQLFilterCondition iCondition , final Object iLeft , final Object iRight , OCommandContext iContext , final ODocumentSerializer serializer ) { } }

implementation: if ( iLeft == null || iRight == null ) return false ; return iLeft . toString ( ) . indexOf ( iRight . toString ( ) ) > - 1 ;


signature:
public class ODocumentSimpleFieldHandlingStrategy { /** * Derives the type of a field in a document .
 * @ param iRecord
 * @ param fieldName
 * @ param requestedFieldType
 * @ return derived field type */
protected OType deriveFieldType ( ODocument iRecord , String fieldName , OType requestedFieldType ) { } }

implementation:
// 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 ) ;


signature:
public class OCommandExecutorSQLRevoke { /** * Execute the command . */
public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation: 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 ;


signature:
public class OLocalRecordCache { /** * Pushes record to cache . Identifier of record used as access key
 * @ param record
 * record that should be cached */
public void updateRecord ( final ORecord record ) { } }

implementation: if ( record . getIdentity ( ) . getClusterId ( ) != excludedCluster && record . getIdentity ( ) . isValid ( ) && ! record . isDirty ( ) && ! ORecordVersionHelper . isTombstone ( record . getVersion ( ) ) ) { if ( underlying . get ( record . getIdentity ( ) ) != record ) underlying . put ( record ) ; }


signature:
public class OLocalRecordCache { /** * Looks up for record in cache by it ' s identifier . Optionally look up in secondary cache and update primary with found record
 * @ param rid
 * unique identifier of record
 * @ return record stored in cache if any , otherwise - { @ code null } */
public ORecord findRecord ( final ORID rid ) { } }

implementation: 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 ;


signature:
public class OCommandExecutorSQLDropIndex { /** * Execute the REMOVE INDEX . */
public Object execute ( final Map < Object , Object > iArgs ) { } }

implementation: 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 ;


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

implementation: init ( object , hints ) ; buffer . put ( binarySerializer . getId ( ) ) ; binarySerializer . serializeInByteBufferObject ( object , buffer ) ;


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

implementation: final byte typeId = buffer . get ( ) ; init ( typeId ) ; return ( T ) binarySerializer . deserializeFromByteBufferObject ( buffer ) ;


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

implementation: final byte serializerId = buffer . get ( ) ; init ( serializerId ) ; return OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE + binarySerializer . getObjectSizeInByteBuffer ( buffer ) ;


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

implementation: final byte typeId = walChanges . getByteValue ( buffer , offset ++ ) ; init ( typeId ) ; return ( T ) binarySerializer . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ;


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

implementation: return OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE + binarySerializer . getObjectSizeInByteBuffer ( buffer , walChanges , OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE + offset ) ;


signature:
public class OGraphBatchInsert { /** * Creates the database ( if it does not exist ) and initializes batch operations . Call this once , before starting to create
 * vertices and edges . */
public void begin ( ) { } }

implementation:
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 ) ; } }


signature:
public class OGraphBatchInsert { /** * Creates a new edge between two vertices . If vertices do not exist , they will be created
 * @ param from
 * id of the vertex that is starting point of the edge
 * @ param to
 * id of the vertex that is end point of the edge */
public void createEdge ( final Long from , final Long to , Map < String , Object > properties ) { } }

implementation: 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 ) ; }


signature:
public class OSelectExecutionPlanner { /** * 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 .
 * @ param info
 * @ param ctx */
private void calculateShardingStrategy ( QueryPlanningInfo info , OCommandContext ctx ) { } }

implementation:
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 ) ;


signature:
public class OSelectExecutionPlanner { /** * 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 .
 * @ param clusterMap
 * @ param queryClusters
 * @ return a map that has node names as a key and clusters ( data files ) for each node as a value */
private Map < String , Set < String > > getMinimalSetOfNodesForShardedQuery ( String localNode , Map < String , Set < String > > clusterMap , Set < String > queryClusters ) { } }

implementation:
// 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 ;


signature:
public class OSelectExecutionPlanner { /** * @ param clusterMap the cluster map for current sharding configuration
 * @ param queryClusters the clusters that are target of the query
 * @ return */
private Set < String > getServersThatHasAllClusters ( Map < String , Set < String > > clusterMap , Set < String > queryClusters ) { } }

implementation: 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 ;


signature:
public class OSelectExecutionPlanner { /** * tries to calculate which clusters will be impacted by this query
 * @ param info
 * @ param ctx
 * @ return a set of cluster names this query will fetch from */
private Set < String > calculateTargetClusters ( QueryPlanningInfo info , OCommandContext ctx ) { } }

implementation: 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 ;


signature:
public class OSelectExecutionPlanner { /** * for backward compatibility , translate " distinct ( foo ) " to " DISTINCT foo " . This method modifies the projection itself .
 * @ param projection the projection */
protected static OProjection translateDistinct ( OProjection projection ) { } }

implementation: 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 ;


signature:
public class OSelectExecutionPlanner { /** * 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 "
 * @ param item the projection
 * @ return */
private static boolean isDistinct ( OProjectionItem item ) { } }

implementation: 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" ) ;


signature:
public class OSelectExecutionPlanner { /** * returns true if the query is minimal , ie . no WHERE condition , no SKIP / LIMIT , no UNWIND , no GROUP / ORDER BY , no LET
 * @ return */
private boolean isMinimalQuery ( QueryPlanningInfo info ) { } }

implementation: 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 ;


signature:
public class OSelectExecutionPlanner { /** * splits LET clauses in global ( executed once ) and local ( executed once per record ) */
private static void splitLet ( QueryPlanningInfo info , OCommandContext ctx ) { } }

implementation: 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 ( ) ) ; } } }


signature:
public class OSelectExecutionPlanner { /** * re - writes a list of flat AND conditions , moving left all the equality operations
 * @ param flattenedWhereClause
 * @ return */
private static List < OAndBlock > moveFlattededEqualitiesLeft ( List < OAndBlock > flattenedWhereClause ) { } }

implementation: 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 ;


signature:
public class OSelectExecutionPlanner { /** * creates additional projections for ORDER BY */
private static void addOrderByProjections ( QueryPlanningInfo info ) { } }

implementation:
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 ) ; } } }


signature:
public class OSelectExecutionPlanner { /** * 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
 * @ param allAliases existing aliases in the projection
 * @ param orderBy sorting clause
 * @ return a list of additional projections to add to the existing projections to allow ORDER BY calculation ( empty if nothing has
 * to be added ) . */
private static List < OProjectionItem > calculateAdditionalOrderByProjections ( Set < String > allAliases , OOrderBy orderBy ) { } }

implementation: 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 ;


signature:
public class OSelectExecutionPlanner { /** * splits projections in three parts ( pre - aggregate , aggregate and final ) to efficiently manage aggregations */
private static void splitProjectionsForGroupBy ( QueryPlanningInfo info , OCommandContext ctx ) { } }

implementation:
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 ) ; }