/** * The main method that creates a new provisioner instance. * * @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance to register the provisioner with * @param \AppserverIo\Appserver\Core\Api\Node\ProvisionerNodeInterface $provisionerConfiguration The provisioner configuration * * @return void */ public static function visit(ApplicationInterface $application, ProvisionerNodeInterface $provisionerConfiguration) { // load the initial context $initialContext = $application->getInitialContext(); // initialize the bean manager $provisioner = new StandardProvisioner($initialContext, $provisionerConfiguration); // attach the instance $application->addProvisioner($provisioner, $provisionerConfiguration); }
/** * Creates a new entity manager instance based on the passed configuration. * * @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance to create the entity manager for * @param \AppserverIo\Appserver\Core\Api\Node\PersistenceUnitNodeInterface $persistenceUnitNode The datasource configuration * * @return object The entity manager instance */ public static function factory(ApplicationInterface $application, PersistenceUnitNodeInterface $persistenceUnitNode) { // register additional annotation libraries foreach ($persistenceUnitNode->getAnnotationRegistries() as $annotationRegistry) { AnnotationRegistry::registerAutoloadNamespace($annotationRegistry->getNamespace(), $annotationRegistry->getDirectoriesAsArray($application->getWebappPath())); } // globally ignore configured annotations to ignore foreach ($persistenceUnitNode->getIgnoredAnnotations() as $ignoredAnnotation) { AnnotationReader::addGlobalIgnoredName($ignoredAnnotation->getNodeValue()->__toString()); } // load the metadata configuration $metadataConfiguration = $persistenceUnitNode->getMetadataConfiguration(); // prepare the setup properties $absolutePaths = $metadataConfiguration->getDirectoriesAsArray($application->getWebappPath()); $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_PROXY_DIR); $isDevMode = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_IS_DEV_MODE); $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_USE_SIMPLE_ANNOTATION_READER); // load the factory method from the available mappings $factoryMethod = EntityManagerFactory::$metadataMapping[$metadataConfiguration->getType()]; // create the database configuration and initialize the entity manager $configuration = Setup::$factoryMethod($absolutePaths, $isDevMode, $proxyDir, null, $useSimpleAnnotationReader); // load the datasource node $datasourceNode = null; foreach ($application->getInitialContext()->getSystemConfiguration()->getDatasources() as $datasourceNode) { if ($datasourceNode->getName() === $persistenceUnitNode->getDatasource()->getName()) { break; } } // throw a exception if the configured datasource is NOT available if ($datasourceNode == null) { throw new \Exception(sprintf('Can\'t find a datasource node for persistence unit %s', $persistenceUnitNode->getName())); } // load the database node $databaseNode = $datasourceNode->getDatabase(); // throw an exception if the configured database is NOT available if ($databaseNode == null) { throw new \Exception(sprintf('Can\'t find database node for persistence unit %s', $persistenceUnitNode->getName())); } // load the driver node $driverNode = $databaseNode->getDriver(); // throw an exception if the configured driver is NOT available if ($driverNode == null) { throw new \Exception(sprintf('Can\'t find driver node for persistence unit %s', $persistenceUnitNode->getName())); } // initialize and return a entity manager decorator instance return new DoctrineEntityManagerDecorator(EntityManager::create(ConnectionUtil::get($application)->fromDatabaseNode($databaseNode), $configuration)); }
/** * The main method that creates new instances in a separate context. * * @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance to register the class loader with * @param \AppserverIo\Appserver\Core\Api\Node\ManagerNodeInterface $managerConfiguration The manager configuration * * @return void */ public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // load the registered loggers $loggers = $application->getInitialContext()->getLoggers(); // initialize the bean locator $beanLocator = new BeanLocator(); // create the initial context instance $initialContext = new NamingContext(); $initialContext->injectApplication($application); // initialize the stackable for the data, the stateful + singleton session beans and the naming directory $data = new StackableStorage(); $instances = new GenericStackable(); $statefulSessionBeans = new StackableStorage(); $singletonSessionBeans = new StackableStorage(); // initialize the default settings for the stateful session beans $statefulSessionBeanSettings = new DefaultStatefulSessionBeanSettings(); $statefulSessionBeanSettings->mergeWithParams($managerConfiguration->getParamsAsArray()); // we need a factory instance for the stateful session bean instances $statefulSessionBeanMapFactory = new StatefulSessionBeanMapFactory($statefulSessionBeans); $statefulSessionBeanMapFactory->injectLoggers($loggers); $statefulSessionBeanMapFactory->start(); // create an instance of the object factory $objectFactory = new GenericObjectFactory(); $objectFactory->injectInstances($instances); $objectFactory->injectApplication($application); $objectFactory->start(); // add a garbage collector and timer service workers for each application $garbageCollector = new StandardGarbageCollector(); $garbageCollector->injectApplication($application); $garbageCollector->start(); // initialize the bean manager $beanManager = new BeanManager(); $beanManager->injectData($data); $beanManager->injectApplication($application); $beanManager->injectResourceLocator($beanLocator); $beanManager->injectObjectFactory($objectFactory); $beanManager->injectInitialContext($initialContext); $beanManager->injectGarbageCollector($garbageCollector); $beanManager->injectStatefulSessionBeans($statefulSessionBeans); $beanManager->injectSingletonSessionBeans($singletonSessionBeans); $beanManager->injectDirectories($managerConfiguration->getDirectories()); $beanManager->injectStatefulSessionBeanSettings($statefulSessionBeanSettings); $beanManager->injectStatefulSessionBeanMapFactory($statefulSessionBeanMapFactory); // attach the instance $application->addManager($beanManager, $managerConfiguration); }
/** * The main method that creates new instances in a separate context. * * @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance to register the class loader with * @param \AppserverIo\Appserver\Core\Api\Node\ManagerNodeInterface $managerConfiguration The manager configuration * * @return void */ public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // load the registered loggers $loggers = $application->getInitialContext()->getLoggers(); // initialize the session pool $sessions = new StackableStorage(); $checksums = new StackableStorage(); $sessionPool = new StackableStorage(); $sessionSettings = new DefaultSessionSettings(); $sessionMarshaller = new StandardSessionMarshaller(); // we need a session factory instance $sessionFactory = new SessionFactory($sessionPool); $sessionFactory->injectLoggers($loggers); $sessionFactory->start(); // we need a persistence manager and garbage collector $persistenceManager = new FilesystemPersistenceManager(); $persistenceManager->injectLoggers($loggers); $persistenceManager->injectSessions($sessions); $persistenceManager->injectChecksums($checksums); $persistenceManager->injectSessionSettings($sessionSettings); $persistenceManager->injectSessionMarshaller($sessionMarshaller); $persistenceManager->injectSessionFactory($sessionFactory); $persistenceManager->injectUser($application->getUser()); $persistenceManager->injectGroup($application->getGroup()); $persistenceManager->injectUmask($application->getUmask()); $persistenceManager->start(); // we need a garbage collector $garbageCollector = new StandardGarbageCollector(); $garbageCollector->injectLoggers($loggers); $garbageCollector->injectSessions($sessions); $garbageCollector->injectSessionFactory($sessionFactory); $garbageCollector->injectSessionSettings($sessionSettings); $garbageCollector->start(); // and finally we need the session manager instance $sessionManager = new StandardSessionManager(); $sessionManager->injectSessions($sessions); $sessionManager->injectSessionFactory($sessionFactory); $sessionManager->injectSessionSettings($sessionSettings); $sessionManager->injectGarbageCollector($garbageCollector); $sessionManager->injectPersistenceManager($persistenceManager); // attach the instance $application->addManager($sessionManager, $managerConfiguration); }
/** * Registers aspects written within source files which we might encounter * * @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance * * @return void */ protected function registerAspectClasses(ApplicationInterface $application) { // check directory for PHP files with classes we want to register /** @var \AppserverIo\Appserver\Core\Api\DeploymentService $service */ $service = $application->newService('AppserverIo\\Appserver\\Core\\Api\\DeploymentService'); // iterate over the directories and try to find aspects $aspectDirectories = $service->globDir($this->getWebappPath() . DIRECTORY_SEPARATOR . '{WEB-INF,META-INF,common}' . DIRECTORY_SEPARATOR . 'classes', GLOB_BRACE); foreach ($aspectDirectories as $aspectDirectory) { // iterate all PHP files found in the directory foreach ($service->globDir($aspectDirectory . DIRECTORY_SEPARATOR . '*.php') as $phpFile) { try { // cut off the META-INF directory and replace OS specific directory separators $relativePathToPhpFile = str_replace(DIRECTORY_SEPARATOR, '\\', str_replace($aspectDirectory, '', $phpFile)); // now cut off the .php extension $className = substr($relativePathToPhpFile, 0, -4); // we need a reflection class to read the annotations $reflectionClass = $this->getReflectionClass($className); // if we found an aspect we have to register it using our aspect register class if ($reflectionClass->hasAnnotation(AspectAnnotation::ANNOTATION)) { $parser = new AspectParser($phpFile, new Config()); $this->aspectRegister->register($parser->getDefinition($reflectionClass->getShortName(), false)); } // if class can not be reflected continue with next class } catch (\Exception $e) { // log an error message $application->getInitialContext()->getSystemLogger()->error($e->__toString()); // proceed with the next class continue; } } } }
/** * Creates a new entity manager instance based on the passed configuration. * * @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance to create the entity manager for * @param \AppserverIo\Appserver\Core\Api\Node\PersistenceUnitNodeInterface $persistenceUnitNode The datasource configuration * * @return object The entity manager instance */ public static function factory(ApplicationInterface $application, PersistenceUnitNodeInterface $persistenceUnitNode) { // register additional annotation libraries foreach ($persistenceUnitNode->getAnnotationRegistries() as $annotationRegistry) { AnnotationRegistry::registerAutoloadNamespace($annotationRegistry->getNamespace(), $annotationRegistry->getDirectoriesAsArray($application->getWebappPath())); } // load the metadata configuration $metadataConfiguration = $persistenceUnitNode->getMetadataConfiguration(); // prepare the setup properties $absolutePaths = $metadataConfiguration->getDirectoriesAsArray($application->getWebappPath()); $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_PROXY_DIR); $isDevMode = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_IS_DEV_MODE); $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_USE_SIMPLE_ANNOTATION_READER); // load the factory method from the available mappings $factoryMethod = EntityManagerFactory::$metadataMapping[$metadataConfiguration->getType()]; // create the database configuration and initialize the entity manager $configuration = Setup::$factoryMethod($absolutePaths, $isDevMode, $proxyDir, null, $useSimpleAnnotationReader); // load the datasource node $datasourceNode = null; foreach ($application->getInitialContext()->getSystemConfiguration()->getDatasources() as $datasourceNode) { if ($datasourceNode->getName() === $persistenceUnitNode->getDatasource()->getName()) { break; } } // throw a exception if the configured datasource is NOT available if ($datasourceNode == null) { throw new \Exception(sprintf('Can\'t find a datasource node for persistence unit %s', $persistenceUnitNode->getName())); } // load the database node $databaseNode = $datasourceNode->getDatabase(); // throw an exception if the configured database is NOT available if ($databaseNode == null) { throw new \Exception(sprintf('Can\'t find database node for persistence unit %s', $persistenceUnitNode->getName())); } // load the driver node $driverNode = $databaseNode->getDriver(); // throw an exception if the configured driver is NOT available if ($driverNode == null) { throw new \Exception(sprintf('Can\'t find driver node for persistence unit %s', $persistenceUnitNode->getName())); } // initialize the connection parameters with the mandatory driver $connectionParameters = array('driver' => $databaseNode->getDriver()->getNodeValue()->__toString()); // initialize the path/memory to the database when we use sqlite for example if ($pathNode = $databaseNode->getPath()) { $connectionParameters['path'] = $application->getWebappPath() . DIRECTORY_SEPARATOR . $pathNode->getNodeValue()->__toString(); } elseif ($memoryNode = $databaseNode->getMemory()) { $connectionParameters['memory'] = Boolean::valueOf(new String($memoryNode->getNodeValue()->__toString()))->booleanValue(); } else { // do nothing here, because there is NO option } // add username, if specified if ($userNode = $databaseNode->getUser()) { $connectionParameters['user'] = $userNode->getNodeValue()->__toString(); } // add password, if specified if ($passwordNode = $databaseNode->getPassword()) { $connectionParameters['password'] = $passwordNode->getNodeValue()->__toString(); } // add database name if using another PDO driver than sqlite if ($databaseNameNode = $databaseNode->getDatabaseName()) { $connectionParameters['dbname'] = $databaseNameNode->getNodeValue()->__toString(); } // add database host if using another PDO driver than sqlite if ($databaseHostNode = $databaseNode->getDatabaseHost()) { $connectionParameters['host'] = $databaseHostNode->getNodeValue()->__toString(); } // add charset, if specified if ($charsetNode = $databaseNode->getCharset()) { $connectionParameters['charset'] = $charsetNode->getNodeValue()->__toString(); } // add driver options, if specified if ($driverOptionsNode = $databaseNode->getDriverOptions()) { // explode the raw options separated with a semicolon $rawOptions = explode(';', $driverOptionsNode->getNodeValue()->__toString()); // prepare the array with the driver options key/value pair (separated with a =) $options = array(); foreach ($rawOptions as $rawOption) { list($key, $value) = explode('=', $rawOption); $options[$key] = $value; } // set the driver options $connectionParameters['driverOptions'] = $options; } // add driver options, if specified if ($unixSocketNode = $databaseNode->getUnixSocket()) { $connectionParameters['unix_socket'] = $unixSocketNode->getNodeValue()->__toString(); } // initialize and return a entity manager decorator instance return new DoctrineEntityManagerDecorator(EntityManager::create($connectionParameters, $configuration)); }
/** * Deploys the message queues. * * @param \AppserverIo\Psr\Application\ApplicationInterface|\AppserverIo\Psr\Naming\NamingDirectoryInterface $application The application instance * * @return void */ protected function registerMessageQueues(ApplicationInterface $application) { // build up META-INF directory var $metaInfDir = $this->getWebappPath() . DIRECTORY_SEPARATOR . 'META-INF'; // check if we've found a valid directory if (is_dir($metaInfDir) === false) { return; } // check META-INF + subdirectories for XML files with MQ definitions /** @var \AppserverIo\Appserver\Core\Api\DeploymentService $service */ $service = $application->newService('AppserverIo\\Appserver\\Core\\Api\\DeploymentService'); $xmlFiles = $service->globDir($metaInfDir . DIRECTORY_SEPARATOR . 'message-queues.xml'); // initialize the array for the creating the subdirectories $this->directories = new GenericStackable(); $this->directories[] = $application->getNamingDirectory(); // gather all the deployed web applications foreach ($xmlFiles as $file) { try { // try to initialize a SimpleXMLElement $sxe = new \SimpleXMLElement($file, null, true); $sxe->registerXPathNamespace('a', 'http://www.appserver.io/appserver'); // lookup the MessageQueue's defined in the passed XML node if (($nodes = $sxe->xpath('/a:message-queues/a:message-queue')) === false) { continue; } // validate the file here, if it is not valid we can skip further steps try { /** @var \AppserverIo\Appserver\Core\Api\ConfigurationService $configurationService */ $configurationService = $application->newService('AppserverIo\\Appserver\\Core\\Api\\ConfigurationService'); $configurationService->validateFile($file, null, true); } catch (InvalidConfigurationException $e) { /** @var \Psr\Log\LoggerInterface $systemLogger */ $systemLogger = $this->getApplication()->getInitialContext()->getSystemLogger(); $systemLogger->error($e->getMessage()); $systemLogger->critical(sprintf('Message queue configuration file %s is invalid, needed queues might be missing.', $file)); return; } // iterate over all found queues and initialize them foreach ($nodes as $node) { $this->registeMessageQueue($node); } // if class can not be reflected continue with next class } catch (\Exception $e) { // log an error message $application->getInitialContext()->getSystemLogger()->error($e->__toString()); // proceed with the next queue continue; } } }
/** * Visitor method that registers the class loaders in the application. * * @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance to register the class loader with * @param \AppserverIo\Appserver\Core\Api\Node\ClassLoaderNodeInterface $configuration The class loader configuration * * @return void */ public static function visit(ApplicationInterface $application, ClassLoaderNodeInterface $configuration) { // load the web application path we want to register the class loader for $webappPath = $application->getWebappPath(); // initialize the class path and the enforcement directories $classPath = array(); $enforcementDirs = array(); // add the possible class path if folder is available foreach ($configuration->getDirectories() as $directory) { if (is_dir($webappPath . $directory->getNodeValue())) { array_push($classPath, $webappPath . $directory->getNodeValue()); if ($directory->isEnforced()) { array_push($enforcementDirs, $webappPath . $directory->getNodeValue()); } } } // initialize the arrays of different omit possibilities $omittedEnforcement = array(); $omittedAutoLoading = array(); // iterate over all namespaces and check if they are omitted in one or the other way foreach ($configuration->getNamespaces() as $namespace) { // is the enforcement omitted for this namespace? if ($namespace->omitEnforcement()) { $omittedEnforcement[] = $namespace->getNodeValue()->__toString(); } // is the autoloading omitted for this namespace? if ($namespace->omitAutoLoading()) { $omittedAutoLoading[] = $namespace->getNodeValue()->__toString(); } } // initialize the class loader configuration $config = new Config(); // set the environment mode we want to use $config->setValue('environment', $configuration->getEnvironment()); // set the cache directory $config->setValue('cache/dir', $application->getCacheDir()); // set the default autoloader values $config->setValue('autoloader/dirs', $classPath); // collect the omitted namespaces (if any) $config->setValue('autoloader/omit', $omittedAutoLoading); $config->setValue('enforcement/omit', $omittedEnforcement); // set the default enforcement configuration values $config->setValue('enforcement/dirs', $enforcementDirs); $config->setValue('enforcement/enforce-default-type-safety', $configuration->getTypeSafety()); $config->setValue('enforcement/processing', $configuration->getProcessing()); $config->setValue('enforcement/level', $configuration->getEnforcementLevel()); $config->setValue('enforcement/logger', $application->getInitialContext()->getSystemLogger()); // create a autoloader instance and initialize it $classLoader = new DgClassLoader($config); $classLoader->init(new StackableStructureMap($config->getValue('autoloader/dirs'), $config->getValue('enforcement/dirs'), $config), new AspectRegister()); // add the autoloader to the manager $application->addClassLoader($classLoader, $configuration); }
/** * Creates a new entity manager instance based on the passed configuration. * * @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance to create the entity manager for * @param \AppserverIo\Appserver\Core\Api\Node\PersistenceUnitNodeInterface $persistenceUnitNode The datasource configuration * * @return object The entity manager instance */ public static function factory(ApplicationInterface $application, PersistenceUnitNodeInterface $persistenceUnitNode) { // register additional annotation libraries foreach ($persistenceUnitNode->getAnnotationRegistries() as $annotationRegistry) { // register the annotations specified by the annotation registery $annotationRegistryType = $annotationRegistry->getType(); $registry = new $annotationRegistryType(); $registry->register($annotationRegistry); } // query whether or not an initialize EM configuration is available if ($application->hasAttribute($persistenceUnitNode->getName()) === false) { // globally ignore configured annotations to ignore foreach ($persistenceUnitNode->getIgnoredAnnotations() as $ignoredAnnotation) { AnnotationReader::addGlobalIgnoredName($ignoredAnnotation->getNodeValue()->__toString()); } // load the metadata configuration $metadataConfiguration = $persistenceUnitNode->getMetadataConfiguration(); // prepare the setup properties $absolutePaths = $metadataConfiguration->getDirectoriesAsArray(); $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_PROXY_DIR); $proxyNamespace = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_PROXY_NAMESPACE); $autoGenerateProxyClasses = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_AUTO_GENERATE_PROXY_CLASSES); $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_USE_SIMPLE_ANNOTATION_READER); // load the metadata driver factory class name $metadataDriverFactory = $metadataConfiguration->getFactory(); // initialize the params to be passed to the factory $metadataDriverParams = array(DriverKeys::USE_SIMPLE_ANNOTATION_READER => $useSimpleAnnotationReader); // create the database configuration and initialize the entity manager /** @var \Doctrine\DBAL\Configuration $configuration */ $configuration = new Configuration(); $configuration->setMetadataDriverImpl($metadataDriverFactory::get($configuration, $absolutePaths, $metadataDriverParams)); // initialize the metadata cache configuration $metadataCacheConfiguration = $persistenceUnitNode->getMetadataCacheConfiguration(); $configuration->setMetadataCacheImpl(EntityManagerFactory::getCacheImpl($persistenceUnitNode, $metadataCacheConfiguration)); // initialize the query cache configuration $queryCacheConfiguration = $persistenceUnitNode->getQueryCacheConfiguration(); $configuration->setQueryCacheImpl(EntityManagerFactory::getCacheImpl($persistenceUnitNode, $queryCacheConfiguration)); // initialize the result cache configuration $resultCacheConfiguration = $persistenceUnitNode->getResultCacheConfiguration(); $configuration->setResultCacheImpl(EntityManagerFactory::getCacheImpl($persistenceUnitNode, $resultCacheConfiguration)); // proxy configuration $configuration->setProxyDir($proxyDir = $proxyDir ?: sys_get_temp_dir()); $configuration->setProxyNamespace($proxyNamespace = $proxyNamespace ?: 'Doctrine\\Proxy'); $configuration->setAutoGenerateProxyClasses($autoGenerateProxyClasses = $autoGenerateProxyClasses ?: true); // load the datasource node $datasourceNode = null; foreach ($application->getInitialContext()->getSystemConfiguration()->getDatasources() as $datasourceNode) { if ($datasourceNode->getName() === $persistenceUnitNode->getDatasource()->getName()) { break; } } // throw a exception if the configured datasource is NOT available if ($datasourceNode == null) { throw new \Exception(sprintf('Can\'t find a datasource node for persistence unit %s', $persistenceUnitNode->getName())); } // load the database node $databaseNode = $datasourceNode->getDatabase(); // throw an exception if the configured database is NOT available if ($databaseNode == null) { throw new \Exception(sprintf('Can\'t find database node for persistence unit %s', $persistenceUnitNode->getName())); } // load the driver node $driverNode = $databaseNode->getDriver(); // throw an exception if the configured driver is NOT available if ($driverNode == null) { throw new \Exception(sprintf('Can\'t find driver node for persistence unit %s', $persistenceUnitNode->getName())); } // load the connection parameters $connectionParameters = ConnectionUtil::get($application)->fromDatabaseNode($databaseNode); // append the initialized EM configuration to the application $application->setAttribute($persistenceUnitNode->getName(), array($connectionParameters, $configuration)); } // load the initialized EM configuration from the application list($connectionParameters, $configuration) = $application->getAttribute($persistenceUnitNode->getName()); // initialize and return a entity manager decorator instance return new DoctrineEntityManagerDecorator(EntityManager::create($connectionParameters, $configuration)); }