repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php
PersistenceManager.lookupProxy
public function lookupProxy($lookupName) { // initialize the remote method call parser and the session storage $sessions = new ArrayList(); // initialize the local context connection $connection = new DoctrineLocalContextConnection(); $connection->injectSessions($sessions); $connection->injectApplication($this->getApplication()); // initialize the context session $session = $connection->createContextSession(); // set the session ID from the environment $session->setSessionId(Environment::singleton()->getAttribute(EnvironmentKeys::SESSION_ID)); // lookup and return the requested remote bean instance return $session->createInitialContext()->lookup($lookupName); }
php
public function lookupProxy($lookupName) { // initialize the remote method call parser and the session storage $sessions = new ArrayList(); // initialize the local context connection $connection = new DoctrineLocalContextConnection(); $connection->injectSessions($sessions); $connection->injectApplication($this->getApplication()); // initialize the context session $session = $connection->createContextSession(); // set the session ID from the environment $session->setSessionId(Environment::singleton()->getAttribute(EnvironmentKeys::SESSION_ID)); // lookup and return the requested remote bean instance return $session->createInitialContext()->lookup($lookupName); }
[ "public", "function", "lookupProxy", "(", "$", "lookupName", ")", "{", "// initialize the remote method call parser and the session storage", "$", "sessions", "=", "new", "ArrayList", "(", ")", ";", "// initialize the local context connection", "$", "connection", "=", "new"...
This returns a proxy to the requested session bean. @param string $lookupName The lookup name for the requested session bean @return \AppserverIo\RemoteMethodInvocation\RemoteObjectInterface The proxy instance
[ "This", "returns", "a", "proxy", "to", "the", "requested", "session", "bean", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php#L264-L283
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php
PersistenceManager.invoke
public function invoke(RemoteMethodInterface $remoteMethod, CollectionInterface $sessions) { // prepare method name and parameters and invoke method $className = $remoteMethod->getClassName(); $methodName = $remoteMethod->getMethodName(); $parameters = $remoteMethod->getParameters(); // load a fresh bean instance and add it to the session container $instance = $this->lookup($className); // invoke the remote method call on the local instance return call_user_func_array(array($instance, $methodName), $parameters); }
php
public function invoke(RemoteMethodInterface $remoteMethod, CollectionInterface $sessions) { // prepare method name and parameters and invoke method $className = $remoteMethod->getClassName(); $methodName = $remoteMethod->getMethodName(); $parameters = $remoteMethod->getParameters(); // load a fresh bean instance and add it to the session container $instance = $this->lookup($className); // invoke the remote method call on the local instance return call_user_func_array(array($instance, $methodName), $parameters); }
[ "public", "function", "invoke", "(", "RemoteMethodInterface", "$", "remoteMethod", ",", "CollectionInterface", "$", "sessions", ")", "{", "// prepare method name and parameters and invoke method", "$", "className", "=", "$", "remoteMethod", "->", "getClassName", "(", ")",...
Invoke the passed remote method on the described session bean and return the result. @param \AppserverIo\RemoteMethodInvocation\RemoteMethodInterface $remoteMethod The remote method description @param \AppserverIo\Collections\CollectionInterface $sessions The collection with the sessions @return mixed The result of the remote method invocation
[ "Invoke", "the", "passed", "remote", "method", "on", "the", "described", "session", "bean", "and", "return", "the", "result", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php#L293-L306
appserver-io/appserver
src/AppserverIo/Appserver/Console/ExecutionContext.php
ExecutionContext.run
public function run() { try { // register the default autoloader require SERVER_AUTOLOADER; // register shutdown handler set_error_handler(array(&$this, 'errorHandler')); register_shutdown_function(array(&$this, 'shutdown')); // try to load the application $application = $this->application; // register the applications class loaders $application->registerClassLoaders(); // register the applications annotation registries $application->registerAnnotationRegistries(); // load input/output instances $input = $this->input; $output = $this->output; // add the application instance to the environment Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $application); // create a simulated request/session ID whereas session equals request ID (as long as session has NOT been started) Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $requestId = SessionUtils::generateRandomString()); Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $requestId); // load and initialize the Symfony console application /** @var \Symfony\Component\Console\Application $cli */ $cli = $application->search('Console'); $cli->setAutoExit(false); $cli->setCatchExceptions(true); // run the Symfony console application $cli->run($input, $output); // update the output instance $this->output = $output; } catch (\Exception $e) { // log the exception \error($e->__toString()); } }
php
public function run() { try { // register the default autoloader require SERVER_AUTOLOADER; // register shutdown handler set_error_handler(array(&$this, 'errorHandler')); register_shutdown_function(array(&$this, 'shutdown')); // try to load the application $application = $this->application; // register the applications class loaders $application->registerClassLoaders(); // register the applications annotation registries $application->registerAnnotationRegistries(); // load input/output instances $input = $this->input; $output = $this->output; // add the application instance to the environment Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $application); // create a simulated request/session ID whereas session equals request ID (as long as session has NOT been started) Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $requestId = SessionUtils::generateRandomString()); Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $requestId); // load and initialize the Symfony console application /** @var \Symfony\Component\Console\Application $cli */ $cli = $application->search('Console'); $cli->setAutoExit(false); $cli->setCatchExceptions(true); // run the Symfony console application $cli->run($input, $output); // update the output instance $this->output = $output; } catch (\Exception $e) { // log the exception \error($e->__toString()); } }
[ "public", "function", "run", "(", ")", "{", "try", "{", "// register the default autoloader", "require", "SERVER_AUTOLOADER", ";", "// register shutdown handler", "set_error_handler", "(", "array", "(", "&", "$", "this", ",", "'errorHandler'", ")", ")", ";", "regist...
The thread's main method. @return void
[ "The", "thread", "s", "main", "method", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Console/ExecutionContext.php#L87-L134
appserver-io/appserver
src/AppserverIo/Appserver/Console/ExecutionContext.php
ExecutionContext.errorHandler
public function errorHandler($errno, $errstr, $errfile, $errline) { // query whether or not we've to handle the passed error if ($errno > error_reporting()) { return true; } // add the passed error information to the array with the errors $error = ErrorUtil::singleton()->fromArray(array($errno, $errstr, $errfile, $errline)); // log the error messge and return TRUE, to prevent execution of additinoal error handlers LoggerUtils::log(LogLevel::ERROR, ErrorUtil::singleton()->prepareMessage($error)); return true; }
php
public function errorHandler($errno, $errstr, $errfile, $errline) { // query whether or not we've to handle the passed error if ($errno > error_reporting()) { return true; } // add the passed error information to the array with the errors $error = ErrorUtil::singleton()->fromArray(array($errno, $errstr, $errfile, $errline)); // log the error messge and return TRUE, to prevent execution of additinoal error handlers LoggerUtils::log(LogLevel::ERROR, ErrorUtil::singleton()->prepareMessage($error)); return true; }
[ "public", "function", "errorHandler", "(", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", ")", "{", "// query whether or not we've to handle the passed error", "if", "(", "$", "errno", ">", "error_reporting", "(", ")", ")", "{", "r...
PHP error handler implemenation that replaces the defaulf PHP error handling. As this method will NOT handle Fatal Errors with code E_ERROR or E_USER, so these have to be processed by the shutdown handler itself. @param integer $errno The intern PHP error number @param string $errstr The error message itself @param string $errfile The file where the error occurs @param integer $errline The line where the error occurs @return boolean Always return TRUE, because we want to disable default PHP error handling @link http://docs.php.net/manual/en/function.set-error-handler.php
[ "PHP", "error", "handler", "implemenation", "that", "replaces", "the", "defaulf", "PHP", "error", "handling", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Console/ExecutionContext.php#L162-L175
appserver-io/appserver
src/AppserverIo/Appserver/Console/ExecutionContext.php
ExecutionContext.shutdown
public function shutdown() { // query whether or not, class has been shutdown by an unhandled error if ($lastError = error_get_last()) { // add the passed error information to the array with the errors $error = ErrorUtil::singleton()->fromArray($lastError); // log the error messge and return TRUE, to prevent execution of additinoal error handlers LoggerUtils::log(LogLevel::ERROR, ErrorUtil::singleton()->prepareMessage($error)); } }
php
public function shutdown() { // query whether or not, class has been shutdown by an unhandled error if ($lastError = error_get_last()) { // add the passed error information to the array with the errors $error = ErrorUtil::singleton()->fromArray($lastError); // log the error messge and return TRUE, to prevent execution of additinoal error handlers LoggerUtils::log(LogLevel::ERROR, ErrorUtil::singleton()->prepareMessage($error)); } }
[ "public", "function", "shutdown", "(", ")", "{", "// query whether or not, class has been shutdown by an unhandled error", "if", "(", "$", "lastError", "=", "error_get_last", "(", ")", ")", "{", "// add the passed error information to the array with the errors", "$", "error", ...
Does shutdown logic for request handler if something went wrong and produces a fatal error for example. @return void
[ "Does", "shutdown", "logic", "for", "request", "handler", "if", "something", "went", "wrong", "and", "produces", "a", "fatal", "error", "for", "example", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Console/ExecutionContext.php#L183-L193
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/CertificatesNodeTrait.php
CertificatesNodeTrait.getCertificatesAsArray
public function getCertificatesAsArray() { // Iterate over certificates nodes and convert to an array $certificates = array(); /** @var \AppserverIo\Appserver\Core\Api\Node\CertificateNode $certificateNode */ foreach ($this->getCertificates() as $certificateNode) { // restructure to an array $certificates[] = array( 'domain' => $certificateNode->getDomain(), 'certPath' => $certificateNode->getCertPath() ); } // return certificates array return $certificates; }
php
public function getCertificatesAsArray() { // Iterate over certificates nodes and convert to an array $certificates = array(); /** @var \AppserverIo\Appserver\Core\Api\Node\CertificateNode $certificateNode */ foreach ($this->getCertificates() as $certificateNode) { // restructure to an array $certificates[] = array( 'domain' => $certificateNode->getDomain(), 'certPath' => $certificateNode->getCertPath() ); } // return certificates array return $certificates; }
[ "public", "function", "getCertificatesAsArray", "(", ")", "{", "// Iterate over certificates nodes and convert to an array", "$", "certificates", "=", "array", "(", ")", ";", "/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\CertificateNode $certificateNode */", "foreach", "(", ...
Returns the certificates as an associative array. @return array The array with certificates
[ "Returns", "the", "certificates", "as", "an", "associative", "array", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/CertificatesNodeTrait.php#L60-L75
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/Doctrine/V2/EntityManagerFactory.php
EntityManagerFactory.getCacheImpl
protected function getCacheImpl(CacheConfigurationInterface $cacheConfiguration) { // load the factory class $factory = $cacheConfiguration->getFactory(); // create a cache instance $cache = $factory::get($cacheConfiguration->getParams()); $cache->setNamespace(sprintf('dc2_%s_', md5($this->getPersistenceUnitNode()->getName()))); // return the cache instance return $cache; }
php
protected function getCacheImpl(CacheConfigurationInterface $cacheConfiguration) { // load the factory class $factory = $cacheConfiguration->getFactory(); // create a cache instance $cache = $factory::get($cacheConfiguration->getParams()); $cache->setNamespace(sprintf('dc2_%s_', md5($this->getPersistenceUnitNode()->getName()))); // return the cache instance return $cache; }
[ "protected", "function", "getCacheImpl", "(", "CacheConfigurationInterface", "$", "cacheConfiguration", ")", "{", "// load the factory class", "$", "factory", "=", "$", "cacheConfiguration", "->", "getFactory", "(", ")", ";", "// create a cache instance", "$", "cache", ...
Factory method to create a new cache instance from the passed configuration. @param \AppserverIo\Description\Configuration\CacheConfigurationInterface $cacheConfiguration The cache configuration @return \Doctrine\Common\Cache\CacheProvider The cache instance
[ "Factory", "method", "to", "create", "a", "new", "cache", "instance", "from", "the", "passed", "configuration", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/Doctrine/V2/EntityManagerFactory.php#L100-L112
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/Doctrine/V2/EntityManagerFactory.php
EntityManagerFactory.createConfiguration
protected function createConfiguration() { // load the persistence unit configuration $persistenceUnitNode = $this->getPersistenceUnitNode(); // load the metadata configuration $metadataConfiguration = $persistenceUnitNode->getMetadataConfiguration(); // prepare the setup properties $absolutePaths = $metadataConfiguration->getDirectoriesAsArray(); $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_PROXY_DIR); $proxyNamespace = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_PROXY_NAMESPACE); $autoGenerateProxyClasses = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_AUTO_GENERATE_PROXY_CLASSES); $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationInterface::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 Doctrine ORM configuration $configuration = new Configuration(); $configuration->setMetadataDriverImpl($metadataDriverFactory::get($configuration, $absolutePaths, $metadataDriverParams)); // initialize the metadata cache configuration $metadataCacheConfiguration = $persistenceUnitNode->getMetadataCacheConfiguration(); $configuration->setMetadataCacheImpl($this->getCacheImpl($metadataCacheConfiguration)); // initialize the query cache configuration $queryCacheConfiguration = $persistenceUnitNode->getQueryCacheConfiguration(); $configuration->setQueryCacheImpl($this->getCacheImpl($queryCacheConfiguration)); // initialize the result cache configuration $resultCacheConfiguration = $persistenceUnitNode->getResultCacheConfiguration(); $configuration->setResultCacheImpl($this->getCacheImpl($resultCacheConfiguration)); // proxy configuration $configuration->setProxyDir($proxyDir = $proxyDir ?: sys_get_temp_dir()); $configuration->setProxyNamespace($proxyNamespace = $proxyNamespace ?: 'Doctrine\Proxy'); $configuration->setAutoGenerateProxyClasses($autoGenerateProxyClasses = $autoGenerateProxyClasses ?: true); // repository configuration $configuration->setDefaultRepositoryClassName($persistenceUnitNode->getDefaultRepositoryClassName()); $configuration->setRepositoryFactory($this->getApplication()->search($persistenceUnitNode->getRepositoryFactory())); // return the configuration instance return $configuration; }
php
protected function createConfiguration() { // load the persistence unit configuration $persistenceUnitNode = $this->getPersistenceUnitNode(); // load the metadata configuration $metadataConfiguration = $persistenceUnitNode->getMetadataConfiguration(); // prepare the setup properties $absolutePaths = $metadataConfiguration->getDirectoriesAsArray(); $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_PROXY_DIR); $proxyNamespace = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_PROXY_NAMESPACE); $autoGenerateProxyClasses = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_AUTO_GENERATE_PROXY_CLASSES); $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationInterface::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 Doctrine ORM configuration $configuration = new Configuration(); $configuration->setMetadataDriverImpl($metadataDriverFactory::get($configuration, $absolutePaths, $metadataDriverParams)); // initialize the metadata cache configuration $metadataCacheConfiguration = $persistenceUnitNode->getMetadataCacheConfiguration(); $configuration->setMetadataCacheImpl($this->getCacheImpl($metadataCacheConfiguration)); // initialize the query cache configuration $queryCacheConfiguration = $persistenceUnitNode->getQueryCacheConfiguration(); $configuration->setQueryCacheImpl($this->getCacheImpl($queryCacheConfiguration)); // initialize the result cache configuration $resultCacheConfiguration = $persistenceUnitNode->getResultCacheConfiguration(); $configuration->setResultCacheImpl($this->getCacheImpl($resultCacheConfiguration)); // proxy configuration $configuration->setProxyDir($proxyDir = $proxyDir ?: sys_get_temp_dir()); $configuration->setProxyNamespace($proxyNamespace = $proxyNamespace ?: 'Doctrine\Proxy'); $configuration->setAutoGenerateProxyClasses($autoGenerateProxyClasses = $autoGenerateProxyClasses ?: true); // repository configuration $configuration->setDefaultRepositoryClassName($persistenceUnitNode->getDefaultRepositoryClassName()); $configuration->setRepositoryFactory($this->getApplication()->search($persistenceUnitNode->getRepositoryFactory())); // return the configuration instance return $configuration; }
[ "protected", "function", "createConfiguration", "(", ")", "{", "// load the persistence unit configuration", "$", "persistenceUnitNode", "=", "$", "this", "->", "getPersistenceUnitNode", "(", ")", ";", "// load the metadata configuration", "$", "metadataConfiguration", "=", ...
Create's and return's a new Doctrine ORM configuration instance. @return \Doctrine\ORM\Configuration The configuration instance
[ "Create", "s", "and", "return", "s", "a", "new", "Doctrine", "ORM", "configuration", "instance", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/Doctrine/V2/EntityManagerFactory.php#L119-L168
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/Doctrine/V2/EntityManagerFactory.php
EntityManagerFactory.factory
public function factory() { // load the application and persistence unit configuration $application = $this->getApplication(); $persistenceUnitNode = $this->getPersistenceUnitNode(); // create a new Doctrine ORM configuration instance $configuration = $this->createConfiguration(); // 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 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)); }
php
public function factory() { // load the application and persistence unit configuration $application = $this->getApplication(); $persistenceUnitNode = $this->getPersistenceUnitNode(); // create a new Doctrine ORM configuration instance $configuration = $this->createConfiguration(); // 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 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)); }
[ "public", "function", "factory", "(", ")", "{", "// load the application and persistence unit configuration", "$", "application", "=", "$", "this", "->", "getApplication", "(", ")", ";", "$", "persistenceUnitNode", "=", "$", "this", "->", "getPersistenceUnitNode", "("...
Creates a new entity manager instance based on the given configuration. @return \Doctrine\ORM\EntityManagerInterface The entity manager instance
[ "Creates", "a", "new", "entity", "manager", "instance", "based", "on", "the", "given", "configuration", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/Doctrine/V2/EntityManagerFactory.php#L175-L233
appserver-io/appserver
src/AppserverIo/Appserver/MessageQueue/Callback.php
Callback.run
public function run() { // register the default autoloader require SERVER_AUTOLOADER; // register shutdown handler register_shutdown_function(array(&$this, "shutdown")); // we need to register the class loaders again $application = $this->application; $application->registerClassLoaders(); // register the applications annotation registries $application->registerAnnotationRegistries(); // add the application instance to the environment Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $application); // create s simulated request/session ID whereas session equals request ID Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $sessionId = SessionUtils::generateRandomString()); Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $sessionId); // load application and message instance $message = $this->message; try { // create an intial context instance $initialContext = new InitialContext(); $initialContext->injectApplication($application); // load the callbacks for the actual message state foreach ($message->getCallbacks($message->getState()) as $callback) { // explode the lookup + method name list ($lookupName, $methodName) = $callback; // lookup the bean instance and invoke the callback call_user_func(array($initialContext->lookup($lookupName), $methodName), $message); } } catch (\Exception $e) { \error($e->__toString()); } }
php
public function run() { // register the default autoloader require SERVER_AUTOLOADER; // register shutdown handler register_shutdown_function(array(&$this, "shutdown")); // we need to register the class loaders again $application = $this->application; $application->registerClassLoaders(); // register the applications annotation registries $application->registerAnnotationRegistries(); // add the application instance to the environment Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $application); // create s simulated request/session ID whereas session equals request ID Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $sessionId = SessionUtils::generateRandomString()); Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $sessionId); // load application and message instance $message = $this->message; try { // create an intial context instance $initialContext = new InitialContext(); $initialContext->injectApplication($application); // load the callbacks for the actual message state foreach ($message->getCallbacks($message->getState()) as $callback) { // explode the lookup + method name list ($lookupName, $methodName) = $callback; // lookup the bean instance and invoke the callback call_user_func(array($initialContext->lookup($lookupName), $methodName), $message); } } catch (\Exception $e) { \error($e->__toString()); } }
[ "public", "function", "run", "(", ")", "{", "// register the default autoloader", "require", "SERVER_AUTOLOADER", ";", "// register shutdown handler", "register_shutdown_function", "(", "array", "(", "&", "$", "this", ",", "\"shutdown\"", ")", ")", ";", "// we need to r...
We process the timer here. @return void
[ "We", "process", "the", "timer", "here", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/MessageQueue/Callback.php#L87-L129
appserver-io/appserver
src/AppserverIo/Appserver/MessageQueue/Callback.php
Callback.shutdown
public function shutdown() { // check if there was a fatal error caused shutdown if ($lastError = error_get_last()) { // initialize type + message $type = 0; $message = ''; // extract the last error values extract($lastError); // query whether we've a fatal/user error if ($type === E_ERROR || $type === E_USER_ERROR) { $this->getApplication()->getInitialContext()->getSystemLogger()->error($message); } } }
php
public function shutdown() { // check if there was a fatal error caused shutdown if ($lastError = error_get_last()) { // initialize type + message $type = 0; $message = ''; // extract the last error values extract($lastError); // query whether we've a fatal/user error if ($type === E_ERROR || $type === E_USER_ERROR) { $this->getApplication()->getInitialContext()->getSystemLogger()->error($message); } } }
[ "public", "function", "shutdown", "(", ")", "{", "// check if there was a fatal error caused shutdown", "if", "(", "$", "lastError", "=", "error_get_last", "(", ")", ")", "{", "// initialize type + message", "$", "type", "=", "0", ";", "$", "message", "=", "''", ...
Does shutdown logic for request handler if something went wrong and produces a fatal error for example. @return void
[ "Does", "shutdown", "logic", "for", "request", "handler", "if", "something", "went", "wrong", "and", "produces", "a", "fatal", "error", "for", "example", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/MessageQueue/Callback.php#L137-L152
appserver-io/appserver
src/AppserverIo/Appserver/DependencyInjectionContainer/ParserFactory.php
ParserFactory.createParser
public function createParser(ParserNodeInterface $parserNode, ManagerInterface $manager) { // create a reflection class from the configured parser type $reflectionClass = new ReflectionClass($parserNode->getType()); // create a new parser instance and pass the configuration and manager to the constructor return $reflectionClass->newInstanceArgs(array($parserNode, $manager)); }
php
public function createParser(ParserNodeInterface $parserNode, ManagerInterface $manager) { // create a reflection class from the configured parser type $reflectionClass = new ReflectionClass($parserNode->getType()); // create a new parser instance and pass the configuration and manager to the constructor return $reflectionClass->newInstanceArgs(array($parserNode, $manager)); }
[ "public", "function", "createParser", "(", "ParserNodeInterface", "$", "parserNode", ",", "ManagerInterface", "$", "manager", ")", "{", "// create a reflection class from the configured parser type", "$", "reflectionClass", "=", "new", "ReflectionClass", "(", "$", "parserNo...
Creates and returns a new parser instance from the passed configuration. @param \AppserverIo\Appserver\Core\Api\Node\ParserNodeInterface $parserNode The parser configuration @param \AppserverIo\Psr\Application\ManagerInterface $manager The manager the parser is bound to @return \AppserverIo\Appserver\DependencyInjectionContainer\ParserInterface The parser instance
[ "Creates", "and", "returns", "a", "new", "parser", "instance", "from", "the", "passed", "configuration", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/ParserFactory.php#L47-L55
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/Doctrine/DoctrineLocalContextConnection.php
DoctrineLocalContextConnection.send
public function send(RemoteMethodInterface $remoteMethod) { return $this->getApplication()->search(PersistenceContextInterface::IDENTIFIER)->invoke($remoteMethod, $this->getSessions()); }
php
public function send(RemoteMethodInterface $remoteMethod) { return $this->getApplication()->search(PersistenceContextInterface::IDENTIFIER)->invoke($remoteMethod, $this->getSessions()); }
[ "public", "function", "send", "(", "RemoteMethodInterface", "$", "remoteMethod", ")", "{", "return", "$", "this", "->", "getApplication", "(", ")", "->", "search", "(", "PersistenceContextInterface", "::", "IDENTIFIER", ")", "->", "invoke", "(", "$", "remoteMeth...
Sends the remote method call to the container instance. @param \AppserverIo\RemoteMethodInvocation\RemoteMethodInterface $remoteMethod The remote method instance @return mixed The response from the container @see \AppserverIo\RemoteMethodInvocation\ConnectionInterface::send()
[ "Sends", "the", "remote", "method", "call", "to", "the", "container", "instance", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/Doctrine/DoctrineLocalContextConnection.php#L47-L50
appserver-io/appserver
src/AppserverIo/Appserver/DependencyInjectionContainer/ProviderFactory.php
ProviderFactory.visit
public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // create the storage for the reflection classes and the application specific aliases $reflectionClasses = new GenericStackable(); $namingDirectoryAliases = new GenericStackable(); // create and initialize the DI provider instance $provider = new Provider(); $provider->injectApplication($application); $provider->injectReflectionClasses($reflectionClasses); $provider->injectNamingDirectoryAliases($namingDirectoryAliases); // attach the instance $application->addManager($provider, $managerConfiguration); }
php
public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // create the storage for the reflection classes and the application specific aliases $reflectionClasses = new GenericStackable(); $namingDirectoryAliases = new GenericStackable(); // create and initialize the DI provider instance $provider = new Provider(); $provider->injectApplication($application); $provider->injectReflectionClasses($reflectionClasses); $provider->injectNamingDirectoryAliases($namingDirectoryAliases); // attach the instance $application->addManager($provider, $managerConfiguration); }
[ "public", "static", "function", "visit", "(", "ApplicationInterface", "$", "application", ",", "ManagerNodeInterface", "$", "managerConfiguration", ")", "{", "// create the storage for the reflection classes and the application specific aliases", "$", "reflectionClasses", "=", "n...
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
[ "The", "main", "method", "that", "creates", "new", "instances", "in", "a", "separate", "context", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/ProviderFactory.php#L48-L63
appserver-io/appserver
src/AppserverIo/Appserver/Core/ProxyClassLoader.php
ProxyClassLoader.loadClass
public function loadClass($className) { // concatenate namespace and separator $namespaceAndSeparator = $this->namespace . $this->namespaceSeparator; // if a namespace is available OR the classname contains a namespace if ($namespaceAndSeparator === substr($className, 0, strlen($namespaceAndSeparator)) || $this->namespace === null) { // initialize filename, classname and namespace $fileName = ''; $namespace = ''; if (($lastNsPos = strripos($className, $this->namespaceSeparator)) !== false) { $namespace = substr($className, 0, $lastNsPos); $className = substr($className, $lastNsPos + 1); $fileName = str_replace($this->namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; } // prepare filename $fileName .= $className . $this->fileExtension; // try to load the requested class $toRequire = $this->includePath . DIRECTORY_SEPARATOR . $fileName; $psr4FileName = $this->includePath . DIRECTORY_SEPARATOR . ltrim(strstr(ltrim(strstr($fileName, DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR); // query whether or tno the file exsists if (file_exists($toRequire)) { // require the file and return TRUE require $toRequire; return true; } elseif (file_exists($psr4FileName) && !is_dir($psr4FileName)) { // require the file and return TRUE require $psr4FileName; return true; } } }
php
public function loadClass($className) { // concatenate namespace and separator $namespaceAndSeparator = $this->namespace . $this->namespaceSeparator; // if a namespace is available OR the classname contains a namespace if ($namespaceAndSeparator === substr($className, 0, strlen($namespaceAndSeparator)) || $this->namespace === null) { // initialize filename, classname and namespace $fileName = ''; $namespace = ''; if (($lastNsPos = strripos($className, $this->namespaceSeparator)) !== false) { $namespace = substr($className, 0, $lastNsPos); $className = substr($className, $lastNsPos + 1); $fileName = str_replace($this->namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; } // prepare filename $fileName .= $className . $this->fileExtension; // try to load the requested class $toRequire = $this->includePath . DIRECTORY_SEPARATOR . $fileName; $psr4FileName = $this->includePath . DIRECTORY_SEPARATOR . ltrim(strstr(ltrim(strstr($fileName, DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR); // query whether or tno the file exsists if (file_exists($toRequire)) { // require the file and return TRUE require $toRequire; return true; } elseif (file_exists($psr4FileName) && !is_dir($psr4FileName)) { // require the file and return TRUE require $psr4FileName; return true; } } }
[ "public", "function", "loadClass", "(", "$", "className", ")", "{", "// concatenate namespace and separator", "$", "namespaceAndSeparator", "=", "$", "this", "->", "namespace", ".", "$", "this", "->", "namespaceSeparator", ";", "// if a namespace is available OR the class...
Loads the given class or interface. @param string $className The name of the class to load. @return void
[ "Loads", "the", "given", "class", "or", "interface", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/ProxyClassLoader.php#L115-L151
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/ModulesNodeTrait.php
ModulesNodeTrait.getModulesAsArray
public function getModulesAsArray() { // initialize the array for the modules $modules = array(); // iterate over the module nodes and sort them into an array /** @var \AppserverIo\Appserver\Core\Api\Node\ModuleNode $module */ foreach ($this->getModules() as $module) { $modules[$module->getUuid()] = $module->getType(); } // return the array return $modules; }
php
public function getModulesAsArray() { // initialize the array for the modules $modules = array(); // iterate over the module nodes and sort them into an array /** @var \AppserverIo\Appserver\Core\Api\Node\ModuleNode $module */ foreach ($this->getModules() as $module) { $modules[$module->getUuid()] = $module->getType(); } // return the array return $modules; }
[ "public", "function", "getModulesAsArray", "(", ")", "{", "// initialize the array for the modules", "$", "modules", "=", "array", "(", ")", ";", "// iterate over the module nodes and sort them into an array", "/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\ModuleNode $module */",...
Returns the modules as an associative array @return array The array with the sorted modules
[ "Returns", "the", "modules", "as", "an", "associative", "array" ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/ModulesNodeTrait.php#L60-L74
appserver-io/appserver
src/AppserverIo/Appserver/Core/Extractors/PharExtractor.php
PharExtractor.deployArchive
public function deployArchive(ContainerConfigurationInterface $containerNode, \SplFileInfo $archive) { try { // create folder names based on the archive's basename $tmpFolderName = new \SplFileInfo($this->getTmpDir($containerNode) . DIRECTORY_SEPARATOR . $archive->getFilename()); $webappFolderName = new \SplFileInfo($this->getWebappsDir($containerNode) . DIRECTORY_SEPARATOR . basename($archive->getFilename(), $this->getExtensionSuffix())); // check if archive has not been deployed yet or failed sometime if ($this->isDeployable($archive)) { // flag webapp as deploying $this->flagArchive($archive, ExtractorInterface::FLAG_DEPLOYING); // backup actual webapp folder, if available if ($webappFolderName->isDir()) { // backup files that are NOT part of the archive $this->backupArchive($containerNode, $archive); // delete directories previously backed up $this->removeDir($webappFolderName); } // remove old temporary directory $this->removeDir($tmpFolderName); // initialize a \Phar instance $p = new \Phar($archive); // create a recursive directory iterator $iterator = new \RecursiveIteratorIterator($p); // unify the archive filename, because Windows uses a \ instead of / $archiveFilename = sprintf('phar://%s', str_replace(DIRECTORY_SEPARATOR, '/', $archive->getPathname())); // iterate over all files foreach ($iterator as $file) { // prepare the temporary filename $target = $tmpFolderName . str_replace($archiveFilename, '', $file->getPathname()); // create the directory if necessary if (file_exists($directory = dirname($target)) === false) { if (mkdir($directory, 0755, true) === false) { throw new \Exception(sprintf('Can\'t create directory %s', $directory)); } } // finally copy the file if (copy($file, $target) === false) { throw new \Exception(sprintf('Can\'t copy %s file to %s', $file, $target)); } } // move extracted content to webapps folder and remove temporary directory FileSystem::copyDir($tmpFolderName->getPathname(), $webappFolderName->getPathname()); FileSystem::removeDir($tmpFolderName->getPathname()); // we need to set the user/rights for the extracted folder $this->setUserRights($webappFolderName); // restore backup if available $this->restoreBackup($containerNode, $archive); // flag webapp as deployed $this->flagArchive($archive, ExtractorInterface::FLAG_DEPLOYED); // log a message that the application has successfully been deployed $this->getInitialContext()->getSystemLogger()->info( sprintf('Application archive %s has succussfully been deployed', $archive->getBasename($this->getExtensionSuffix())) ); } } catch (\Exception $e) { // log error $this->getInitialContext()->getSystemLogger()->error($e->__toString()); // flag webapp as failed $this->flagArchive($archive, ExtractorInterface::FLAG_FAILED); } }
php
public function deployArchive(ContainerConfigurationInterface $containerNode, \SplFileInfo $archive) { try { // create folder names based on the archive's basename $tmpFolderName = new \SplFileInfo($this->getTmpDir($containerNode) . DIRECTORY_SEPARATOR . $archive->getFilename()); $webappFolderName = new \SplFileInfo($this->getWebappsDir($containerNode) . DIRECTORY_SEPARATOR . basename($archive->getFilename(), $this->getExtensionSuffix())); // check if archive has not been deployed yet or failed sometime if ($this->isDeployable($archive)) { // flag webapp as deploying $this->flagArchive($archive, ExtractorInterface::FLAG_DEPLOYING); // backup actual webapp folder, if available if ($webappFolderName->isDir()) { // backup files that are NOT part of the archive $this->backupArchive($containerNode, $archive); // delete directories previously backed up $this->removeDir($webappFolderName); } // remove old temporary directory $this->removeDir($tmpFolderName); // initialize a \Phar instance $p = new \Phar($archive); // create a recursive directory iterator $iterator = new \RecursiveIteratorIterator($p); // unify the archive filename, because Windows uses a \ instead of / $archiveFilename = sprintf('phar://%s', str_replace(DIRECTORY_SEPARATOR, '/', $archive->getPathname())); // iterate over all files foreach ($iterator as $file) { // prepare the temporary filename $target = $tmpFolderName . str_replace($archiveFilename, '', $file->getPathname()); // create the directory if necessary if (file_exists($directory = dirname($target)) === false) { if (mkdir($directory, 0755, true) === false) { throw new \Exception(sprintf('Can\'t create directory %s', $directory)); } } // finally copy the file if (copy($file, $target) === false) { throw new \Exception(sprintf('Can\'t copy %s file to %s', $file, $target)); } } // move extracted content to webapps folder and remove temporary directory FileSystem::copyDir($tmpFolderName->getPathname(), $webappFolderName->getPathname()); FileSystem::removeDir($tmpFolderName->getPathname()); // we need to set the user/rights for the extracted folder $this->setUserRights($webappFolderName); // restore backup if available $this->restoreBackup($containerNode, $archive); // flag webapp as deployed $this->flagArchive($archive, ExtractorInterface::FLAG_DEPLOYED); // log a message that the application has successfully been deployed $this->getInitialContext()->getSystemLogger()->info( sprintf('Application archive %s has succussfully been deployed', $archive->getBasename($this->getExtensionSuffix())) ); } } catch (\Exception $e) { // log error $this->getInitialContext()->getSystemLogger()->error($e->__toString()); // flag webapp as failed $this->flagArchive($archive, ExtractorInterface::FLAG_FAILED); } }
[ "public", "function", "deployArchive", "(", "ContainerConfigurationInterface", "$", "containerNode", ",", "\\", "SplFileInfo", "$", "archive", ")", "{", "try", "{", "// create folder names based on the archive's basename", "$", "tmpFolderName", "=", "new", "\\", "SplFileI...
(non-PHPdoc) @param \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode The container the archive belongs to @param \SplFileInfo $archive The archive file to be deployed @return void @see \AppserverIo\Appserver\Core\AbstractExtractor::deployArchive()
[ "(", "non", "-", "PHPdoc", ")" ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Extractors/PharExtractor.php#L77-L155
appserver-io/appserver
src/AppserverIo/Appserver/Core/Extractors/PharExtractor.php
PharExtractor.backupArchive
public function backupArchive(ContainerConfigurationInterface $containerNode, \SplFileInfo $archive) { // if we don't want to create backups, to nothing if ($this->getExtractorNode()->isCreateBackups() === false) { return; } // load the PHAR archive's pathname $pharPathname = $archive->getPathname(); // create tmp & webapp folder name based on the archive's basename $webappFolderName = $this->getWebappsDir($containerNode) . DIRECTORY_SEPARATOR . basename($archive->getFilename(), $this->getExtensionSuffix()); $tmpFolderName = $this->getTmpDir($containerNode) . DIRECTORY_SEPARATOR . md5(basename($archive->getFilename(), $this->getExtensionSuffix())); // initialize PHAR archive $p = new \Phar($archive); // iterate over the PHAR content to backup files that are NOT part of the archive foreach (new \RecursiveIteratorIterator($p) as $file) { unlink(str_replace($this->createUrl($pharPathname), $webappFolderName, $file->getPathName())); } // delete empty directories but LEAVE files created by app $this->removeDir($webappFolderName, false); // copy backup to tmp directory $this->copyDir($webappFolderName, $tmpFolderName); // we have to set the user rights to the user:group configured within the system configuration $this->setUserRights(new \SplFileInfo($tmpFolderName)); // log a message that the application has successfully been deployed $this->getInitialContext()->getSystemLogger()->info( sprintf('Application archive %s has succussfully been backed up', $archive->getBasename($this->getExtensionSuffix())) ); }
php
public function backupArchive(ContainerConfigurationInterface $containerNode, \SplFileInfo $archive) { // if we don't want to create backups, to nothing if ($this->getExtractorNode()->isCreateBackups() === false) { return; } // load the PHAR archive's pathname $pharPathname = $archive->getPathname(); // create tmp & webapp folder name based on the archive's basename $webappFolderName = $this->getWebappsDir($containerNode) . DIRECTORY_SEPARATOR . basename($archive->getFilename(), $this->getExtensionSuffix()); $tmpFolderName = $this->getTmpDir($containerNode) . DIRECTORY_SEPARATOR . md5(basename($archive->getFilename(), $this->getExtensionSuffix())); // initialize PHAR archive $p = new \Phar($archive); // iterate over the PHAR content to backup files that are NOT part of the archive foreach (new \RecursiveIteratorIterator($p) as $file) { unlink(str_replace($this->createUrl($pharPathname), $webappFolderName, $file->getPathName())); } // delete empty directories but LEAVE files created by app $this->removeDir($webappFolderName, false); // copy backup to tmp directory $this->copyDir($webappFolderName, $tmpFolderName); // we have to set the user rights to the user:group configured within the system configuration $this->setUserRights(new \SplFileInfo($tmpFolderName)); // log a message that the application has successfully been deployed $this->getInitialContext()->getSystemLogger()->info( sprintf('Application archive %s has succussfully been backed up', $archive->getBasename($this->getExtensionSuffix())) ); }
[ "public", "function", "backupArchive", "(", "ContainerConfigurationInterface", "$", "containerNode", ",", "\\", "SplFileInfo", "$", "archive", ")", "{", "// if we don't want to create backups, to nothing", "if", "(", "$", "this", "->", "getExtractorNode", "(", ")", "->"...
Creates a backup of files that are NOT part of the passed archive. @param \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode The container the archive belongs to @param \SplFileInfo $archive Backup files that are NOT part of this archive @return void
[ "Creates", "a", "backup", "of", "files", "that", "are", "NOT", "part", "of", "the", "passed", "archive", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Extractors/PharExtractor.php#L166-L202
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/Doctrine/V2/DriverFactories/AnnotationDriverFactory.php
AnnotationDriverFactory.get
public static function get(Configuration $configuration, array $paths = array(), array $params = array()) { // query whether or not we want to use the simple annotation reader $useSimpleAnnotationReader = false; if (isset($params[DriverKeys::USE_SIMPLE_ANNOTATION_READER])) { $useSimpleAnnotationReader = $params[DriverKeys::USE_SIMPLE_ANNOTATION_READER]; } // create and return the driver instance return $configuration->newDefaultAnnotationDriver($paths, $useSimpleAnnotationReader); }
php
public static function get(Configuration $configuration, array $paths = array(), array $params = array()) { // query whether or not we want to use the simple annotation reader $useSimpleAnnotationReader = false; if (isset($params[DriverKeys::USE_SIMPLE_ANNOTATION_READER])) { $useSimpleAnnotationReader = $params[DriverKeys::USE_SIMPLE_ANNOTATION_READER]; } // create and return the driver instance return $configuration->newDefaultAnnotationDriver($paths, $useSimpleAnnotationReader); }
[ "public", "static", "function", "get", "(", "Configuration", "$", "configuration", ",", "array", "$", "paths", "=", "array", "(", ")", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "// query whether or not we want to use the simple annotation read...
Return's the new driver instance. @param \Doctrine\ORM\Configuration $configuration The DBAL configuration to create the driver for @param array $paths The path to the driver configuration @param array $params The additional configuration params @return \Doctrine\Common\Persistence\Mapping\Driver\MappingDriver The driver instance
[ "Return", "s", "the", "new", "driver", "instance", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/Doctrine/V2/DriverFactories/AnnotationDriverFactory.php#L47-L58
appserver-io/appserver
src/AppserverIo/Appserver/AspectContainer/AspectManagerFactory.php
AspectManagerFactory.visit
public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // check if the correct autoloader has been registered, if so we have to get its aspect register. // if not we have to fail here $classLoader = $application->search('DgClassLoader'); $aspectRegister = $classLoader->getAspectRegister(); // initialize the aspect manager $aspectManager = new AspectManager(); $aspectManager->injectApplication($application); $aspectManager->injectAspectRegister($aspectRegister); // attach the instance $application->addManager($aspectManager, $managerConfiguration); }
php
public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // check if the correct autoloader has been registered, if so we have to get its aspect register. // if not we have to fail here $classLoader = $application->search('DgClassLoader'); $aspectRegister = $classLoader->getAspectRegister(); // initialize the aspect manager $aspectManager = new AspectManager(); $aspectManager->injectApplication($application); $aspectManager->injectAspectRegister($aspectRegister); // attach the instance $application->addManager($aspectManager, $managerConfiguration); }
[ "public", "static", "function", "visit", "(", "ApplicationInterface", "$", "application", ",", "ManagerNodeInterface", "$", "managerConfiguration", ")", "{", "// check if the correct autoloader has been registered, if so we have to get its aspect register.", "// if not we have to fail ...
The main method that creates new instances in a separate context. @param \AppserverIo\Psr\Application\ApplicationInterface|\AppserverIo\Psr\Naming\NamingDirectoryInterface $application The application instance to register the class loader with @param \AppserverIo\Appserver\Core\Api\Node\ManagerNodeInterface $managerConfiguration The manager configuration @return void
[ "The", "main", "method", "that", "creates", "new", "instances", "in", "a", "separate", "context", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/AspectContainer/AspectManagerFactory.php#L47-L62
appserver-io/appserver
src/AppserverIo/Appserver/Core/FileClassLoaderFactory.php
FileClassLoaderFactory.visit
public static function visit(ApplicationInterface $application, ClassLoaderNodeInterface $configuration) { // initialize the array with the configured directories $directories = array(); // load the composer class loader for the configured directories /** @var \AppserverIo\Appserver\Core\Api\Node\DirectoryNode $directory */ foreach ($configuration->getDirectories() as $directory) { // we prepare the directories to include files AFTER registering (in application context) $directories[] = $directory->getNodeValue(); } // attach the class loader instance $application->addClassLoader(new FileClassLoader($directories), $configuration); }
php
public static function visit(ApplicationInterface $application, ClassLoaderNodeInterface $configuration) { // initialize the array with the configured directories $directories = array(); // load the composer class loader for the configured directories /** @var \AppserverIo\Appserver\Core\Api\Node\DirectoryNode $directory */ foreach ($configuration->getDirectories() as $directory) { // we prepare the directories to include files AFTER registering (in application context) $directories[] = $directory->getNodeValue(); } // attach the class loader instance $application->addClassLoader(new FileClassLoader($directories), $configuration); }
[ "public", "static", "function", "visit", "(", "ApplicationInterface", "$", "application", ",", "ClassLoaderNodeInterface", "$", "configuration", ")", "{", "// initialize the array with the configured directories", "$", "directories", "=", "array", "(", ")", ";", "// load ...
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
[ "Visitor", "method", "that", "registers", "the", "class", "loaders", "in", "the", "application", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/FileClassLoaderFactory.php#L47-L62
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/PersistenceContainerValve.php
PersistenceContainerValve.invoke
public function invoke(HttpServletRequestInterface $servletRequest, HttpServletResponseInterface $servletResponse) { try { // unpack the remote method call $remoteMethod = RemoteMethodProtocol::unpack($servletRequest->getBodyContent()); // start the session $servletRequest->setRequestedSessionName(SessionInterface::SESSION_NAME); $servletRequest->getSession(true); // load the application context /** @var \AppserverIo\Appserver\Application\Application $application */ $application = $servletRequest->getContext(); // invoke the remote method and re-attach the bean instance to the container $response = $application->search(BeanContextInterface::IDENTIFIER)->invoke($remoteMethod, new ArrayList()); // serialize the remote method and write it to the socket $servletResponse->appendBodyStream(RemoteMethodProtocol::pack($response)); } catch (\Exception $e) { // catch the exception and append it to the body stream $servletResponse->appendBodyStream(RemoteMethodProtocol::pack(RemoteExceptionWrapper::factory($e))); } // finally dispatch this request, because we have finished processing it $servletRequest->setDispatched(true); }
php
public function invoke(HttpServletRequestInterface $servletRequest, HttpServletResponseInterface $servletResponse) { try { // unpack the remote method call $remoteMethod = RemoteMethodProtocol::unpack($servletRequest->getBodyContent()); // start the session $servletRequest->setRequestedSessionName(SessionInterface::SESSION_NAME); $servletRequest->getSession(true); // load the application context /** @var \AppserverIo\Appserver\Application\Application $application */ $application = $servletRequest->getContext(); // invoke the remote method and re-attach the bean instance to the container $response = $application->search(BeanContextInterface::IDENTIFIER)->invoke($remoteMethod, new ArrayList()); // serialize the remote method and write it to the socket $servletResponse->appendBodyStream(RemoteMethodProtocol::pack($response)); } catch (\Exception $e) { // catch the exception and append it to the body stream $servletResponse->appendBodyStream(RemoteMethodProtocol::pack(RemoteExceptionWrapper::factory($e))); } // finally dispatch this request, because we have finished processing it $servletRequest->setDispatched(true); }
[ "public", "function", "invoke", "(", "HttpServletRequestInterface", "$", "servletRequest", ",", "HttpServletResponseInterface", "$", "servletResponse", ")", "{", "try", "{", "// unpack the remote method call", "$", "remoteMethod", "=", "RemoteMethodProtocol", "::", "unpack"...
Processes the request by invoking the request handler that executes the servlet in a protected context. @param \AppserverIo\Psr\Servlet\Http\HttpServletRequestInterface $servletRequest The request instance @param \AppserverIo\Psr\Servlet\Http\HttpServletResponseInterface $servletResponse The response instance @return void
[ "Processes", "the", "request", "by", "invoking", "the", "request", "handler", "that", "executes", "the", "servlet", "in", "a", "protected", "context", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/PersistenceContainerValve.php#L54-L82
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/WebResourceCollectionNode.php
WebResourceCollectionNode.getUrlPatternsAsArray
public function getUrlPatternsAsArray() { // initialize the array for the URL patterns $urlPatterns = array(); // prepare the URL patterns /** @var \AppserverIo\Appserver\Core\Api\Node\UrlPatternNode $urlPatternNode */ foreach ($this->getUrlPatterns() as $urlPatternNode) { $urlPatterns[] = $urlPatternNode->__toString(); } // return the array with the URL patterns return $urlPatterns; }
php
public function getUrlPatternsAsArray() { // initialize the array for the URL patterns $urlPatterns = array(); // prepare the URL patterns /** @var \AppserverIo\Appserver\Core\Api\Node\UrlPatternNode $urlPatternNode */ foreach ($this->getUrlPatterns() as $urlPatternNode) { $urlPatterns[] = $urlPatternNode->__toString(); } // return the array with the URL patterns return $urlPatterns; }
[ "public", "function", "getUrlPatternsAsArray", "(", ")", "{", "// initialize the array for the URL patterns", "$", "urlPatterns", "=", "array", "(", ")", ";", "// prepare the URL patterns", "/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\UrlPatternNode $urlPatternNode */", "fore...
Returns the URL patterns as an associative array @return array The array with the sorted URL patterns
[ "Returns", "the", "URL", "patterns", "as", "an", "associative", "array" ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/WebResourceCollectionNode.php#L157-L171
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/WebResourceCollectionNode.php
WebResourceCollectionNode.getHttpMethodsAsArray
public function getHttpMethodsAsArray() { // initialize the array for the HTTP methods $httpMethods = array(); // prepare the HTTP methods /** @var \AppserverIo\Appserver\Core\Api\Node\HttpMethodNode $httpMethodNode */ foreach ($this->getHttpMethods() as $httpMethodNode) { $httpMethods[] = strtoupper($httpMethodNode->__toString()); } // return the array with the HTTP methods return $httpMethods; }
php
public function getHttpMethodsAsArray() { // initialize the array for the HTTP methods $httpMethods = array(); // prepare the HTTP methods /** @var \AppserverIo\Appserver\Core\Api\Node\HttpMethodNode $httpMethodNode */ foreach ($this->getHttpMethods() as $httpMethodNode) { $httpMethods[] = strtoupper($httpMethodNode->__toString()); } // return the array with the HTTP methods return $httpMethods; }
[ "public", "function", "getHttpMethodsAsArray", "(", ")", "{", "// initialize the array for the HTTP methods", "$", "httpMethods", "=", "array", "(", ")", ";", "// prepare the HTTP methods", "/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\HttpMethodNode $httpMethodNode */", "fore...
Returns the HTTP methods as an associative array. The HTTP methods will be converted to upper case when using this method. @return array The array with the HTTP methods
[ "Returns", "the", "HTTP", "methods", "as", "an", "associative", "array", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/WebResourceCollectionNode.php#L180-L194
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/WebResourceCollectionNode.php
WebResourceCollectionNode.getHttpMethodOmissionsAsArray
public function getHttpMethodOmissionsAsArray() { // initialize the array for the HTTP method omissions $httpMethodOmissions = array(); // prepare the HTTP method omissions /** @var \AppserverIo\Appserver\Core\Api\Node\HttpMethodOmissionNode $httpMethodOmissionNode */ foreach ($this->getHttpMethodOmissions() as $httpMethodOmissionNode) { $httpMethodOmissions[] = strtoupper($httpMethodOmissionNode->__toString()); } // return the array with the HTTP method omissions return $httpMethodOmissions; }
php
public function getHttpMethodOmissionsAsArray() { // initialize the array for the HTTP method omissions $httpMethodOmissions = array(); // prepare the HTTP method omissions /** @var \AppserverIo\Appserver\Core\Api\Node\HttpMethodOmissionNode $httpMethodOmissionNode */ foreach ($this->getHttpMethodOmissions() as $httpMethodOmissionNode) { $httpMethodOmissions[] = strtoupper($httpMethodOmissionNode->__toString()); } // return the array with the HTTP method omissions return $httpMethodOmissions; }
[ "public", "function", "getHttpMethodOmissionsAsArray", "(", ")", "{", "// initialize the array for the HTTP method omissions", "$", "httpMethodOmissions", "=", "array", "(", ")", ";", "// prepare the HTTP method omissions", "/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\HttpMetho...
Returns the HTTP method omissions as an associative array. The HTTP methods will be converted to upper case when using this method. @return array The array with the HTTP method omissions
[ "Returns", "the", "HTTP", "method", "omissions", "as", "an", "associative", "array", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/WebResourceCollectionNode.php#L203-L217
appserver-io/appserver
src/AppserverIo/Appserver/Core/AbstractExecutorThread.php
AbstractExecutorThread.run
public function run() { try { // register shutdown handler register_shutdown_function($this->getDefaultShutdownMethod()); // bootstrap the daemon $this->bootstrap(); // invoke the execute method try { $this->execute(); } catch (\Exception $e) { $this->log(LogLevel::ERROR, $e->__toString()); } // clean up the instances and free memory $this->cleanUp(); } catch (\Exception $e) { $this->log(LogLevel::ERROR, $e->__toString()); } }
php
public function run() { try { // register shutdown handler register_shutdown_function($this->getDefaultShutdownMethod()); // bootstrap the daemon $this->bootstrap(); // invoke the execute method try { $this->execute(); } catch (\Exception $e) { $this->log(LogLevel::ERROR, $e->__toString()); } // clean up the instances and free memory $this->cleanUp(); } catch (\Exception $e) { $this->log(LogLevel::ERROR, $e->__toString()); } }
[ "public", "function", "run", "(", ")", "{", "try", "{", "// register shutdown handler", "register_shutdown_function", "(", "$", "this", "->", "getDefaultShutdownMethod", "(", ")", ")", ";", "// bootstrap the daemon", "$", "this", "->", "bootstrap", "(", ")", ";", ...
The daemon's main run method. It should not be necessary to override, instead use the main(), iterate() and cleanup() methods to implement the daemons custom functionality. @return void @see \Thread::run()
[ "The", "daemon", "s", "main", "run", "method", ".", "It", "should", "not", "be", "necessary", "to", "override", "instead", "use", "the", "main", "()", "iterate", "()", "and", "cleanup", "()", "methods", "to", "implement", "the", "daemons", "custom", "funct...
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractExecutorThread.php#L92-L115
appserver-io/appserver
src/AppserverIo/Appserver/Core/Listeners/CreateSslCertificateListener.php
CreateSslCertificateListener.handle
public function handle(EventInterface $event) { try { // load the application server instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // load the service instance and create the SSL file if not available /** @var \AppserverIo\Appserver\Core\Api\ContainerService $service */ $service = $applicationServer->newService('AppserverIo\Appserver\Core\Api\ContainerService'); $service->createSslCertificate(new \SplFileInfo($service->getConfDir(CreateSslCertificateListener::DEFAULT_CERTIFICATE_NAME))); } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
php
public function handle(EventInterface $event) { try { // load the application server instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // load the service instance and create the SSL file if not available /** @var \AppserverIo\Appserver\Core\Api\ContainerService $service */ $service = $applicationServer->newService('AppserverIo\Appserver\Core\Api\ContainerService'); $service->createSslCertificate(new \SplFileInfo($service->getConfDir(CreateSslCertificateListener::DEFAULT_CERTIFICATE_NAME))); } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
[ "public", "function", "handle", "(", "EventInterface", "$", "event", ")", "{", "try", "{", "// load the application server instance", "/** @var \\AppserverIo\\Psr\\ApplicationServer\\ApplicationServerInterface $applicationServer */", "$", "applicationServer", "=", "$", "this", "-...
Handle an event. @param \League\Event\EventInterface $event The triggering event @return void @see \League\Event\ListenerInterface::handle()
[ "Handle", "an", "event", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Listeners/CreateSslCertificateListener.php#L52-L71
appserver-io/appserver
src/AppserverIo/Appserver/Application/ManagerShutdownThread.php
ManagerShutdownThread.run
public function run() { // register the default autoloader require SERVER_AUTOLOADER; // create a local copy of the manager instance $manager = $this->manager; // query whether the manager has an application with class loaders/annotation registries to be registered if (method_exists($manager, 'getApplication') && $application = $manager->getApplication()) { $application->registerClassLoaders(); $application->registerAnnotationRegistries(); } // stop the manager if an apropriate method exists if (method_exists($manager, 'stop')) { $manager->stop(); } }
php
public function run() { // register the default autoloader require SERVER_AUTOLOADER; // create a local copy of the manager instance $manager = $this->manager; // query whether the manager has an application with class loaders/annotation registries to be registered if (method_exists($manager, 'getApplication') && $application = $manager->getApplication()) { $application->registerClassLoaders(); $application->registerAnnotationRegistries(); } // stop the manager if an apropriate method exists if (method_exists($manager, 'stop')) { $manager->stop(); } }
[ "public", "function", "run", "(", ")", "{", "// register the default autoloader", "require", "SERVER_AUTOLOADER", ";", "// create a local copy of the manager instance", "$", "manager", "=", "$", "this", "->", "manager", ";", "// query whether the manager has an application with...
Handles the clean manager shutdown. @return void
[ "Handles", "the", "clean", "manager", "shutdown", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Application/ManagerShutdownThread.php#L54-L73
appserver-io/appserver
src/AppserverIo/Appserver/Core/Utilities/EnumState.php
EnumState.get
public static function get($state) { // check if the requested container state is available and create a new instance if (in_array($state, EnumState::getStates())) { return new EnumState($state); } // throw a exception if the requested runlevel is not available throw new InvalidStateException( sprintf( 'Requested state %s is not available (choose on of: %s)', $state, implode(',', EnumState::getStates()) ) ); }
php
public static function get($state) { // check if the requested container state is available and create a new instance if (in_array($state, EnumState::getStates())) { return new EnumState($state); } // throw a exception if the requested runlevel is not available throw new InvalidStateException( sprintf( 'Requested state %s is not available (choose on of: %s)', $state, implode(',', EnumState::getStates()) ) ); }
[ "public", "static", "function", "get", "(", "$", "state", ")", "{", "// check if the requested container state is available and create a new instance", "if", "(", "in_array", "(", "$", "state", ",", "EnumState", "::", "getStates", "(", ")", ")", ")", "{", "return", ...
Factory method to create a new state instance. @param integer $state The state to create an instance for @return \AppserverIo\Appserver\Core\Utilities\EnumState The state key instance @throws \AppserverIo\Appserver\Core\Utilities\InvalidStateException Is thrown if the state is not available
[ "Factory", "method", "to", "create", "a", "new", "state", "instance", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/EnumState.php#L163-L179
appserver-io/appserver
src/AppserverIo/Appserver/Core/Scanner/RecursiveDirectoryScanner.php
RecursiveDirectoryScanner.getDirectoryHash
protected function getDirectoryHash(\SplFileInfo $directory) { // clear the stat cache clearstatcache(); // initialize the array for the file stats $files = array(); $result = array(); // prepare the array with the file extensions of the files used to build the hash $extensionsToWatch = $this->getExtensionsToWatch(); // load all files foreach ($extensionsToWatch as $extensionToWatch) { $files = array_merge($files, $this->getService()->globDir($directory . DIRECTORY_SEPARATOR . '*.' . $extensionToWatch)); } // iterate over the files foreach ($files as $file) { // load the last modification time $mtime = filemtime($file); // store the modification time if (isset($result[$file]) === false || $result[$file] !== $mtime) { $result[$file] = $mtime; } } // return a md5 hash representation of the directory return md5(serialize($result)); }
php
protected function getDirectoryHash(\SplFileInfo $directory) { // clear the stat cache clearstatcache(); // initialize the array for the file stats $files = array(); $result = array(); // prepare the array with the file extensions of the files used to build the hash $extensionsToWatch = $this->getExtensionsToWatch(); // load all files foreach ($extensionsToWatch as $extensionToWatch) { $files = array_merge($files, $this->getService()->globDir($directory . DIRECTORY_SEPARATOR . '*.' . $extensionToWatch)); } // iterate over the files foreach ($files as $file) { // load the last modification time $mtime = filemtime($file); // store the modification time if (isset($result[$file]) === false || $result[$file] !== $mtime) { $result[$file] = $mtime; } } // return a md5 hash representation of the directory return md5(serialize($result)); }
[ "protected", "function", "getDirectoryHash", "(", "\\", "SplFileInfo", "$", "directory", ")", "{", "// clear the stat cache", "clearstatcache", "(", ")", ";", "// initialize the array for the file stats", "$", "files", "=", "array", "(", ")", ";", "$", "result", "="...
Calculates an hash value for all files with certain extensions. This is used to test if the hash value changed, so if it changed, the appserver can react accordingly. @param \SplFileInfo $directory The directory to watch @return string The hash value build out of the found filenames
[ "Calculates", "an", "hash", "value", "for", "all", "files", "with", "certain", "extensions", ".", "This", "is", "used", "to", "test", "if", "the", "hash", "value", "changed", "so", "if", "it", "changed", "the", "appserver", "can", "react", "accordingly", "...
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Scanner/RecursiveDirectoryScanner.php#L67-L98
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Servlets/DhtmlServlet.php
DhtmlServlet.init
public function init(ServletConfigInterface $servletConfig) { // pre-initialize the X-POWERED-BY header $this->poweredBy = get_class($this); // pre-initialize the possible DHTML template paths $this->webappPath = $servletConfig->getWebappPath(); $this->appBase = $servletConfig->getServletContext()->getAppBase(); $this->baseDirectory = $servletConfig->getServletContext()->getBaseDirectory(); }
php
public function init(ServletConfigInterface $servletConfig) { // pre-initialize the X-POWERED-BY header $this->poweredBy = get_class($this); // pre-initialize the possible DHTML template paths $this->webappPath = $servletConfig->getWebappPath(); $this->appBase = $servletConfig->getServletContext()->getAppBase(); $this->baseDirectory = $servletConfig->getServletContext()->getBaseDirectory(); }
[ "public", "function", "init", "(", "ServletConfigInterface", "$", "servletConfig", ")", "{", "// pre-initialize the X-POWERED-BY header", "$", "this", "->", "poweredBy", "=", "get_class", "(", "$", "this", ")", ";", "// pre-initialize the possible DHTML template paths", "...
Initializes the servlet with the passed configuration. @param \AppserverIo\Psr\Servlet\ServletConfigInterface $servletConfig The configuration to initialize the servlet with @return void
[ "Initializes", "the", "servlet", "with", "the", "passed", "configuration", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Servlets/DhtmlServlet.php#L122-L132
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Servlets/DhtmlServlet.php
DhtmlServlet.service
public function service(ServletRequestInterface $servletRequest, ServletResponseInterface $servletResponse) { // pre-initialize the X-POWERED-BY header $poweredBy = $this->getPoweredBy(); // append an existing X-POWERED-BY header if available if ($servletResponse->hasHeader(HttpProtocol::HEADER_X_POWERED_BY)) { $poweredBy = $servletResponse->getHeader(HttpProtocol::HEADER_X_POWERED_BY) . ', ' . $poweredBy; } // set the X-POWERED-BY header $servletResponse->addHeader(HttpProtocol::HEADER_X_POWERED_BY, $poweredBy); // servlet path === relative path to the template name $template = $servletRequest->getServletPath(); // check if the template is available if (!file_exists($pathToTemplate = $this->getWebappPath() . $template)) { if (!file_exists($pathToTemplate = $this->getAppBase() . $template)) { if (!file_exists($pathToTemplate = $this->getBaseDirectory() . $template)) { throw new ServletException(sprintf('Can\'t load requested template \'%s\'', $template)); } } } // process the template ob_start(); require $pathToTemplate; // add the servlet name to the response $servletResponse->appendBodyStream(ob_get_clean()); }
php
public function service(ServletRequestInterface $servletRequest, ServletResponseInterface $servletResponse) { // pre-initialize the X-POWERED-BY header $poweredBy = $this->getPoweredBy(); // append an existing X-POWERED-BY header if available if ($servletResponse->hasHeader(HttpProtocol::HEADER_X_POWERED_BY)) { $poweredBy = $servletResponse->getHeader(HttpProtocol::HEADER_X_POWERED_BY) . ', ' . $poweredBy; } // set the X-POWERED-BY header $servletResponse->addHeader(HttpProtocol::HEADER_X_POWERED_BY, $poweredBy); // servlet path === relative path to the template name $template = $servletRequest->getServletPath(); // check if the template is available if (!file_exists($pathToTemplate = $this->getWebappPath() . $template)) { if (!file_exists($pathToTemplate = $this->getAppBase() . $template)) { if (!file_exists($pathToTemplate = $this->getBaseDirectory() . $template)) { throw new ServletException(sprintf('Can\'t load requested template \'%s\'', $template)); } } } // process the template ob_start(); require $pathToTemplate; // add the servlet name to the response $servletResponse->appendBodyStream(ob_get_clean()); }
[ "public", "function", "service", "(", "ServletRequestInterface", "$", "servletRequest", ",", "ServletResponseInterface", "$", "servletResponse", ")", "{", "// pre-initialize the X-POWERED-BY header", "$", "poweredBy", "=", "$", "this", "->", "getPoweredBy", "(", ")", ";...
Processes the DHTML file specified as servlet name. @param \AppserverIo\Psr\Servlet\ServletRequestInterface $servletRequest The request instance @param \AppserverIo\Psr\Servlet\ServletResponseInterface $servletResponse The response sent back to the client @return void @throws \AppserverIo\Psr\Servlet\ServletException If no action has been found for the requested path
[ "Processes", "the", "DHTML", "file", "specified", "as", "servlet", "name", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Servlets/DhtmlServlet.php#L144-L176
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php
AppserverNode.initDefaultDirectories
protected function initDefaultDirectories() { $this->setParam(DirectoryKeys::TMP, ParamNode::TYPE_STRING, '/tmp'); $this->setParam(DirectoryKeys::DEPLOY, ParamNode::TYPE_STRING, '/deploy'); $this->setParam(DirectoryKeys::VENDOR, ParamNode::TYPE_STRING, '/vendor'); $this->setParam(DirectoryKeys::WEBAPPS, ParamNode::TYPE_STRING, '/webapps'); $this->setParam(DirectoryKeys::VAR_LOG, ParamNode::TYPE_STRING, '/var/log'); $this->setParam(DirectoryKeys::VAR_RUN, ParamNode::TYPE_STRING, '/var/run'); $this->setParam(DirectoryKeys::VAR_TMP, ParamNode::TYPE_STRING, '/var/tmp'); $this->setParam(DirectoryKeys::ETC, ParamNode::TYPE_STRING, '/etc'); $this->setParam(DirectoryKeys::ETC_APPSERVER, ParamNode::TYPE_STRING, '/etc/appserver'); $this->setParam(DirectoryKeys::ETC_APPSERVER_CONFD, ParamNode::TYPE_STRING, '/etc/appserver/conf.d'); }
php
protected function initDefaultDirectories() { $this->setParam(DirectoryKeys::TMP, ParamNode::TYPE_STRING, '/tmp'); $this->setParam(DirectoryKeys::DEPLOY, ParamNode::TYPE_STRING, '/deploy'); $this->setParam(DirectoryKeys::VENDOR, ParamNode::TYPE_STRING, '/vendor'); $this->setParam(DirectoryKeys::WEBAPPS, ParamNode::TYPE_STRING, '/webapps'); $this->setParam(DirectoryKeys::VAR_LOG, ParamNode::TYPE_STRING, '/var/log'); $this->setParam(DirectoryKeys::VAR_RUN, ParamNode::TYPE_STRING, '/var/run'); $this->setParam(DirectoryKeys::VAR_TMP, ParamNode::TYPE_STRING, '/var/tmp'); $this->setParam(DirectoryKeys::ETC, ParamNode::TYPE_STRING, '/etc'); $this->setParam(DirectoryKeys::ETC_APPSERVER, ParamNode::TYPE_STRING, '/etc/appserver'); $this->setParam(DirectoryKeys::ETC_APPSERVER_CONFD, ParamNode::TYPE_STRING, '/etc/appserver/conf.d'); }
[ "protected", "function", "initDefaultDirectories", "(", ")", "{", "$", "this", "->", "setParam", "(", "DirectoryKeys", "::", "TMP", ",", "ParamNode", "::", "TYPE_STRING", ",", "'/tmp'", ")", ";", "$", "this", "->", "setParam", "(", "DirectoryKeys", "::", "DE...
Initialize the default directories. @return void
[ "Initialize", "the", "default", "directories", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php#L141-L153
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php
AppserverNode.initDefaultFiles
protected function initDefaultFiles() { $logDir = $this->getParam(DirectoryKeys::VAR_LOG) . DIRECTORY_SEPARATOR; $this->setParam(FileKeys::APPSERVER_ERRORS_LOG, ParamNode::TYPE_STRING, $logDir . 'appserver-errors.log'); $this->setParam(FileKeys::APPSERVER_ACCESS_LOG, ParamNode::TYPE_STRING, $logDir . 'appserver-access.log'); }
php
protected function initDefaultFiles() { $logDir = $this->getParam(DirectoryKeys::VAR_LOG) . DIRECTORY_SEPARATOR; $this->setParam(FileKeys::APPSERVER_ERRORS_LOG, ParamNode::TYPE_STRING, $logDir . 'appserver-errors.log'); $this->setParam(FileKeys::APPSERVER_ACCESS_LOG, ParamNode::TYPE_STRING, $logDir . 'appserver-access.log'); }
[ "protected", "function", "initDefaultFiles", "(", ")", "{", "$", "logDir", "=", "$", "this", "->", "getParam", "(", "DirectoryKeys", "::", "VAR_LOG", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "this", "->", "setParam", "(", "FileKeys", "::", "APPSERVER_ERRORS_...
Initialize the default files. @return void
[ "Initialize", "the", "default", "files", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php#L160-L165
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php
AppserverNode.initDefaultInitialContext
protected function initDefaultInitialContext() { // initialize the configuration values for the initial context $description = new DescriptionNode(new NodeValue('The initial context configuration.')); $storage = new StorageNode('AppserverIo\Storage\StackableStorage'); // set the default initial context configuration $this->initialContext = new InitialContextNode('AppserverIo\Appserver\Core\InitialContext', $description, $storage); }
php
protected function initDefaultInitialContext() { // initialize the configuration values for the initial context $description = new DescriptionNode(new NodeValue('The initial context configuration.')); $storage = new StorageNode('AppserverIo\Storage\StackableStorage'); // set the default initial context configuration $this->initialContext = new InitialContextNode('AppserverIo\Appserver\Core\InitialContext', $description, $storage); }
[ "protected", "function", "initDefaultInitialContext", "(", ")", "{", "// initialize the configuration values for the initial context", "$", "description", "=", "new", "DescriptionNode", "(", "new", "NodeValue", "(", "'The initial context configuration.'", ")", ")", ";", "$", ...
Initializes the default initial context configuration. @return void
[ "Initializes", "the", "default", "initial", "context", "configuration", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php#L172-L181
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php
AppserverNode.getContainer
public function getContainer($name) { // try to match one of the container names with the passed name /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $container */ foreach ($this->getContainers() as $container) { if (fnmatch($name, $container->getName())) { return $container; } } }
php
public function getContainer($name) { // try to match one of the container names with the passed name /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $container */ foreach ($this->getContainers() as $container) { if (fnmatch($name, $container->getName())) { return $container; } } }
[ "public", "function", "getContainer", "(", "$", "name", ")", "{", "// try to match one of the container names with the passed name", "/** @var \\AppserverIo\\Psr\\ApplicationServer\\Configuration\\ContainerConfigurationInterface $container */", "foreach", "(", "$", "this", "->", "getCo...
Returns the container with the passed name. @param string $name The name of the container to return @return \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface The container node matching the passed name
[ "Returns", "the", "container", "with", "the", "passed", "name", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php#L310-L319
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php
AppserverNode.getContainersAsArray
public function getContainersAsArray() { // initialize the array for the containers $containers = array(); // iterate over all found containers and assemble the array /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $container */ foreach ($this->getContainers() as $container) { $containers[$container->getName()] = $container; } // return the array with the containers return $containers; }
php
public function getContainersAsArray() { // initialize the array for the containers $containers = array(); // iterate over all found containers and assemble the array /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $container */ foreach ($this->getContainers() as $container) { $containers[$container->getName()] = $container; } // return the array with the containers return $containers; }
[ "public", "function", "getContainersAsArray", "(", ")", "{", "// initialize the array for the containers", "$", "containers", "=", "array", "(", ")", ";", "// iterate over all found containers and assemble the array", "/** @var \\AppserverIo\\Psr\\ApplicationServer\\Configuration\\Cont...
Returns the containers as array with the container name as key. @return array The array with the containers
[ "Returns", "the", "containers", "as", "array", "with", "the", "container", "name", "as", "key", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/AppserverNode.php#L326-L340
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/DatasourceService.php
DatasourceService.findAll
public function findAll() { $datasourceNodes = array(); foreach ($this->getSystemConfiguration()->getDatasources() as $datasourceNode) { $datasourceNodes[$datasourceNode->getPrimaryKey()] = $datasourceNode; } return $datasourceNodes; }
php
public function findAll() { $datasourceNodes = array(); foreach ($this->getSystemConfiguration()->getDatasources() as $datasourceNode) { $datasourceNodes[$datasourceNode->getPrimaryKey()] = $datasourceNode; } return $datasourceNodes; }
[ "public", "function", "findAll", "(", ")", "{", "$", "datasourceNodes", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getSystemConfiguration", "(", ")", "->", "getDatasources", "(", ")", "as", "$", "datasourceNode", ")", "{", "$", "dat...
Returns all deployed applications. @return array All deployed applications @see \AppserverIo\Psr\ApplicationServer\ServiceInterface::findAll()
[ "Returns", "all", "deployed", "applications", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DatasourceService.php#L44-L52
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/DatasourceService.php
DatasourceService.findAllByName
public function findAllByName($name) { $datasourceNodes = array(); foreach ($this->findAll() as $datasourceNode) { if ($datasourceNode->getName() === $name) { $datasourceNodes[$datasourceNode->getPrimaryKey()] = $datasourceNode; } } return $datasourceNodes; }
php
public function findAllByName($name) { $datasourceNodes = array(); foreach ($this->findAll() as $datasourceNode) { if ($datasourceNode->getName() === $name) { $datasourceNodes[$datasourceNode->getPrimaryKey()] = $datasourceNode; } } return $datasourceNodes; }
[ "public", "function", "findAllByName", "(", "$", "name", ")", "{", "$", "datasourceNodes", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "findAll", "(", ")", "as", "$", "datasourceNode", ")", "{", "if", "(", "$", "datasourceNode", "->...
Returns an array with the datasources with the passed name. @param string $name Name of the datasource to return @return array The datasources with the name passed as parameter
[ "Returns", "an", "array", "with", "the", "datasources", "with", "the", "passed", "name", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DatasourceService.php#L61-L71
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/DatasourceService.php
DatasourceService.findByName
public function findByName($name) { foreach ($this->findAll() as $datasourceNode) { if ($datasourceNode->getName() === $name) { return $datasourceNode; } } }
php
public function findByName($name) { foreach ($this->findAll() as $datasourceNode) { if ($datasourceNode->getName() === $name) { return $datasourceNode; } } }
[ "public", "function", "findByName", "(", "$", "name", ")", "{", "foreach", "(", "$", "this", "->", "findAll", "(", ")", "as", "$", "datasourceNode", ")", "{", "if", "(", "$", "datasourceNode", "->", "getName", "(", ")", "===", "$", "name", ")", "{", ...
Returns the datasource with the passed name. @param string $name Name of the datasource to return @return \AppserverIo\Psr\ApplicationServer\Configuration\DatasourceConfigurationInterface The datasource with the name passed as parameter
[ "Returns", "the", "datasource", "with", "the", "passed", "name", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DatasourceService.php#L80-L87
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/DatasourceService.php
DatasourceService.load
public function load($uuid) { foreach ($this->findAll() as $datasourceNode) { if ($datasourceNode->getPrimaryKey() == $uuid) { return $datasourceNode; } } }
php
public function load($uuid) { foreach ($this->findAll() as $datasourceNode) { if ($datasourceNode->getPrimaryKey() == $uuid) { return $datasourceNode; } } }
[ "public", "function", "load", "(", "$", "uuid", ")", "{", "foreach", "(", "$", "this", "->", "findAll", "(", ")", "as", "$", "datasourceNode", ")", "{", "if", "(", "$", "datasourceNode", "->", "getPrimaryKey", "(", ")", "==", "$", "uuid", ")", "{", ...
Returns the datasource with the passed UUID. @param string $uuid UUID of the datasource to return @return \AppserverIo\Psr\ApplicationServer\Configuration\DatasourceConfigurationInterface The datasource with the UUID passed as parameter @see \AppserverIo\Psr\ApplicationServer\ServiceInterface::load()
[ "Returns", "the", "datasource", "with", "the", "passed", "UUID", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DatasourceService.php#L97-L104
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/DatasourceService.php
DatasourceService.persist
public function persist(NodeInterface $datasourceNode) { $systemConfiguration = $this->getSystemConfiguration(); $systemConfiguration->attachDatasource($datasourceNode); $this->setSystemConfiguration($systemConfiguration); }
php
public function persist(NodeInterface $datasourceNode) { $systemConfiguration = $this->getSystemConfiguration(); $systemConfiguration->attachDatasource($datasourceNode); $this->setSystemConfiguration($systemConfiguration); }
[ "public", "function", "persist", "(", "NodeInterface", "$", "datasourceNode", ")", "{", "$", "systemConfiguration", "=", "$", "this", "->", "getSystemConfiguration", "(", ")", ";", "$", "systemConfiguration", "->", "attachDatasource", "(", "$", "datasourceNode", "...
Persists the passed datasource. @param \AppserverIo\Configuration\Interfaces\NodeInterface $datasourceNode The datasource to persist @return void
[ "Persists", "the", "passed", "datasource", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DatasourceService.php#L113-L118
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/Doctrine/EntityManagerFactory.php
EntityManagerFactory.factory
public function factory() { // register additional annotation libraries foreach ($this->persistenceUnitNode->getAnnotationRegistries() as $annotationRegistry) { AnnotationRegistry::registerAutoloadNamespace( $annotationRegistry->getNamespace(), $annotationRegistry->getDirectoriesAsArray($this->application->getWebappPath()) ); } // globally ignore configured annotations to ignore foreach ($this->persistenceUnitNode->getIgnoredAnnotations() as $ignoredAnnotation) { AnnotationReader::addGlobalIgnoredName($ignoredAnnotation->getNodeValue()->__toString()); } // load the metadata configuration $metadataConfiguration = $this->persistenceUnitNode->getMetadataConfiguration(); // prepare the setup properties $absolutePaths = $metadataConfiguration->getDirectoriesAsArray($this->application->getWebappPath()); $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_PROXY_DIR); $isDevMode = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_IS_DEV_MODE); $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationInterface::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 ($this->application->getInitialContext()->getSystemConfiguration()->getDatasources() as $datasourceNode) { if ($datasourceNode->getName() === $this->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', $this->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', $this->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', $this->persistenceUnitNode->getName() ) ); } // initialize and return a entity manager decorator instance return new DoctrineEntityManagerDecorator( EntityManager::create(ConnectionUtil::get($this->application)->fromDatabaseNode($databaseNode), $configuration) ); }
php
public function factory() { // register additional annotation libraries foreach ($this->persistenceUnitNode->getAnnotationRegistries() as $annotationRegistry) { AnnotationRegistry::registerAutoloadNamespace( $annotationRegistry->getNamespace(), $annotationRegistry->getDirectoriesAsArray($this->application->getWebappPath()) ); } // globally ignore configured annotations to ignore foreach ($this->persistenceUnitNode->getIgnoredAnnotations() as $ignoredAnnotation) { AnnotationReader::addGlobalIgnoredName($ignoredAnnotation->getNodeValue()->__toString()); } // load the metadata configuration $metadataConfiguration = $this->persistenceUnitNode->getMetadataConfiguration(); // prepare the setup properties $absolutePaths = $metadataConfiguration->getDirectoriesAsArray($this->application->getWebappPath()); $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_PROXY_DIR); $isDevMode = $metadataConfiguration->getParam(MetadataConfigurationInterface::PARAM_IS_DEV_MODE); $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationInterface::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 ($this->application->getInitialContext()->getSystemConfiguration()->getDatasources() as $datasourceNode) { if ($datasourceNode->getName() === $this->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', $this->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', $this->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', $this->persistenceUnitNode->getName() ) ); } // initialize and return a entity manager decorator instance return new DoctrineEntityManagerDecorator( EntityManager::create(ConnectionUtil::get($this->application)->fromDatabaseNode($databaseNode), $configuration) ); }
[ "public", "function", "factory", "(", ")", "{", "// register additional annotation libraries", "foreach", "(", "$", "this", "->", "persistenceUnitNode", "->", "getAnnotationRegistries", "(", ")", "as", "$", "annotationRegistry", ")", "{", "AnnotationRegistry", "::", "...
Creates a new entity manager instance based on the passed configuration. @return object The entity manager instance
[ "Creates", "a", "new", "entity", "manager", "instance", "based", "on", "the", "passed", "configuration", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/Doctrine/EntityManagerFactory.php#L85-L164
appserver-io/appserver
src/AppserverIo/Appserver/Core/ComposerClassLoaderFactory.php
ComposerClassLoaderFactory.visit
public static function visit(ApplicationInterface $application, ClassLoaderNodeInterface $configuration) { // initialize the array with the configured directories $directories = array(); // load the composer class loader for the configured directories /** @var \AppserverIo\Appserver\Core\Api\Node\DirectoryNode $directory */ foreach ($configuration->getDirectories() as $directory) { // we prepare the directories to include scripts AFTER registering (in application context) $directories[] = $directory->getNodeValue(); // check if an autoload.php is available if (file_exists($directory->getNodeValue() . DIRECTORY_SEPARATOR . 'autoload.php')) { // if yes, we try to instanciate a new class loader instance $classLoader = new ComposerClassLoader($directories); // set the composer include paths if (file_exists($directory->getNodeValue() . '/composer/include_paths.php')) { $includePaths = require $directory->getNodeValue() . '/composer/include_paths.php'; array_push($includePaths, get_include_path()); set_include_path(join(PATH_SEPARATOR, $includePaths)); } // add the composer namespace declarations if (file_exists($directory->getNodeValue() . '/composer/autoload_namespaces.php')) { $map = require $directory->getNodeValue() . '/composer/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $classLoader->set($namespace, $path); } } // add the composer PSR-4 compatible namespace declarations if (file_exists($directory->getNodeValue() . '/composer/autoload_psr4.php')) { $map = require $directory->getNodeValue() . '/composer/autoload_psr4.php'; foreach ($map as $namespace => $path) { $classLoader->setPsr4($namespace, $path); } } // add the composer class map if (file_exists($directory->getNodeValue() . '/composer/autoload_classmap.php')) { $classMap = require $directory->getNodeValue() . '/composer/autoload_classmap.php'; if ($classMap) { $classLoader->addClassMap($classMap); } } // attach the class loader instance $application->addClassLoader($classLoader, $configuration); } } }
php
public static function visit(ApplicationInterface $application, ClassLoaderNodeInterface $configuration) { // initialize the array with the configured directories $directories = array(); // load the composer class loader for the configured directories /** @var \AppserverIo\Appserver\Core\Api\Node\DirectoryNode $directory */ foreach ($configuration->getDirectories() as $directory) { // we prepare the directories to include scripts AFTER registering (in application context) $directories[] = $directory->getNodeValue(); // check if an autoload.php is available if (file_exists($directory->getNodeValue() . DIRECTORY_SEPARATOR . 'autoload.php')) { // if yes, we try to instanciate a new class loader instance $classLoader = new ComposerClassLoader($directories); // set the composer include paths if (file_exists($directory->getNodeValue() . '/composer/include_paths.php')) { $includePaths = require $directory->getNodeValue() . '/composer/include_paths.php'; array_push($includePaths, get_include_path()); set_include_path(join(PATH_SEPARATOR, $includePaths)); } // add the composer namespace declarations if (file_exists($directory->getNodeValue() . '/composer/autoload_namespaces.php')) { $map = require $directory->getNodeValue() . '/composer/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $classLoader->set($namespace, $path); } } // add the composer PSR-4 compatible namespace declarations if (file_exists($directory->getNodeValue() . '/composer/autoload_psr4.php')) { $map = require $directory->getNodeValue() . '/composer/autoload_psr4.php'; foreach ($map as $namespace => $path) { $classLoader->setPsr4($namespace, $path); } } // add the composer class map if (file_exists($directory->getNodeValue() . '/composer/autoload_classmap.php')) { $classMap = require $directory->getNodeValue() . '/composer/autoload_classmap.php'; if ($classMap) { $classLoader->addClassMap($classMap); } } // attach the class loader instance $application->addClassLoader($classLoader, $configuration); } } }
[ "public", "static", "function", "visit", "(", "ApplicationInterface", "$", "application", ",", "ClassLoaderNodeInterface", "$", "configuration", ")", "{", "// initialize the array with the configured directories", "$", "directories", "=", "array", "(", ")", ";", "// load ...
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
[ "Visitor", "method", "that", "registers", "the", "class", "loaders", "in", "the", "application", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/ComposerClassLoaderFactory.php#L47-L99
appserver-io/appserver
src/AppserverIo/Appserver/Core/InitialContext.php
InitialContext.newInstance
public function newInstance($className, array $args = array()) { // create and return a new instance $reflectionClass = $this->newReflectionClass($className); return $reflectionClass->newInstanceArgs($args); }
php
public function newInstance($className, array $args = array()) { // create and return a new instance $reflectionClass = $this->newReflectionClass($className); return $reflectionClass->newInstanceArgs($args); }
[ "public", "function", "newInstance", "(", "$", "className", ",", "array", "$", "args", "=", "array", "(", ")", ")", "{", "// create and return a new instance", "$", "reflectionClass", "=", "$", "this", "->", "newReflectionClass", "(", "$", "className", ")", ";...
Returns a new instance of the passed class name. @param string $className The fully qualified class name to return the instance for @param array $args Arguments to pass to the constructor of the instance @return object The instance itself
[ "Returns", "a", "new", "instance", "of", "the", "passed", "class", "name", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/InitialContext.php#L193-L198
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/TimerServiceExecutor.php
TimerServiceExecutor.schedule
public function schedule(TimerInterface $timer) { // force handling the timer tasks now $this->synchronized(function (TimerInterface $t) { // store the timer-ID and the PK of the timer service => necessary to load the timer later $this->scheduledTimers[$timerId = $t->getId()] = $t->getTimerService()->getPrimaryKey(); // create a wrapper instance for the timer task that we want to schedule $timerTaskWrapper = new \stdClass(); $timerTaskWrapper->executeAt = microtime(true) + ($t->getTimeRemaining() / 1000000); $timerTaskWrapper->taskId = uniqid(); $timerTaskWrapper->timerId = $timerId; // schedule the timer tasks as wrapper $this->tasksToExecute[$timerTaskWrapper->taskId] = $timerTaskWrapper; }, $timer); }
php
public function schedule(TimerInterface $timer) { // force handling the timer tasks now $this->synchronized(function (TimerInterface $t) { // store the timer-ID and the PK of the timer service => necessary to load the timer later $this->scheduledTimers[$timerId = $t->getId()] = $t->getTimerService()->getPrimaryKey(); // create a wrapper instance for the timer task that we want to schedule $timerTaskWrapper = new \stdClass(); $timerTaskWrapper->executeAt = microtime(true) + ($t->getTimeRemaining() / 1000000); $timerTaskWrapper->taskId = uniqid(); $timerTaskWrapper->timerId = $timerId; // schedule the timer tasks as wrapper $this->tasksToExecute[$timerTaskWrapper->taskId] = $timerTaskWrapper; }, $timer); }
[ "public", "function", "schedule", "(", "TimerInterface", "$", "timer", ")", "{", "// force handling the timer tasks now", "$", "this", "->", "synchronized", "(", "function", "(", "TimerInterface", "$", "t", ")", "{", "// store the timer-ID and the PK of the timer service ...
Adds the passed timer task to the schedule. @param \AppserverIo\Psr\EnterpriseBeans\TimerInterface $timer The timer we want to schedule @return void
[ "Adds", "the", "passed", "timer", "task", "to", "the", "schedule", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/TimerServiceExecutor.php#L136-L155
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/TimerServiceExecutor.php
TimerServiceExecutor.collectGarbage
public function collectGarbage() { $this->synchronized(function () { foreach ($this->timerTasks as $taskId => $timerTask) { if ($timerTask->isRunning()) { continue; } else { unset($this->timerTasks[$taskId]); } } }); }
php
public function collectGarbage() { $this->synchronized(function () { foreach ($this->timerTasks as $taskId => $timerTask) { if ($timerTask->isRunning()) { continue; } else { unset($this->timerTasks[$taskId]); } } }); }
[ "public", "function", "collectGarbage", "(", ")", "{", "$", "this", "->", "synchronized", "(", "function", "(", ")", "{", "foreach", "(", "$", "this", "->", "timerTasks", "as", "$", "taskId", "=>", "$", "timerTask", ")", "{", "if", "(", "$", "timerTask...
Collect the finished timer task jobs. @return void
[ "Collect", "the", "finished", "timer", "task", "jobs", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/TimerServiceExecutor.php#L195-L206
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/TimerServiceExecutor.php
TimerServiceExecutor.iterate
public function iterate($timeout) { // call parent method and sleep for the default timeout parent::iterate($timeout); // iterate over the timer tasks that has to be executed foreach ($this->tasksToExecute as $taskId => $timerTaskWrapper) { // this should never happen if (!$timerTaskWrapper instanceof \stdClass) { // log an error message because we task wrapper has wrong type \error(sprintf('Timer-Task-Wrapper %s has wrong type %s', $taskId, get_class($timerTaskWrapper))); // we didn't foud a timer task ignore this continue; } // query if the task has to be executed now if ($timerTaskWrapper->executeAt < microtime(true)) { // load the timer task wrapper we want to execute if ($pk = $this->scheduledTimers[$timerId = $timerTaskWrapper->timerId]) { // load the timer service registry $timerServiceRegistry = $this->getApplication()->search(TimerServiceContextInterface::IDENTIFIER); // lookup the timer from the timer service $timer = $timerServiceRegistry->lookup($pk)->getTimers()->get($timerId); // create and execute the timer task $this->timerTasks[$taskId] = $timer->getTimerTask($this->getApplication()); // remove the key from the list of tasks to be executed unset($this->tasksToExecute[$taskId]); } else { // log an error message because we can't find the timer instance \error(sprintf('Can\'t find timer %s to create timer task %s', $timerTaskWrapper->timerId, $taskId)); } } } // collect the garbage (finished timer task jobs) $this->collectGarbage(); // profile the size of the timer tasks to be executed if ($this->profileLogger) { $this->profileLogger->debug( sprintf('Processed timer service executor, executing %d timer tasks', sizeof($this->tasksToExecute)) ); } }
php
public function iterate($timeout) { // call parent method and sleep for the default timeout parent::iterate($timeout); // iterate over the timer tasks that has to be executed foreach ($this->tasksToExecute as $taskId => $timerTaskWrapper) { // this should never happen if (!$timerTaskWrapper instanceof \stdClass) { // log an error message because we task wrapper has wrong type \error(sprintf('Timer-Task-Wrapper %s has wrong type %s', $taskId, get_class($timerTaskWrapper))); // we didn't foud a timer task ignore this continue; } // query if the task has to be executed now if ($timerTaskWrapper->executeAt < microtime(true)) { // load the timer task wrapper we want to execute if ($pk = $this->scheduledTimers[$timerId = $timerTaskWrapper->timerId]) { // load the timer service registry $timerServiceRegistry = $this->getApplication()->search(TimerServiceContextInterface::IDENTIFIER); // lookup the timer from the timer service $timer = $timerServiceRegistry->lookup($pk)->getTimers()->get($timerId); // create and execute the timer task $this->timerTasks[$taskId] = $timer->getTimerTask($this->getApplication()); // remove the key from the list of tasks to be executed unset($this->tasksToExecute[$taskId]); } else { // log an error message because we can't find the timer instance \error(sprintf('Can\'t find timer %s to create timer task %s', $timerTaskWrapper->timerId, $taskId)); } } } // collect the garbage (finished timer task jobs) $this->collectGarbage(); // profile the size of the timer tasks to be executed if ($this->profileLogger) { $this->profileLogger->debug( sprintf('Processed timer service executor, executing %d timer tasks', sizeof($this->tasksToExecute)) ); } }
[ "public", "function", "iterate", "(", "$", "timeout", ")", "{", "// call parent method and sleep for the default timeout", "parent", "::", "iterate", "(", "$", "timeout", ")", ";", "// iterate over the timer tasks that has to be executed", "foreach", "(", "$", "this", "->...
This is invoked on every iteration of the daemons while() loop. @param integer $timeout The timeout before the daemon wakes up @return void
[ "This", "is", "invoked", "on", "every", "iteration", "of", "the", "daemons", "while", "()", "loop", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/TimerServiceExecutor.php#L216-L264
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/TimerServiceExecutor.php
TimerServiceExecutor.sleep
public function sleep($timeout) { $this->synchronized(function ($self) use ($timeout) { $self->wait($timeout); }, $this); }
php
public function sleep($timeout) { $this->synchronized(function ($self) use ($timeout) { $self->wait($timeout); }, $this); }
[ "public", "function", "sleep", "(", "$", "timeout", ")", "{", "$", "this", "->", "synchronized", "(", "function", "(", "$", "self", ")", "use", "(", "$", "timeout", ")", "{", "$", "self", "->", "wait", "(", "$", "timeout", ")", ";", "}", ",", "$"...
Let the daemon sleep for the passed value of miroseconds. @param integer $timeout The number of microseconds to sleep @return void
[ "Let", "the", "daemon", "sleep", "for", "the", "passed", "value", "of", "miroseconds", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/TimerServiceExecutor.php#L287-L292
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/ServiceLocator.php
ServiceLocator.lookup
public function lookup(ServiceContextInterface $serviceContext, $serviceIdentifier, array $args = array()) { // first check if the service is available if ($serviceContext->getServices()->has($serviceIdentifier) === false) { throw new EnterpriseBeansException( sprintf( 'Requested service %s to handle %s is not available', $serviceContext->getIdentifier(), $serviceIdentifier ) ); } // return the initialized service instance return $serviceContext->getServices()->get($serviceIdentifier); }
php
public function lookup(ServiceContextInterface $serviceContext, $serviceIdentifier, array $args = array()) { // first check if the service is available if ($serviceContext->getServices()->has($serviceIdentifier) === false) { throw new EnterpriseBeansException( sprintf( 'Requested service %s to handle %s is not available', $serviceContext->getIdentifier(), $serviceIdentifier ) ); } // return the initialized service instance return $serviceContext->getServices()->get($serviceIdentifier); }
[ "public", "function", "lookup", "(", "ServiceContextInterface", "$", "serviceContext", ",", "$", "serviceIdentifier", ",", "array", "$", "args", "=", "array", "(", ")", ")", "{", "// first check if the service is available", "if", "(", "$", "serviceContext", "->", ...
Tries to lookup the service with the passed identifier. @param \AppserverIo\Psr\EnterpriseBeans\ServiceContextInterface $serviceContext The service context instance @param string $serviceIdentifier The identifier of the service to be looked up @param array $args The arguments passed to the service providers constructor @return \AppserverIo\Psr\EnterpriseBeans\ServiceProviderInterface The requested service provider instance @throws \AppserverIo\Psr\EnterpriseBeans\EnterpriseBeansException Is thrown if the requested server can't be lookup up @see \AppserverIo\Psr\EnterpriseBeans\ServiceResourceLocatorInterface::lookup()
[ "Tries", "to", "lookup", "the", "service", "with", "the", "passed", "identifier", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/ServiceLocator.php#L50-L66
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/Tasks/CalendarTimerTask.php
CalendarTimerTask.callTimeout
protected function callTimeout(TimerInterface $timer) { // if we have any more schedules remaining, then schedule a new task if ($timer->getNextExpiration() != null && !$timer->isInRetry()) { $timer->scheduleTimeout(false); } // finally invoke the timeout method through the invoker if ($timer->isAutoTimer()) { $timer->getTimerService()->getTimedObjectInvoker()->callTimeout($timer, $timer->getTimeoutMethod()); } else { $timer->getTimerService()->getTimedObjectInvoker()->callTimeout($timer); } }
php
protected function callTimeout(TimerInterface $timer) { // if we have any more schedules remaining, then schedule a new task if ($timer->getNextExpiration() != null && !$timer->isInRetry()) { $timer->scheduleTimeout(false); } // finally invoke the timeout method through the invoker if ($timer->isAutoTimer()) { $timer->getTimerService()->getTimedObjectInvoker()->callTimeout($timer, $timer->getTimeoutMethod()); } else { $timer->getTimerService()->getTimedObjectInvoker()->callTimeout($timer); } }
[ "protected", "function", "callTimeout", "(", "TimerInterface", "$", "timer", ")", "{", "// if we have any more schedules remaining, then schedule a new task", "if", "(", "$", "timer", "->", "getNextExpiration", "(", ")", "!=", "null", "&&", "!", "$", "timer", "->", ...
Invokes the timeout on the passed timer. @param \AppserverIo\Psr\EnterpriseBeans\TimerInterface $timer The timer we want to invoke the timeout for @return void
[ "Invokes", "the", "timeout", "on", "the", "passed", "timer", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/Tasks/CalendarTimerTask.php#L44-L58
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/CalendarTimerFactory.php
CalendarTimerFactory.createTimer
public function createTimer(TimerServiceInterface $timerService, ScheduleExpression $schedule, \Serializable $info = null, $persistent = true, MethodInterface $timeoutMethod = null) { // lock the method \Mutex::lock($this->mutex); // we're not dispatched $this->dispatched = false; // initialize the data $this->info = $info; $this->schedule = $schedule; $this->persistent = $persistent; $this->timerService = $timerService; $this->timeoutMethod = $timeoutMethod; // notify the thread $this->notify(); // wait till we've dispatched the request while ($this->dispatched === false) { usleep(100); } // unlock the method \Mutex::unlock($this->mutex); // return the created timer return $this->timer; }
php
public function createTimer(TimerServiceInterface $timerService, ScheduleExpression $schedule, \Serializable $info = null, $persistent = true, MethodInterface $timeoutMethod = null) { // lock the method \Mutex::lock($this->mutex); // we're not dispatched $this->dispatched = false; // initialize the data $this->info = $info; $this->schedule = $schedule; $this->persistent = $persistent; $this->timerService = $timerService; $this->timeoutMethod = $timeoutMethod; // notify the thread $this->notify(); // wait till we've dispatched the request while ($this->dispatched === false) { usleep(100); } // unlock the method \Mutex::unlock($this->mutex); // return the created timer return $this->timer; }
[ "public", "function", "createTimer", "(", "TimerServiceInterface", "$", "timerService", ",", "ScheduleExpression", "$", "schedule", ",", "\\", "Serializable", "$", "info", "=", "null", ",", "$", "persistent", "=", "true", ",", "MethodInterface", "$", "timeoutMetho...
Create a calendar-based timer based on the input schedule expression. @param \AppserverIo\Psr\EnterpriseBeans\TimerServiceInterface $timerService The timer service to create the service for @param \AppserverIo\Psr\EnterpriseBeans\ScheduleExpression $schedule A schedule expression describing the timeouts for this timer @param \Serializable $info Serializable info that will be made available through the newly created timers Timer::getInfo() method @param boolean $persistent TRUE if the newly created timer has to be persistent @param \AppserverIo\Lang\Reflection\MethodInterface $timeoutMethod The timeout method to be invoked @return \AppserverIo\Psr\EnterpriseBeans\TimerInterface The newly created Timer. @throws \AppserverIo\Psr\EnterpriseBeans\EnterpriseBeansException If this method could not complete due to a system-level failure. @throws \Exception
[ "Create", "a", "calendar", "-", "based", "timer", "based", "on", "the", "input", "schedule", "expression", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/CalendarTimerFactory.php#L96-L125
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/CalendarTimerFactory.php
CalendarTimerFactory.iterate
public function iterate($timeout) { // call parent method and sleep for the default timeout parent::iterate($timeout); // create the requested timer instance $this->synchronized(function ($self) { // create the calendar timer, only if we're NOT dispatched if ($self->dispatched === false) { $self->timer = CalendarTimer::builder() ->setAutoTimer($self->timeoutMethod != null) ->setScheduleExprSecond($self->schedule->getSecond()) ->setScheduleExprMinute($self->schedule->getMinute()) ->setScheduleExprHour($self->schedule->getHour()) ->setScheduleExprDayOfWeek($self->schedule->getDayOfWeek()) ->setScheduleExprDayOfMonth($self->schedule->getDayOfMonth()) ->setScheduleExprMonth($self->schedule->getMonth()) ->setScheduleExprYear($self->schedule->getYear()) ->setScheduleExprStartDate($self->schedule->getStart()) ->setScheduleExprEndDate($self->schedule->getEnd()) ->setScheduleExprTimezone($self->schedule->getTimezone()) ->setTimeoutMethod($self->timeoutMethod) ->setTimerState(TimerState::CREATED) ->setId(Uuid::uuid4()->__toString()) ->setPersistent($self->persistent) ->setTimedObjectId($self->timerService->getTimedObjectInvoker()->getTimedObjectId()) ->setInfo($self->info) ->setNewTimer(true) ->build($self->timerService); // we're dispatched now $self->dispatched = true; } }, $this); // profile the size of the sessions if ($this->profileLogger) { $this->profileLogger->debug( sprintf('Size of session pool is: %d', sizeof($this->sessionPool)) ); } }
php
public function iterate($timeout) { // call parent method and sleep for the default timeout parent::iterate($timeout); // create the requested timer instance $this->synchronized(function ($self) { // create the calendar timer, only if we're NOT dispatched if ($self->dispatched === false) { $self->timer = CalendarTimer::builder() ->setAutoTimer($self->timeoutMethod != null) ->setScheduleExprSecond($self->schedule->getSecond()) ->setScheduleExprMinute($self->schedule->getMinute()) ->setScheduleExprHour($self->schedule->getHour()) ->setScheduleExprDayOfWeek($self->schedule->getDayOfWeek()) ->setScheduleExprDayOfMonth($self->schedule->getDayOfMonth()) ->setScheduleExprMonth($self->schedule->getMonth()) ->setScheduleExprYear($self->schedule->getYear()) ->setScheduleExprStartDate($self->schedule->getStart()) ->setScheduleExprEndDate($self->schedule->getEnd()) ->setScheduleExprTimezone($self->schedule->getTimezone()) ->setTimeoutMethod($self->timeoutMethod) ->setTimerState(TimerState::CREATED) ->setId(Uuid::uuid4()->__toString()) ->setPersistent($self->persistent) ->setTimedObjectId($self->timerService->getTimedObjectInvoker()->getTimedObjectId()) ->setInfo($self->info) ->setNewTimer(true) ->build($self->timerService); // we're dispatched now $self->dispatched = true; } }, $this); // profile the size of the sessions if ($this->profileLogger) { $this->profileLogger->debug( sprintf('Size of session pool is: %d', sizeof($this->sessionPool)) ); } }
[ "public", "function", "iterate", "(", "$", "timeout", ")", "{", "// call parent method and sleep for the default timeout", "parent", "::", "iterate", "(", "$", "timeout", ")", ";", "// create the requested timer instance", "$", "this", "->", "synchronized", "(", "functi...
This is invoked on every iteration of the daemons while() loop. @param integer $timeout The timeout before the daemon wakes up @return void
[ "This", "is", "invoked", "on", "every", "iteration", "of", "the", "daemons", "while", "()", "loop", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/CalendarTimerFactory.php#L160-L204
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/CalendarTimerFactory.php
CalendarTimerFactory.log
public function log($level, $message, array $context = array()) { $this->getApplication()->getInitialContext()->getSystemLogger()->log($level, $message, $context); }
php
public function log($level, $message, array $context = array()) { $this->getApplication()->getInitialContext()->getSystemLogger()->log($level, $message, $context); }
[ "public", "function", "log", "(", "$", "level", ",", "$", "message", ",", "array", "$", "context", "=", "array", "(", ")", ")", "{", "$", "this", "->", "getApplication", "(", ")", "->", "getInitialContext", "(", ")", "->", "getSystemLogger", "(", ")", ...
This is a very basic method to log some stuff by using the error_log() method of PHP. @param mixed $level The log level to use @param string $message The message we want to log @param array $context The context we of the message @return void
[ "This", "is", "a", "very", "basic", "method", "to", "log", "some", "stuff", "by", "using", "the", "error_log", "()", "method", "of", "PHP", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/CalendarTimerFactory.php#L229-L232
appserver-io/appserver
src/AppserverIo/Appserver/MessageQueue/Job.php
Job.run
public function run() { // register the default autoloader require SERVER_AUTOLOADER; // register shutdown handler register_shutdown_function(array(&$this, "shutdown")); // we need to register the class loaders again $application = $this->application; $application->registerClassLoaders(); // register the applications annotation registries $application->registerAnnotationRegistries(); // add the application instance to the environment Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $application); // create s simulated request/session ID whereas session equals request ID Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $sessionId = SessionUtils::generateRandomString()); Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $sessionId); // load application and message instance $message = $this->message; try { // load class name and session ID from remote method $queueProxy = $message->getDestination(); $sessionId = $message->getSessionId(); // lookup the queue and process the message if ($queue = $application->search(QueueContextInterface::IDENTIFIER)->locate($queueProxy)) { // the queues receiver type $queueType = $queue->getType(); // create an intial context instance $initialContext = new InitialContext(); $initialContext->injectApplication($application); // lookup the bean instance $instance = $initialContext->lookup($queueType); // inject the application to the receiver and process the message $instance->onMessage($message, $sessionId); // set the new message state to processed $message->setState(StateProcessed::get()); } } catch (\Exception $e) { // log the exception \error($e->__toString()); // set the message state to failed $message->setState(StateFailed::get()); } // mark the job finished $this->finished = true; // set the message back to the global context $this->message = $message; }
php
public function run() { // register the default autoloader require SERVER_AUTOLOADER; // register shutdown handler register_shutdown_function(array(&$this, "shutdown")); // we need to register the class loaders again $application = $this->application; $application->registerClassLoaders(); // register the applications annotation registries $application->registerAnnotationRegistries(); // add the application instance to the environment Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $application); // create s simulated request/session ID whereas session equals request ID Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $sessionId = SessionUtils::generateRandomString()); Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $sessionId); // load application and message instance $message = $this->message; try { // load class name and session ID from remote method $queueProxy = $message->getDestination(); $sessionId = $message->getSessionId(); // lookup the queue and process the message if ($queue = $application->search(QueueContextInterface::IDENTIFIER)->locate($queueProxy)) { // the queues receiver type $queueType = $queue->getType(); // create an intial context instance $initialContext = new InitialContext(); $initialContext->injectApplication($application); // lookup the bean instance $instance = $initialContext->lookup($queueType); // inject the application to the receiver and process the message $instance->onMessage($message, $sessionId); // set the new message state to processed $message->setState(StateProcessed::get()); } } catch (\Exception $e) { // log the exception \error($e->__toString()); // set the message state to failed $message->setState(StateFailed::get()); } // mark the job finished $this->finished = true; // set the message back to the global context $this->message = $message; }
[ "public", "function", "run", "(", ")", "{", "// register the default autoloader", "require", "SERVER_AUTOLOADER", ";", "// register shutdown handler", "register_shutdown_function", "(", "array", "(", "&", "$", "this", ",", "\"shutdown\"", ")", ")", ";", "// we need to r...
We process the timer here. @return void
[ "We", "process", "the", "timer", "here", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/MessageQueue/Job.php#L101-L163
appserver-io/appserver
src/AppserverIo/Appserver/Core/Listeners/DeployApplicationsListener.php
DeployApplicationsListener.handle
public function handle(EventInterface $event) { try { // load the application server and the naming directory instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */ $namingDirectory = $applicationServer->getNamingDirectory(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // deploy the applications for all containers /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */ foreach ($applicationServer->getSystemConfiguration()->getContainers() as $containerNode) { // load the container instance to deploy the applications for /** @var \AppserverIo\Psr\ApplicationServer\ContainerInterface $container */ $container = $namingDirectory->search( sprintf( 'php:services/%s/%s', $applicationServer->runlevelToString(ApplicationServerInterface::NETWORK), $containerNode->getName() ) ); // load the containers deployment /** @var \AppserverIo\Psr\Deployment\DeploymentInterface $deployment */ $deployment = $container->getDeployment(); $deployment->injectContainer($container); // deploy and initialize the container's applications $deployment->deploy(); } } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
php
public function handle(EventInterface $event) { try { // load the application server and the naming directory instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */ $namingDirectory = $applicationServer->getNamingDirectory(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // deploy the applications for all containers /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */ foreach ($applicationServer->getSystemConfiguration()->getContainers() as $containerNode) { // load the container instance to deploy the applications for /** @var \AppserverIo\Psr\ApplicationServer\ContainerInterface $container */ $container = $namingDirectory->search( sprintf( 'php:services/%s/%s', $applicationServer->runlevelToString(ApplicationServerInterface::NETWORK), $containerNode->getName() ) ); // load the containers deployment /** @var \AppserverIo\Psr\Deployment\DeploymentInterface $deployment */ $deployment = $container->getDeployment(); $deployment->injectContainer($container); // deploy and initialize the container's applications $deployment->deploy(); } } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
[ "public", "function", "handle", "(", "EventInterface", "$", "event", ")", "{", "try", "{", "// load the application server and the naming directory instance", "/** @var \\AppserverIo\\Psr\\ApplicationServer\\ApplicationServerInterface $applicationServer */", "$", "applicationServer", "...
Handle an event. @param \League\Event\EventInterface $event The triggering event @return void @see \League\Event\ListenerInterface::handle()
[ "Handle", "an", "event", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Listeners/DeployApplicationsListener.php#L46-L84
appserver-io/appserver
src/AppserverIo/Appserver/Server/Contexts/StandardServerContext.php
StandardServerContext.hasLogger
public function hasLogger($loggerType) { try { $this->getContainer()->getNamingDirectory()->search(sprintf('php:global/log/%s', $loggerType)); return true; } catch (NamingException $ne) { return false; } }
php
public function hasLogger($loggerType) { try { $this->getContainer()->getNamingDirectory()->search(sprintf('php:global/log/%s', $loggerType)); return true; } catch (NamingException $ne) { return false; } }
[ "public", "function", "hasLogger", "(", "$", "loggerType", ")", "{", "try", "{", "$", "this", "->", "getContainer", "(", ")", "->", "getNamingDirectory", "(", ")", "->", "search", "(", "sprintf", "(", "'php:global/log/%s'", ",", "$", "loggerType", ")", ")"...
Queries if the requested logger type is registered or not. @param string $loggerType The logger type we want to query @return boolean TRUE if the logger is registered, else FALSE
[ "Queries", "if", "the", "requested", "logger", "type", "is", "registered", "or", "not", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Server/Contexts/StandardServerContext.php#L47-L55
appserver-io/appserver
src/AppserverIo/Appserver/Server/Contexts/StandardServerContext.php
StandardServerContext.getLogger
public function getLogger($loggerType = self::DEFAULT_LOGGER_TYPE) { try { return $this->getContainer()->getNamingDirectory()->search(sprintf('php:global/log/%s', $loggerType)); } catch (NamingException $ne) { throw new ServerException("Logger name '$loggerType' does not exist.", 500); } }
php
public function getLogger($loggerType = self::DEFAULT_LOGGER_TYPE) { try { return $this->getContainer()->getNamingDirectory()->search(sprintf('php:global/log/%s', $loggerType)); } catch (NamingException $ne) { throw new ServerException("Logger name '$loggerType' does not exist.", 500); } }
[ "public", "function", "getLogger", "(", "$", "loggerType", "=", "self", "::", "DEFAULT_LOGGER_TYPE", ")", "{", "try", "{", "return", "$", "this", "->", "getContainer", "(", ")", "->", "getNamingDirectory", "(", ")", "->", "search", "(", "sprintf", "(", "'p...
Returns the logger instance with the passed type. @param string $loggerType The requested logger's type @return \Psr\Log\LoggerInterface The logger instance @throws \AppserverIo\Server\Exceptions\ServerException
[ "Returns", "the", "logger", "instance", "with", "the", "passed", "type", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Server/Contexts/StandardServerContext.php#L65-L72
appserver-io/appserver
src/AppserverIo/Appserver/Core/Listeners/LoadLoggersListener.php
LoadLoggersListener.handle
public function handle(EventInterface $event) { try { // load the application server, naming directory and system configuration instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */ $namingDirectory = $applicationServer->getNamingDirectory(); /** @var \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface $systemConfiguration */ $systemConfiguration = $applicationServer->getSystemConfiguration(); // initialize the loggers $loggers = array(); foreach ($systemConfiguration->getLoggers() as $loggerNode) { $loggers[$loggerNode->getName()] = LoggerFactory::factory($loggerNode); } // register the logger callbacks in the naming directory foreach ($loggers as $name => $logger) { $namingDirectory->bind(sprintf('php:global/log/%s', $name), $logger); } // set the initialized loggers finally $applicationServer->setLoggers($loggers); } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
php
public function handle(EventInterface $event) { try { // load the application server, naming directory and system configuration instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */ $namingDirectory = $applicationServer->getNamingDirectory(); /** @var \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface $systemConfiguration */ $systemConfiguration = $applicationServer->getSystemConfiguration(); // initialize the loggers $loggers = array(); foreach ($systemConfiguration->getLoggers() as $loggerNode) { $loggers[$loggerNode->getName()] = LoggerFactory::factory($loggerNode); } // register the logger callbacks in the naming directory foreach ($loggers as $name => $logger) { $namingDirectory->bind(sprintf('php:global/log/%s', $name), $logger); } // set the initialized loggers finally $applicationServer->setLoggers($loggers); } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
[ "public", "function", "handle", "(", "EventInterface", "$", "event", ")", "{", "try", "{", "// load the application server, naming directory and system configuration instance", "/** @var \\AppserverIo\\Psr\\ApplicationServer\\ApplicationServerInterface $applicationServer */", "$", "appli...
Handle an event. @param \League\Event\EventInterface $event The triggering event @return void @see \League\Event\ListenerInterface::handle()
[ "Handle", "an", "event", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Listeners/LoadLoggersListener.php#L46-L75
appserver-io/appserver
src/AppserverIo/Appserver/Core/Listeners/SwitchUmaskListener.php
SwitchUmaskListener.handle
public function handle(EventInterface $event) { try { // load the application server instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // load the service instance and switch the umask /** @var \AppserverIo\Appserver\Core\Api\DeploymentService $service */ $service = $applicationServer->newService('AppserverIo\Appserver\Core\Api\DeploymentService'); $service->initUmask($applicationServer->getSystemConfiguration()->getUmask()); } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
php
public function handle(EventInterface $event) { try { // load the application server instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // load the service instance and switch the umask /** @var \AppserverIo\Appserver\Core\Api\DeploymentService $service */ $service = $applicationServer->newService('AppserverIo\Appserver\Core\Api\DeploymentService'); $service->initUmask($applicationServer->getSystemConfiguration()->getUmask()); } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
[ "public", "function", "handle", "(", "EventInterface", "$", "event", ")", "{", "try", "{", "// load the application server instance", "/** @var \\AppserverIo\\Psr\\ApplicationServer\\ApplicationServerInterface $applicationServer */", "$", "applicationServer", "=", "$", "this", "-...
Handle an event. @param \League\Event\EventInterface $event The triggering event @return void @see \League\Event\ListenerInterface::handle()
[ "Handle", "an", "event", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Listeners/SwitchUmaskListener.php#L45-L64
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/ServletManagerFactory.php
ServletManagerFactory.visit
public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // initialize the stackable storage $data = new StackableStorage(); $servlets = new StackableStorage(); $errorPages = new StackableStorage(); $initParameters = new StackableStorage(); $servletMappings = new GenericStackable(); $securedUrlConfigs = new StackableStorage(); $sessionParameters = new StackableStorage(); // initialize the default settings for the stateful session beans $servletManagerSettings = new StandardManagerSettings(); $servletManagerSettings->mergeWithParams($managerConfiguration->getParamsAsArray()); // initialize the servlet locator $servletLocator = new ServletLocator(); // initialize the servlet manager $servletManager = new ServletManager(); $servletManager->injectData($data); $servletManager->injectServlets($servlets); $servletManager->injectErrorPages($errorPages); $servletManager->injectApplication($application); $servletManager->injectInitParameters($initParameters); $servletManager->injectResourceLocator($servletLocator); $servletManager->injectServletMappings($servletMappings); $servletManager->injectSecuredUrlConfigs($securedUrlConfigs); $servletManager->injectSessionParameters($sessionParameters); $servletManager->injectManagerSettings($servletManagerSettings); $servletManager->injectManagerConfiguration($managerConfiguration); // create the naming context and add it the manager $contextFactory = $managerConfiguration->getContextFactory(); $contextFactory::visit($servletManager); // attach the instance $application->addManager($servletManager, $managerConfiguration); }
php
public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // initialize the stackable storage $data = new StackableStorage(); $servlets = new StackableStorage(); $errorPages = new StackableStorage(); $initParameters = new StackableStorage(); $servletMappings = new GenericStackable(); $securedUrlConfigs = new StackableStorage(); $sessionParameters = new StackableStorage(); // initialize the default settings for the stateful session beans $servletManagerSettings = new StandardManagerSettings(); $servletManagerSettings->mergeWithParams($managerConfiguration->getParamsAsArray()); // initialize the servlet locator $servletLocator = new ServletLocator(); // initialize the servlet manager $servletManager = new ServletManager(); $servletManager->injectData($data); $servletManager->injectServlets($servlets); $servletManager->injectErrorPages($errorPages); $servletManager->injectApplication($application); $servletManager->injectInitParameters($initParameters); $servletManager->injectResourceLocator($servletLocator); $servletManager->injectServletMappings($servletMappings); $servletManager->injectSecuredUrlConfigs($securedUrlConfigs); $servletManager->injectSessionParameters($sessionParameters); $servletManager->injectManagerSettings($servletManagerSettings); $servletManager->injectManagerConfiguration($managerConfiguration); // create the naming context and add it the manager $contextFactory = $managerConfiguration->getContextFactory(); $contextFactory::visit($servletManager); // attach the instance $application->addManager($servletManager, $managerConfiguration); }
[ "public", "static", "function", "visit", "(", "ApplicationInterface", "$", "application", ",", "ManagerNodeInterface", "$", "managerConfiguration", ")", "{", "// initialize the stackable storage", "$", "data", "=", "new", "StackableStorage", "(", ")", ";", "$", "servl...
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
[ "The", "main", "method", "that", "creates", "new", "instances", "in", "a", "separate", "context", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/ServletManagerFactory.php#L50-L89
appserver-io/appserver
src/AppserverIo/Appserver/Core/Listeners/ShutdownApplicationsListener.php
ShutdownApplicationsListener.handle
public function handle(EventInterface $event) { try { // load the application server and the naming directory instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */ $namingDirectory = $applicationServer->getNamingDirectory(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // deploy the applications for all containers /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */ foreach ($applicationServer->getSystemConfiguration()->getContainers() as $containerNode) { // load the container instance to deploy the applications for /** @var \AppserverIo\Psr\ApplicationServer\ContainerInterface $container */ $container = $namingDirectory->search( sprintf( 'php:services/%s/%s', $applicationServer->runlevelToString(ApplicationServerInterface::NETWORK), $containerNode->getName() ) ); // iterate over all applications and shut them down /** @var \AppserverIo\Psr\Application\ApplicationInterface $application */ foreach ($container->getApplications() as $application) { $application->stop(); } } } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
php
public function handle(EventInterface $event) { try { // load the application server and the naming directory instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); /** @var \AppserverIo\Psr\Naming\NamingDirectoryInterface $namingDirectory */ $namingDirectory = $applicationServer->getNamingDirectory(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // deploy the applications for all containers /** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */ foreach ($applicationServer->getSystemConfiguration()->getContainers() as $containerNode) { // load the container instance to deploy the applications for /** @var \AppserverIo\Psr\ApplicationServer\ContainerInterface $container */ $container = $namingDirectory->search( sprintf( 'php:services/%s/%s', $applicationServer->runlevelToString(ApplicationServerInterface::NETWORK), $containerNode->getName() ) ); // iterate over all applications and shut them down /** @var \AppserverIo\Psr\Application\ApplicationInterface $application */ foreach ($container->getApplications() as $application) { $application->stop(); } } } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
[ "public", "function", "handle", "(", "EventInterface", "$", "event", ")", "{", "try", "{", "// load the application server and the naming directory instance", "/** @var \\AppserverIo\\Psr\\ApplicationServer\\ApplicationServerInterface $applicationServer */", "$", "applicationServer", "...
Handle an event. @param \League\Event\EventInterface $event The triggering event @return void @see \League\Event\ListenerInterface::handle()
[ "Handle", "an", "event", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Listeners/ShutdownApplicationsListener.php#L46-L82
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/ContextNode.php
ContextNode.initDefaultDirectories
public function initDefaultDirectories() { $this->setParam(DirectoryKeys::DATA, ParamNode::TYPE_STRING, '/data'); $this->setParam(DirectoryKeys::CACHE, ParamNode::TYPE_STRING, '/cache'); $this->setParam(DirectoryKeys::SESSION, ParamNode::TYPE_STRING, '/session'); }
php
public function initDefaultDirectories() { $this->setParam(DirectoryKeys::DATA, ParamNode::TYPE_STRING, '/data'); $this->setParam(DirectoryKeys::CACHE, ParamNode::TYPE_STRING, '/cache'); $this->setParam(DirectoryKeys::SESSION, ParamNode::TYPE_STRING, '/session'); }
[ "public", "function", "initDefaultDirectories", "(", ")", "{", "$", "this", "->", "setParam", "(", "DirectoryKeys", "::", "DATA", ",", "ParamNode", "::", "TYPE_STRING", ",", "'/data'", ")", ";", "$", "this", "->", "setParam", "(", "DirectoryKeys", "::", "CAC...
Initialize the default directories. @return void
[ "Initialize", "the", "default", "directories", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/ContextNode.php#L154-L159
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/ContextNode.php
ContextNode.merge
public function merge(ContextNode $contextNode) { // merge the application type if ($type = $contextNode->getType()) { $this->setType($type); } // merge the application factory class name if ($factory = $contextNode->getFactory()) { $this->setFactory($factory); } // merge the application webapp path if ($webappPath = $contextNode->getWebappPath()) { $this->setWebappPath($webappPath); } // load the params defined in this context $localParams = $this->getParams(); // merge them with the passed ones foreach ($contextNode->getParams() as $paramToMerge) { $isMerged = false; /** @var \AppserverIo\Appserver\Core\Api\Node\ParamNode $param */ foreach ($localParams as $key => $param) { if ($param->getName() == $paramToMerge->getName()) { $localParams[$key] = $paramToMerge; $isMerged = true; } } if ($isMerged === false) { $localParams[$paramToMerge->getUuid()] = $paramToMerge; } } // set the params back to the context $this->setParams($localParams); // load the annotation registries defined of this context $localAnnotationRegistries = $this->getAnnotationRegistries(); // append the annotation registries /** @var \AppserverIo\Description\Api\Node\AnnotationRegistryNode $additionalAnnotationRegistry */ foreach ($contextNode->getAnnotationRegistries() as $additionalAnnotationRegistry) { $localAnnotationRegistries[] = $additionalAnnotationRegistry; } // set the annotation registries back to the context $this->setAnnotationRegistries($localAnnotationRegistries); // load the managers defined of this context $localManagers = $this->getManagers(); // merge them with the passed ones /** @var \AppserverIo\Appserver\Core\Api\Node\ManagerNode $managerToMerge */ foreach ($contextNode->getManagers() as $managerToMerge) { $isMerged = false; /** @var \AppserverIo\Appserver\Core\Api\Node\ManagerNode $manager */ foreach ($localManagers as $key => $manager) { if ($manager->getName() === $managerToMerge->getName()) { $manager->merge($managerToMerge); $localManagers[$key] = $manager; $isMerged = true; } } if ($isMerged === false) { $localManagers[$managerToMerge->getUuid()] = $managerToMerge; } } // set the managers back to the context $this->setManagers($localManagers); // load the class loaders of this context $localClassLoaders = $this->getClassLoaders(); // merge them with the passed ones /** @var \AppserverIo\Appserver\Core\Api\Node\ClassLoaderNode $classLoaderToMerge */ foreach ($contextNode->getClassLoaders() as $classLoaderToMerge) { $isMerged = false; /** @var \AppserverIo\Appserver\Core\Api\Node\ClassLoaderNode $classLoader */ foreach ($localClassLoaders as $key => $classLoader) { if ($classLoader->getName() === $classLoaderToMerge->getName()) { $localClassLoaders[$key] = $classLoaderToMerge; $isMerged = true; } } if ($isMerged === false) { $localClassLoaders[$classLoaderToMerge->getUuid()] = $classLoaderToMerge; } } // set the class loaders back to the context $this->setClassLoaders($localClassLoaders); // load the loggers of this context $localLoggers = $this->getLoggers(); // merge them with the passed ones (DO override already registered loggers) /** @var \AppserverIo\Appserver\Core\Api\Node\LoggerNode $loggerToMerge */ foreach ($contextNode->getLoggers() as $loggerToMerge) { $localLoggers[$loggerToMerge->getName()] = $loggerToMerge; } // set the loggers back to the context $this->setLoggers($localLoggers); }
php
public function merge(ContextNode $contextNode) { // merge the application type if ($type = $contextNode->getType()) { $this->setType($type); } // merge the application factory class name if ($factory = $contextNode->getFactory()) { $this->setFactory($factory); } // merge the application webapp path if ($webappPath = $contextNode->getWebappPath()) { $this->setWebappPath($webappPath); } // load the params defined in this context $localParams = $this->getParams(); // merge them with the passed ones foreach ($contextNode->getParams() as $paramToMerge) { $isMerged = false; /** @var \AppserverIo\Appserver\Core\Api\Node\ParamNode $param */ foreach ($localParams as $key => $param) { if ($param->getName() == $paramToMerge->getName()) { $localParams[$key] = $paramToMerge; $isMerged = true; } } if ($isMerged === false) { $localParams[$paramToMerge->getUuid()] = $paramToMerge; } } // set the params back to the context $this->setParams($localParams); // load the annotation registries defined of this context $localAnnotationRegistries = $this->getAnnotationRegistries(); // append the annotation registries /** @var \AppserverIo\Description\Api\Node\AnnotationRegistryNode $additionalAnnotationRegistry */ foreach ($contextNode->getAnnotationRegistries() as $additionalAnnotationRegistry) { $localAnnotationRegistries[] = $additionalAnnotationRegistry; } // set the annotation registries back to the context $this->setAnnotationRegistries($localAnnotationRegistries); // load the managers defined of this context $localManagers = $this->getManagers(); // merge them with the passed ones /** @var \AppserverIo\Appserver\Core\Api\Node\ManagerNode $managerToMerge */ foreach ($contextNode->getManagers() as $managerToMerge) { $isMerged = false; /** @var \AppserverIo\Appserver\Core\Api\Node\ManagerNode $manager */ foreach ($localManagers as $key => $manager) { if ($manager->getName() === $managerToMerge->getName()) { $manager->merge($managerToMerge); $localManagers[$key] = $manager; $isMerged = true; } } if ($isMerged === false) { $localManagers[$managerToMerge->getUuid()] = $managerToMerge; } } // set the managers back to the context $this->setManagers($localManagers); // load the class loaders of this context $localClassLoaders = $this->getClassLoaders(); // merge them with the passed ones /** @var \AppserverIo\Appserver\Core\Api\Node\ClassLoaderNode $classLoaderToMerge */ foreach ($contextNode->getClassLoaders() as $classLoaderToMerge) { $isMerged = false; /** @var \AppserverIo\Appserver\Core\Api\Node\ClassLoaderNode $classLoader */ foreach ($localClassLoaders as $key => $classLoader) { if ($classLoader->getName() === $classLoaderToMerge->getName()) { $localClassLoaders[$key] = $classLoaderToMerge; $isMerged = true; } } if ($isMerged === false) { $localClassLoaders[$classLoaderToMerge->getUuid()] = $classLoaderToMerge; } } // set the class loaders back to the context $this->setClassLoaders($localClassLoaders); // load the loggers of this context $localLoggers = $this->getLoggers(); // merge them with the passed ones (DO override already registered loggers) /** @var \AppserverIo\Appserver\Core\Api\Node\LoggerNode $loggerToMerge */ foreach ($contextNode->getLoggers() as $loggerToMerge) { $localLoggers[$loggerToMerge->getName()] = $loggerToMerge; } // set the loggers back to the context $this->setLoggers($localLoggers); }
[ "public", "function", "merge", "(", "ContextNode", "$", "contextNode", ")", "{", "// merge the application type", "if", "(", "$", "type", "=", "$", "contextNode", "->", "getType", "(", ")", ")", "{", "$", "this", "->", "setType", "(", "$", "type", ")", "...
This method merges the installation steps of the passed provisioning node into the steps of this instance. If a installation node with the same type already exists, the one of this instance will be overwritten. @param \AppserverIo\Appserver\Core\Api\Node\ContextNode $contextNode The node with the installation steps we want to merge @return void
[ "This", "method", "merges", "the", "installation", "steps", "of", "the", "passed", "provisioning", "node", "into", "the", "steps", "of", "this", "instance", ".", "If", "a", "installation", "node", "with", "the", "same", "type", "already", "exists", "the", "o...
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/ContextNode.php#L280-L387
appserver-io/appserver
src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php
ThreadedContextTrait.getAttributes
public function getAttributes() { // initialize the array with the attributes $attributes = array(); // prepare the pattern to filter the attributes $pattern = sprintf('%s-*', $this->getSerial()); // prepare the array with the attributes foreach ($this as $key => $value) { if (fnmatch($pattern, $key)) { $attributes[$key] = $value; } } // return the attributes return $attributes; }
php
public function getAttributes() { // initialize the array with the attributes $attributes = array(); // prepare the pattern to filter the attributes $pattern = sprintf('%s-*', $this->getSerial()); // prepare the array with the attributes foreach ($this as $key => $value) { if (fnmatch($pattern, $key)) { $attributes[$key] = $value; } } // return the attributes return $attributes; }
[ "public", "function", "getAttributes", "(", ")", "{", "// initialize the array with the attributes", "$", "attributes", "=", "array", "(", ")", ";", "// prepare the pattern to filter the attributes", "$", "pattern", "=", "sprintf", "(", "'%s-*'", ",", "$", "this", "->...
All values registered in the context. @return array The context data
[ "All", "values", "registered", "in", "the", "context", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php#L74-L92
appserver-io/appserver
src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php
ThreadedContextTrait.getAllKeys
public function getAllKeys() { // initialize the array with keys of all attributes $keys = array(); // prepare the pattern to filter the attributes $pattern = sprintf('%s-*', $this->getSerial()); // prepare the array with the attribute keys foreach (array_keys((array) $this) as $key) { if (fnmatch($pattern, $key)) { $keys[] = $this->unmaskKey($key); } } // return the attribute keys return $keys; }
php
public function getAllKeys() { // initialize the array with keys of all attributes $keys = array(); // prepare the pattern to filter the attributes $pattern = sprintf('%s-*', $this->getSerial()); // prepare the array with the attribute keys foreach (array_keys((array) $this) as $key) { if (fnmatch($pattern, $key)) { $keys[] = $this->unmaskKey($key); } } // return the attribute keys return $keys; }
[ "public", "function", "getAllKeys", "(", ")", "{", "// initialize the array with keys of all attributes", "$", "keys", "=", "array", "(", ")", ";", "// prepare the pattern to filter the attributes", "$", "pattern", "=", "sprintf", "(", "'%s-*'", ",", "$", "this", "->"...
Returns the keys of the bound attributes. @return array The keys of the bound attributes
[ "Returns", "the", "keys", "of", "the", "bound", "attributes", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php#L99-L117
appserver-io/appserver
src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php
ThreadedContextTrait.getAttribute
public function getAttribute($key) { // query whether the identifier exists or not if (isset($this[$uid = $this->maskKey($key)])) { return $this[$uid]; } }
php
public function getAttribute($key) { // query whether the identifier exists or not if (isset($this[$uid = $this->maskKey($key)])) { return $this[$uid]; } }
[ "public", "function", "getAttribute", "(", "$", "key", ")", "{", "// query whether the identifier exists or not", "if", "(", "isset", "(", "$", "this", "[", "$", "uid", "=", "$", "this", "->", "maskKey", "(", "$", "key", ")", "]", ")", ")", "{", "return"...
Returns the value with the passed name from the context. @param string $key The key of the value to return from the context. @return mixed The requested attribute @see \AppserverIo\Psr\Context\ContextInterface::getAttribute()
[ "Returns", "the", "value", "with", "the", "passed", "name", "from", "the", "context", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php#L127-L134
appserver-io/appserver
src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php
ThreadedContextTrait.setAttribute
public function setAttribute($key, $value) { // if the value is already set, throw an exception if (isset($this[$uid = $this->maskKey($key)])) { throw new \Exception( sprintf('A value with key %s has already been set in application %s', $key, $this->getName()) ); } // append the value to the application $this[$uid] = $value; }
php
public function setAttribute($key, $value) { // if the value is already set, throw an exception if (isset($this[$uid = $this->maskKey($key)])) { throw new \Exception( sprintf('A value with key %s has already been set in application %s', $key, $this->getName()) ); } // append the value to the application $this[$uid] = $value; }
[ "public", "function", "setAttribute", "(", "$", "key", ",", "$", "value", ")", "{", "// if the value is already set, throw an exception", "if", "(", "isset", "(", "$", "this", "[", "$", "uid", "=", "$", "this", "->", "maskKey", "(", "$", "key", ")", "]", ...
Sets the passed key/value pair in the directory. @param string $key The attributes key @param mixed $value Tha attribute to be bound @return void @throws \Exception Is thrown if the value already exists
[ "Sets", "the", "passed", "key", "/", "value", "pair", "in", "the", "directory", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php#L145-L157
appserver-io/appserver
src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php
ThreadedContextTrait.removeAttribute
public function removeAttribute($key) { if (isset($this[$uid = $this->maskKey($key)])) { unset($this[$uid]); } }
php
public function removeAttribute($key) { if (isset($this[$uid = $this->maskKey($key)])) { unset($this[$uid]); } }
[ "public", "function", "removeAttribute", "(", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "this", "[", "$", "uid", "=", "$", "this", "->", "maskKey", "(", "$", "key", ")", "]", ")", ")", "{", "unset", "(", "$", "this", "[", "$", "uid", ...
Removes the attribue from the application. @param string $key The attribute to remove @return void
[ "Removes", "the", "attribue", "from", "the", "application", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Traits/ThreadedContextTrait.php#L178-L183
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/JobsNodeTrait.php
JobsNodeTrait.getJob
public function getJob($name) { foreach ($this->getJobs() as $job) { if ($job->getName() === $name) { return $job; } } }
php
public function getJob($name) { foreach ($this->getJobs() as $job) { if ($job->getName() === $name) { return $job; } } }
[ "public", "function", "getJob", "(", "$", "name", ")", "{", "foreach", "(", "$", "this", "->", "getJobs", "(", ")", "as", "$", "job", ")", "{", "if", "(", "$", "job", "->", "getName", "(", ")", "===", "$", "name", ")", "{", "return", "$", "job"...
Returns the job with the passed name. @param string $name The name of the job to be returned @return mixed The requested job
[ "Returns", "the", "job", "with", "the", "passed", "name", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/JobsNodeTrait.php#L76-L83
appserver-io/appserver
src/AppserverIo/Appserver/Core/Utilities/ShellFacade.php
ShellFacade.exec
public function exec($command) { // Check for prohibited commands foreach ($this->prohibitedCommands as $prohibitedCommand) { if (strpos(trim($command), $prohibitedCommand) !== false) { throw new \Exception('The shell command ' . $command . ' is prohibited'); } } return exec($command); }
php
public function exec($command) { // Check for prohibited commands foreach ($this->prohibitedCommands as $prohibitedCommand) { if (strpos(trim($command), $prohibitedCommand) !== false) { throw new \Exception('The shell command ' . $command . ' is prohibited'); } } return exec($command); }
[ "public", "function", "exec", "(", "$", "command", ")", "{", "// Check for prohibited commands", "foreach", "(", "$", "this", "->", "prohibitedCommands", "as", "$", "prohibitedCommand", ")", "{", "if", "(", "strpos", "(", "trim", "(", "$", "command", ")", ",...
Will execute a shell command using exec() function. @param string $command The command to execute over the shell @throws \Exception @return mixed
[ "Will", "execute", "a", "shell", "command", "using", "exec", "()", "function", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/ShellFacade.php#L62-L71
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/TimerServiceRegistry.php
TimerServiceRegistry.getClassAnnotation
public function getClassAnnotation(ClassInterface $reflectionClass, $annotationName) { return $this->getAnnotationReader()->getClassAnnotation($reflectionClass->toPhpReflectionClass(), $annotationName); }
php
public function getClassAnnotation(ClassInterface $reflectionClass, $annotationName) { return $this->getAnnotationReader()->getClassAnnotation($reflectionClass->toPhpReflectionClass(), $annotationName); }
[ "public", "function", "getClassAnnotation", "(", "ClassInterface", "$", "reflectionClass", ",", "$", "annotationName", ")", "{", "return", "$", "this", "->", "getAnnotationReader", "(", ")", "->", "getClassAnnotation", "(", "$", "reflectionClass", "->", "toPhpReflec...
Return's the class annotation with the passed name, if available. @param \AppserverIo\Lang\Reflection\ClassInterface $reflectionClass The reflection class to return the annotation for @param string $annotationName The name of the annotation to return @return object|null The class annotation, or NULL if not available
[ "Return", "s", "the", "class", "annotation", "with", "the", "passed", "name", "if", "available", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/TimerServiceRegistry.php#L83-L86
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/TimerServiceRegistry.php
TimerServiceRegistry.initialize
public function initialize(ApplicationInterface $application) { // build up META-INF directory var $metaInfDir = $application->getWebappPath() . DIRECTORY_SEPARATOR .'META-INF'; // check if we've found a valid directory if (is_dir($metaInfDir) === false) { return; } // load the timer service executor and timer factories $timerFactory = $this->getTimerFactory(); $calendarTimerFactory = $this->getCalendarTimerFactory(); $timerServiceExecutor = $this->getTimerServiceExecutor(); // load the service to iterate over application folders /** @var \AppserverIo\Appserver\Core\Api\DeploymentService $service */ $service = $application->newService('AppserverIo\Appserver\Core\Api\DeploymentService'); $phpFiles = $service->globDir($metaInfDir . DIRECTORY_SEPARATOR . '*.php'); // iterate all php files foreach ($phpFiles as $phpFile) { try { // cut off the META-INF directory and replace OS specific directory separators $relativePathToPhpFile = str_replace(DIRECTORY_SEPARATOR, '\\', str_replace($metaInfDir, '', $phpFile)); // now cut off the first directory, that will be '/classes' by default $pregResult = preg_replace('%^(\\\\*)[^\\\\]+%', '', $relativePathToPhpFile); $className = substr($pregResult, 0, -4); // create the reflection class instance $reflectionClass = new \ReflectionClass($className); // initialize the timed object instance with the data from the reflection class $timedObject = TimedObject::fromPhpReflectionClass($reflectionClass); // check if we have a bean with a @Stateless, @Singleton or @MessageDriven annotation if ($this->getClassAnnotation($timedObject, Stateless::class) || $this->getClassAnnotation($timedObject, Singleton::class) || $this->getClassAnnotation($timedObject, MessageDriven::class) ) { // initialize the stackable for the timeout methods $timeoutMethods = new StackableStorage(); // create the timed object invoker $timedObjectInvoker = new TimedObjectInvoker(); $timedObjectInvoker->injectApplication($application); $timedObjectInvoker->injectTimedObject($timedObject); $timedObjectInvoker->injectTimeoutMethods($timeoutMethods); $timedObjectInvoker->start(PTHREADS_INHERIT_NONE|PTHREADS_INHERIT_CONSTANTS); // initialize the stackable for the timers $timers = new StackableStorage(); // initialize the timer service $timerService = new TimerService(); $timerService->injectTimers($timers); $timerService->injectTimerFactory($timerFactory); $timerService->injectTimedObjectInvoker($timedObjectInvoker); $timerService->injectCalendarTimerFactory($calendarTimerFactory); $timerService->injectTimerServiceExecutor($timerServiceExecutor); $timerService->start(PTHREADS_INHERIT_NONE|PTHREADS_INHERIT_CONSTANTS); // register the initialized timer service $this->register($timerService); // log a message that the timer service has been registered $application->getInitialContext()->getSystemLogger()->debug( sprintf( 'Successfully registered timer service for bean %s', $reflectionClass->getName() ) ); } // 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 bean continue; } } }
php
public function initialize(ApplicationInterface $application) { // build up META-INF directory var $metaInfDir = $application->getWebappPath() . DIRECTORY_SEPARATOR .'META-INF'; // check if we've found a valid directory if (is_dir($metaInfDir) === false) { return; } // load the timer service executor and timer factories $timerFactory = $this->getTimerFactory(); $calendarTimerFactory = $this->getCalendarTimerFactory(); $timerServiceExecutor = $this->getTimerServiceExecutor(); // load the service to iterate over application folders /** @var \AppserverIo\Appserver\Core\Api\DeploymentService $service */ $service = $application->newService('AppserverIo\Appserver\Core\Api\DeploymentService'); $phpFiles = $service->globDir($metaInfDir . DIRECTORY_SEPARATOR . '*.php'); // iterate all php files foreach ($phpFiles as $phpFile) { try { // cut off the META-INF directory and replace OS specific directory separators $relativePathToPhpFile = str_replace(DIRECTORY_SEPARATOR, '\\', str_replace($metaInfDir, '', $phpFile)); // now cut off the first directory, that will be '/classes' by default $pregResult = preg_replace('%^(\\\\*)[^\\\\]+%', '', $relativePathToPhpFile); $className = substr($pregResult, 0, -4); // create the reflection class instance $reflectionClass = new \ReflectionClass($className); // initialize the timed object instance with the data from the reflection class $timedObject = TimedObject::fromPhpReflectionClass($reflectionClass); // check if we have a bean with a @Stateless, @Singleton or @MessageDriven annotation if ($this->getClassAnnotation($timedObject, Stateless::class) || $this->getClassAnnotation($timedObject, Singleton::class) || $this->getClassAnnotation($timedObject, MessageDriven::class) ) { // initialize the stackable for the timeout methods $timeoutMethods = new StackableStorage(); // create the timed object invoker $timedObjectInvoker = new TimedObjectInvoker(); $timedObjectInvoker->injectApplication($application); $timedObjectInvoker->injectTimedObject($timedObject); $timedObjectInvoker->injectTimeoutMethods($timeoutMethods); $timedObjectInvoker->start(PTHREADS_INHERIT_NONE|PTHREADS_INHERIT_CONSTANTS); // initialize the stackable for the timers $timers = new StackableStorage(); // initialize the timer service $timerService = new TimerService(); $timerService->injectTimers($timers); $timerService->injectTimerFactory($timerFactory); $timerService->injectTimedObjectInvoker($timedObjectInvoker); $timerService->injectCalendarTimerFactory($calendarTimerFactory); $timerService->injectTimerServiceExecutor($timerServiceExecutor); $timerService->start(PTHREADS_INHERIT_NONE|PTHREADS_INHERIT_CONSTANTS); // register the initialized timer service $this->register($timerService); // log a message that the timer service has been registered $application->getInitialContext()->getSystemLogger()->debug( sprintf( 'Successfully registered timer service for bean %s', $reflectionClass->getName() ) ); } // 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 bean continue; } } }
[ "public", "function", "initialize", "(", "ApplicationInterface", "$", "application", ")", "{", "// build up META-INF directory var", "$", "metaInfDir", "=", "$", "application", "->", "getWebappPath", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "'META-INF'", ";", "// ch...
Has been automatically invoked by the container after the application instance has been created. @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance @return void @see \AppserverIo\Psr\Application\ManagerInterface::initialize()
[ "Has", "been", "automatically", "invoked", "by", "the", "container", "after", "the", "application", "instance", "has", "been", "created", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/TimerServiceRegistry.php#L163-L248
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/TimerServiceRegistry.php
TimerServiceRegistry.register
public function register(ServiceProviderInterface $instance) { // check if the service has already been registered if ($this->getServices()->has($pk = $instance->getPrimaryKey())) { throw new ServiceAlreadyRegisteredException( sprintf( 'It is not allowed to register service %s with primary key %s more than on times', $instance->getServiceName(), $pk ) ); } // register the service using the primary key $this->getServices()->set($pk, $instance); }
php
public function register(ServiceProviderInterface $instance) { // check if the service has already been registered if ($this->getServices()->has($pk = $instance->getPrimaryKey())) { throw new ServiceAlreadyRegisteredException( sprintf( 'It is not allowed to register service %s with primary key %s more than on times', $instance->getServiceName(), $pk ) ); } // register the service using the primary key $this->getServices()->set($pk, $instance); }
[ "public", "function", "register", "(", "ServiceProviderInterface", "$", "instance", ")", "{", "// check if the service has already been registered", "if", "(", "$", "this", "->", "getServices", "(", ")", "->", "has", "(", "$", "pk", "=", "$", "instance", "->", "...
Attaches the passed service, to the context. @param \AppserverIo\Psr\EnterpriseBeans\ServiceProviderInterface $instance The service instance to attach @return void @throws \AppserverIo\Psr\EnterpriseBeans\ServiceAlreadyRegisteredException Is thrown if the passed service has already been registered
[ "Attaches", "the", "passed", "service", "to", "the", "context", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/TimerServiceRegistry.php#L258-L274
appserver-io/appserver
src/AppserverIo/Appserver/PersistenceContainer/TimerServiceRegistry.php
TimerServiceRegistry.stop
public function stop() { $this->getTimerServiceExecutor()->stop(); $this->getCalendarTimerFactory()->stop(); $this->getTimerFactory()->stop(); }
php
public function stop() { $this->getTimerServiceExecutor()->stop(); $this->getCalendarTimerFactory()->stop(); $this->getTimerFactory()->stop(); }
[ "public", "function", "stop", "(", ")", "{", "$", "this", "->", "getTimerServiceExecutor", "(", ")", "->", "stop", "(", ")", ";", "$", "this", "->", "getCalendarTimerFactory", "(", ")", "->", "stop", "(", ")", ";", "$", "this", "->", "getTimerFactory", ...
Shutdown the session manager instance. @return void \AppserverIo\Psr\Application\ManagerInterface::stop()
[ "Shutdown", "the", "session", "manager", "instance", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/TimerServiceRegistry.php#L293-L298
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Http/Response.php
Response.init
public function init() { // init body stream $this->bodyStream = ''; // init exception $this->exception = null; // init default response properties $this->statusCode = 200; $this->version = 'HTTP/1.1'; $this->statusReasonPhrase = "OK"; $this->mimeType = "text/plain"; $this->state = HttpResponseStates::INITIAL; // initialize cookies and headers $this->cookies = array(); $this->headers = array(); // initialize the default headers $this->initDefaultHeaders(); }
php
public function init() { // init body stream $this->bodyStream = ''; // init exception $this->exception = null; // init default response properties $this->statusCode = 200; $this->version = 'HTTP/1.1'; $this->statusReasonPhrase = "OK"; $this->mimeType = "text/plain"; $this->state = HttpResponseStates::INITIAL; // initialize cookies and headers $this->cookies = array(); $this->headers = array(); // initialize the default headers $this->initDefaultHeaders(); }
[ "public", "function", "init", "(", ")", "{", "// init body stream", "$", "this", "->", "bodyStream", "=", "''", ";", "// init exception", "$", "this", "->", "exception", "=", "null", ";", "// init default response properties", "$", "this", "->", "statusCode", "=...
Initialises the response object to default properties. @return void
[ "Initialises", "the", "response", "object", "to", "default", "properties", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Response.php#L56-L78
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Http/Response.php
Response.initDefaultHeaders
protected function initDefaultHeaders() { // add this header to prevent .php request to be cached $this->addHeader(HttpProtocol::HEADER_EXPIRES, '19 Nov 1981 08:52:00 GMT'); $this->addHeader(HttpProtocol::HEADER_CACHE_CONTROL, 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); $this->addHeader(HttpProtocol::HEADER_PRAGMA, 'no-cache'); // set per default text/html mimetype $this->addHeader(HttpProtocol::HEADER_CONTENT_TYPE, 'text/html'); }
php
protected function initDefaultHeaders() { // add this header to prevent .php request to be cached $this->addHeader(HttpProtocol::HEADER_EXPIRES, '19 Nov 1981 08:52:00 GMT'); $this->addHeader(HttpProtocol::HEADER_CACHE_CONTROL, 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); $this->addHeader(HttpProtocol::HEADER_PRAGMA, 'no-cache'); // set per default text/html mimetype $this->addHeader(HttpProtocol::HEADER_CONTENT_TYPE, 'text/html'); }
[ "protected", "function", "initDefaultHeaders", "(", ")", "{", "// add this header to prevent .php request to be cached", "$", "this", "->", "addHeader", "(", "HttpProtocol", "::", "HEADER_EXPIRES", ",", "'19 Nov 1981 08:52:00 GMT'", ")", ";", "$", "this", "->", "addHeader...
Initializes the response with the default headers. @return void
[ "Initializes", "the", "response", "with", "the", "default", "headers", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Response.php#L85-L94
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Http/Response.php
Response.addCookie
public function addCookie(CookieInterface $cookie) { // check if this cookie has already been set if ($this->hasCookie($name = $cookie->getName())) { // then check if we've already one cookie header available if (is_array($cookieValue = $this->getCookie($name))) { $cookieValue[] = $cookie; } else { $cookieValue = array($cookieValue, $cookie); } // add the cookie array $this->cookies[$name] = $cookieValue; } else { // when add it the first time, simply add it $this->cookies[$name] = $cookie; } }
php
public function addCookie(CookieInterface $cookie) { // check if this cookie has already been set if ($this->hasCookie($name = $cookie->getName())) { // then check if we've already one cookie header available if (is_array($cookieValue = $this->getCookie($name))) { $cookieValue[] = $cookie; } else { $cookieValue = array($cookieValue, $cookie); } // add the cookie array $this->cookies[$name] = $cookieValue; } else { // when add it the first time, simply add it $this->cookies[$name] = $cookie; } }
[ "public", "function", "addCookie", "(", "CookieInterface", "$", "cookie", ")", "{", "// check if this cookie has already been set", "if", "(", "$", "this", "->", "hasCookie", "(", "$", "name", "=", "$", "cookie", "->", "getName", "(", ")", ")", ")", "{", "//...
Adds a cookie. @param \AppserverIo\Psr\HttpMessage\CookieInterface $cookie The cookie instance to add @return void
[ "Adds", "a", "cookie", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Response.php#L103-L122
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Http/Response.php
Response.getCookie
public function getCookie($cookieName) { if ($this->hasCookie($cookieName) === false) { throw new HttpException("Cookie '$cookieName' not found"); } return $this->cookies[$cookieName]; }
php
public function getCookie($cookieName) { if ($this->hasCookie($cookieName) === false) { throw new HttpException("Cookie '$cookieName' not found"); } return $this->cookies[$cookieName]; }
[ "public", "function", "getCookie", "(", "$", "cookieName", ")", "{", "if", "(", "$", "this", "->", "hasCookie", "(", "$", "cookieName", ")", "===", "false", ")", "{", "throw", "new", "HttpException", "(", "\"Cookie '$cookieName' not found\"", ")", ";", "}", ...
Returns the cookie with the a cookie @param string $cookieName Name of the cookie to be checked @return mixed The cookie instance or an array of cookie instances @throws \AppserverIo\Http\HttpException Is thrown if the requested header is not available
[ "Returns", "the", "cookie", "with", "the", "a", "cookie" ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Response.php#L145-L151
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Http/Response.php
Response.copyBodyStream
public function copyBodyStream($sourceStream, $maxlength = null, $offset = 0) { // check if a stream has been passed if (is_resource($sourceStream)) { if ($offset && $maxlength) { $this->bodyStream = stream_get_contents($sourceStream, $maxlength, $offset); } if (!$offset && $maxlength) { $this->bodyStream = stream_get_contents($sourceStream, $maxlength); } if (!$offset && !$maxlength) { $this->bodyStream = stream_get_contents($sourceStream); } } else { // if not, copy the string $this->bodyStream = substr($sourceStream, $offset, $maxlength); } // return the string length return strlen($this->bodyStream); }
php
public function copyBodyStream($sourceStream, $maxlength = null, $offset = 0) { // check if a stream has been passed if (is_resource($sourceStream)) { if ($offset && $maxlength) { $this->bodyStream = stream_get_contents($sourceStream, $maxlength, $offset); } if (!$offset && $maxlength) { $this->bodyStream = stream_get_contents($sourceStream, $maxlength); } if (!$offset && !$maxlength) { $this->bodyStream = stream_get_contents($sourceStream); } } else { // if not, copy the string $this->bodyStream = substr($sourceStream, $offset, $maxlength); } // return the string length return strlen($this->bodyStream); }
[ "public", "function", "copyBodyStream", "(", "$", "sourceStream", ",", "$", "maxlength", "=", "null", ",", "$", "offset", "=", "0", ")", "{", "// check if a stream has been passed", "if", "(", "is_resource", "(", "$", "sourceStream", ")", ")", "{", "if", "("...
Copies a source stream to body stream. @param resource $sourceStream The file pointer to source stream @param integer $maxlength The max length to read from source stream @param integer $offset The offset from source stream to read @return integer The total number of bytes copied
[ "Copies", "a", "source", "stream", "to", "body", "stream", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Response.php#L214-L235
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Http/Response.php
Response.getHeadersAsString
public function getHeadersAsString() { $headerString = ''; foreach ($this->getHeaders() as $name => $header) { // build up a header string $headerString .= $name . ': ' . $header . PHP_EOL; } return $headerString; }
php
public function getHeadersAsString() { $headerString = ''; foreach ($this->getHeaders() as $name => $header) { // build up a header string $headerString .= $name . ': ' . $header . PHP_EOL; } return $headerString; }
[ "public", "function", "getHeadersAsString", "(", ")", "{", "$", "headerString", "=", "''", ";", "foreach", "(", "$", "this", "->", "getHeaders", "(", ")", "as", "$", "name", "=>", "$", "header", ")", "{", "// build up a header string", "$", "headerString", ...
Returns the headers as string @return string
[ "Returns", "the", "headers", "as", "string" ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Response.php#L276-L285
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Http/Response.php
Response.addHeader
public function addHeader($name, $value, $append = false) { // normalize header names in case of 'Content-type' into 'Content-Type' $name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name))); // check if we've a Set-Cookie header to process if ($this->hasHeader($name) && $append === true) { // then check if we've already one cookie header available if (is_array($headerValue = $this->getHeader($name))) { $headerValue[] = $value; } else { $headerValue = array($headerValue, $value); } // if no cookie header simple add it $this->headers[$name] = $headerValue; } else { $this->headers[$name] = $value; } }
php
public function addHeader($name, $value, $append = false) { // normalize header names in case of 'Content-type' into 'Content-Type' $name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name))); // check if we've a Set-Cookie header to process if ($this->hasHeader($name) && $append === true) { // then check if we've already one cookie header available if (is_array($headerValue = $this->getHeader($name))) { $headerValue[] = $value; } else { $headerValue = array($headerValue, $value); } // if no cookie header simple add it $this->headers[$name] = $headerValue; } else { $this->headers[$name] = $value; } }
[ "public", "function", "addHeader", "(", "$", "name", ",", "$", "value", ",", "$", "append", "=", "false", ")", "{", "// normalize header names in case of 'Content-type' into 'Content-Type'", "$", "name", "=", "str_replace", "(", "' '", ",", "'-'", ",", "ucwords", ...
Adds a header information got from connection. We've to take care that headers like Set-Cookie header can exist multiple times. To support this create an array that keeps the multiple header values. @param string $name The header name @param string $value The headers value @param boolean $append If TRUE and a header with the passed name already exists, the value will be appended @return void
[ "Adds", "a", "header", "information", "got", "from", "connection", ".", "We", "ve", "to", "take", "care", "that", "headers", "like", "Set", "-", "Cookie", "header", "can", "exist", "multiple", "times", ".", "To", "support", "this", "create", "an", "array",...
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Response.php#L298-L318
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Http/Response.php
Response.setStatusCode
public function setStatusCode($code) { // set status code $this->statusCode = $code; // lookup reason phrase by code and set $this->setStatusReasonPhrase(HttpProtocol::getStatusReasonPhraseByCode($code)); }
php
public function setStatusCode($code) { // set status code $this->statusCode = $code; // lookup reason phrase by code and set $this->setStatusReasonPhrase(HttpProtocol::getStatusReasonPhraseByCode($code)); }
[ "public", "function", "setStatusCode", "(", "$", "code", ")", "{", "// set status code", "$", "this", "->", "statusCode", "=", "$", "code", ";", "// lookup reason phrase by code and set", "$", "this", "->", "setStatusReasonPhrase", "(", "HttpProtocol", "::", "getSta...
Sets the http response status code @param int $code The status code to set @return void
[ "Sets", "the", "http", "response", "status", "code" ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Response.php#L379-L386
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Http/Response.php
Response.redirect
public function redirect($url, $code = 301) { $this->setStatusCode($code); $this->addHeader(HttpProtocol::HEADER_LOCATION, $url); }
php
public function redirect($url, $code = 301) { $this->setStatusCode($code); $this->addHeader(HttpProtocol::HEADER_LOCATION, $url); }
[ "public", "function", "redirect", "(", "$", "url", ",", "$", "code", "=", "301", ")", "{", "$", "this", "->", "setStatusCode", "(", "$", "code", ")", ";", "$", "this", "->", "addHeader", "(", "HttpProtocol", "::", "HEADER_LOCATION", ",", "$", "url", ...
Redirects to the passed URL by adding a 'Location' header and setting the appropriate status code, by default 301. @param string $url The URL to forward to @param integer $code The status code to set @return void
[ "Redirects", "to", "the", "passed", "URL", "by", "adding", "a", "Location", "header", "and", "setting", "the", "appropriate", "status", "code", "by", "default", "301", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Response.php#L463-L467
appserver-io/appserver
src/AppserverIo/Appserver/Core/SplClassLoader.php
SplClassLoader.visit
public static function visit(ApplicationInterface $application, ClassLoaderNodeInterface $configuration = null) { $application->addClassLoader(SplClassLoader::factory()); }
php
public static function visit(ApplicationInterface $application, ClassLoaderNodeInterface $configuration = null) { $application->addClassLoader(SplClassLoader::factory()); }
[ "public", "static", "function", "visit", "(", "ApplicationInterface", "$", "application", ",", "ClassLoaderNodeInterface", "$", "configuration", "=", "null", ")", "{", "$", "application", "->", "addClassLoader", "(", "SplClassLoader", "::", "factory", "(", ")", ")...
Visitor method that adds a initialized class loader to the passed application. @param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance @param \AppserverIo\Appserver\Core\Api\Node\ClassLoaderNodeInterface $configuration The class loader configuration node @return void
[ "Visitor", "method", "that", "adds", "a", "initialized", "class", "loader", "to", "the", "passed", "application", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/SplClassLoader.php#L61-L64
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/RewritesNodeTrait.php
RewritesNodeTrait.getRewrite
public function getRewrite($condition) { // iterate over all rewrites foreach ($this->getRewrites() as $rewriteNode) { // if we found one with a matching condition we will return it if ($rewriteNode->getCondition() === $condition) { return $rewriteNode; } } // we did not find anything return false; }
php
public function getRewrite($condition) { // iterate over all rewrites foreach ($this->getRewrites() as $rewriteNode) { // if we found one with a matching condition we will return it if ($rewriteNode->getCondition() === $condition) { return $rewriteNode; } } // we did not find anything return false; }
[ "public", "function", "getRewrite", "(", "$", "condition", ")", "{", "// iterate over all rewrites", "foreach", "(", "$", "this", "->", "getRewrites", "(", ")", "as", "$", "rewriteNode", ")", "{", "// if we found one with a matching condition we will return it", "if", ...
Will return the rewrite node with the specified condition and if nothing could be found we will return false. @param string $condition The condition of the rewrite in question @return \AppserverIo\Appserver\Core\Api\Node\RewriteNode|boolean The requested rewrite node
[ "Will", "return", "the", "rewrite", "node", "with", "the", "specified", "condition", "and", "if", "nothing", "could", "be", "found", "we", "will", "return", "false", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/RewritesNodeTrait.php#L61-L74
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/RewritesNodeTrait.php
RewritesNodeTrait.getRewritesAsArray
public function getRewritesAsArray() { // initialize the array for the rewrites $rewrites = array(); // prepare the array with the rewrite rules /** @var \AppserverIo\Appserver\Core\Api\Node\RewriteNode $rewrite */ foreach ($this->getRewrites() as $rewrite) { // rewrites might be extended using different injector extension types, check for that if ($rewrite->hasInjector()) { $target = $rewrite->getInjection(); } else { $target = $rewrite->getTarget(); } // build up the array entry $rewrites[] = array( 'condition' => $rewrite->getCondition(), 'target' => $target, 'flag' => $rewrite->getFlag() ); } // return the array return $rewrites; }
php
public function getRewritesAsArray() { // initialize the array for the rewrites $rewrites = array(); // prepare the array with the rewrite rules /** @var \AppserverIo\Appserver\Core\Api\Node\RewriteNode $rewrite */ foreach ($this->getRewrites() as $rewrite) { // rewrites might be extended using different injector extension types, check for that if ($rewrite->hasInjector()) { $target = $rewrite->getInjection(); } else { $target = $rewrite->getTarget(); } // build up the array entry $rewrites[] = array( 'condition' => $rewrite->getCondition(), 'target' => $target, 'flag' => $rewrite->getFlag() ); } // return the array return $rewrites; }
[ "public", "function", "getRewritesAsArray", "(", ")", "{", "// initialize the array for the rewrites", "$", "rewrites", "=", "array", "(", ")", ";", "// prepare the array with the rewrite rules", "/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\RewriteNode $rewrite */", "foreach"...
Returns the rewrites as an associative array. @return array The array with the sorted rewrites
[ "Returns", "the", "rewrites", "as", "an", "associative", "array", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/RewritesNodeTrait.php#L81-L107
appserver-io/appserver
src/AppserverIo/Appserver/Core/GenericContainerFactory.php
GenericContainerFactory.factory
public static function factory( ApplicationServerInterface $applicationServer, ContainerConfigurationInterface $configuration, $runlevel = ApplicationServerInterface::NETWORK ) { // create a new reflection class instance $reflectionClass = new \ReflectionClass($configuration->getType()); // initialize the container configuration with the base directory and pass it to the thread $params = array($applicationServer->getInitialContext(), $applicationServer->getNamingDirectory(), $configuration, $applicationServer->runlevelToString($runlevel)); // create, initialize and return the container instance return $reflectionClass->newInstanceArgs($params); }
php
public static function factory( ApplicationServerInterface $applicationServer, ContainerConfigurationInterface $configuration, $runlevel = ApplicationServerInterface::NETWORK ) { // create a new reflection class instance $reflectionClass = new \ReflectionClass($configuration->getType()); // initialize the container configuration with the base directory and pass it to the thread $params = array($applicationServer->getInitialContext(), $applicationServer->getNamingDirectory(), $configuration, $applicationServer->runlevelToString($runlevel)); // create, initialize and return the container instance return $reflectionClass->newInstanceArgs($params); }
[ "public", "static", "function", "factory", "(", "ApplicationServerInterface", "$", "applicationServer", ",", "ContainerConfigurationInterface", "$", "configuration", ",", "$", "runlevel", "=", "ApplicationServerInterface", "::", "NETWORK", ")", "{", "// create a new reflect...
Factory method to create a new container instance. @param \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer The application instance to register the class loader with @param \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $configuration The class loader configuration @param integer $runlevel The runlevel the container has been started in @return void
[ "Factory", "method", "to", "create", "a", "new", "container", "instance", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/GenericContainerFactory.php#L48-L62
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/RewriteMapsNodeTrait.php
RewriteMapsNodeTrait.getRewriteMapsAsArray
public function getRewriteMapsAsArray() { // initialize the array for the rewrite maps $rewriteMaps = array(); // iterate over the rewriteMaps nodes and sort them into an array foreach ($this->getRewriteMaps() as $rewriteMapNode) { $rewriteMaps[$rewriteMapNode->getType()] = $rewriteMapNode->getParamsAsArray(); } // return the array return $rewriteMaps; }
php
public function getRewriteMapsAsArray() { // initialize the array for the rewrite maps $rewriteMaps = array(); // iterate over the rewriteMaps nodes and sort them into an array foreach ($this->getRewriteMaps() as $rewriteMapNode) { $rewriteMaps[$rewriteMapNode->getType()] = $rewriteMapNode->getParamsAsArray(); } // return the array return $rewriteMaps; }
[ "public", "function", "getRewriteMapsAsArray", "(", ")", "{", "// initialize the array for the rewrite maps", "$", "rewriteMaps", "=", "array", "(", ")", ";", "// iterate over the rewriteMaps nodes and sort them into an array", "foreach", "(", "$", "this", "->", "getRewriteMa...
Returns the rewriteMaps as an associative array. @return array The array with the rewriteMaps
[ "Returns", "the", "rewriteMaps", "as", "an", "associative", "array", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/RewriteMapsNodeTrait.php#L59-L72
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/AbstractServletEngine.php
AbstractServletEngine.findRequestedApplication
public function findRequestedApplication(RequestContextInterface $requestContext) { // prepare the request URL we want to match $webappsDir = $this->getServerContext()->getServerConfig()->getDocumentRoot(); $relativeRequestPath = strstr($requestContext->getServerVar(ServerVars::DOCUMENT_ROOT) . $requestContext->getServerVar(ServerVars::X_REQUEST_URI), $webappsDir); $proposedAppName = strstr(str_replace($webappsDir . '/', '', $relativeRequestPath), '/', true); // try to match a registered application with the passed request foreach ($this->applications as $application) { if ($application->getName() === $proposedAppName) { return $application; } } // if we did not find anything we should throw a bad request exception throw new BadRequestException( sprintf( 'Can\'t find application for URL %s%s', $requestContext->getServerVar(ServerVars::HTTP_HOST), $requestContext->getServerVar(ServerVars::X_REQUEST_URI) ), 404 ); }
php
public function findRequestedApplication(RequestContextInterface $requestContext) { // prepare the request URL we want to match $webappsDir = $this->getServerContext()->getServerConfig()->getDocumentRoot(); $relativeRequestPath = strstr($requestContext->getServerVar(ServerVars::DOCUMENT_ROOT) . $requestContext->getServerVar(ServerVars::X_REQUEST_URI), $webappsDir); $proposedAppName = strstr(str_replace($webappsDir . '/', '', $relativeRequestPath), '/', true); // try to match a registered application with the passed request foreach ($this->applications as $application) { if ($application->getName() === $proposedAppName) { return $application; } } // if we did not find anything we should throw a bad request exception throw new BadRequestException( sprintf( 'Can\'t find application for URL %s%s', $requestContext->getServerVar(ServerVars::HTTP_HOST), $requestContext->getServerVar(ServerVars::X_REQUEST_URI) ), 404 ); }
[ "public", "function", "findRequestedApplication", "(", "RequestContextInterface", "$", "requestContext", ")", "{", "// prepare the request URL we want to match", "$", "webappsDir", "=", "$", "this", "->", "getServerContext", "(", ")", "->", "getServerConfig", "(", ")", ...
Will try to find the application based on the context path taken from the requested filename. Will return the found application on success and throw an exception if nothing could be found @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext Context of the current request @return null|\AppserverIo\Psr\Application\ApplicationInterface @throws \AppserverIo\Appserver\ServletEngine\BadRequestException
[ "Will", "try", "to", "find", "the", "application", "based", "on", "the", "context", "path", "taken", "from", "the", "requested", "filename", ".", "Will", "return", "the", "found", "application", "on", "success", "and", "throw", "an", "exception", "if", "noth...
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/AbstractServletEngine.php#L83-L107
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/AbstractServletEngine.php
AbstractServletEngine.logDebugException
public function logDebugException(\Exception $e) { if ($this->getServerContext()->hasLogger(LoggerUtils::SYSTEM)) { $this->getServerContext()->getLogger(LoggerUtils::SYSTEM)->debug($e->__toString()); } }
php
public function logDebugException(\Exception $e) { if ($this->getServerContext()->hasLogger(LoggerUtils::SYSTEM)) { $this->getServerContext()->getLogger(LoggerUtils::SYSTEM)->debug($e->__toString()); } }
[ "public", "function", "logDebugException", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "$", "this", "->", "getServerContext", "(", ")", "->", "hasLogger", "(", "LoggerUtils", "::", "SYSTEM", ")", ")", "{", "$", "this", "->", "getServerContext", ...
Helper method that writes debug system exceptions to the system logger if configured. @param \Exception $e The exception to be logged @return void
[ "Helper", "method", "that", "writes", "debug", "system", "exceptions", "to", "the", "system", "logger", "if", "configured", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/AbstractServletEngine.php#L219-L224
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/AbstractServletEngine.php
AbstractServletEngine.logErrorException
public function logErrorException(\Exception $e) { if ($this->getServerContext()->hasLogger(LoggerUtils::SYSTEM)) { $this->getServerContext()->getLogger(LoggerUtils::SYSTEM)->error($e->__toString()); } }
php
public function logErrorException(\Exception $e) { if ($this->getServerContext()->hasLogger(LoggerUtils::SYSTEM)) { $this->getServerContext()->getLogger(LoggerUtils::SYSTEM)->error($e->__toString()); } }
[ "public", "function", "logErrorException", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "$", "this", "->", "getServerContext", "(", ")", "->", "hasLogger", "(", "LoggerUtils", "::", "SYSTEM", ")", ")", "{", "$", "this", "->", "getServerContext", ...
Helper method that writes system exceptions to the system logger if configured. @param \Exception $e The exception to be logged @return void
[ "Helper", "method", "that", "writes", "system", "exceptions", "to", "the", "system", "logger", "if", "configured", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/AbstractServletEngine.php#L234-L239
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/AbstractServletEngine.php
AbstractServletEngine.logCriticalException
public function logCriticalException(\Exception $e) { if ($this->getServerContext()->hasLogger(LoggerUtils::SYSTEM)) { $this->getServerContext()->getLogger(LoggerUtils::SYSTEM)->critical($e->__toString()); } }
php
public function logCriticalException(\Exception $e) { if ($this->getServerContext()->hasLogger(LoggerUtils::SYSTEM)) { $this->getServerContext()->getLogger(LoggerUtils::SYSTEM)->critical($e->__toString()); } }
[ "public", "function", "logCriticalException", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "$", "this", "->", "getServerContext", "(", ")", "->", "hasLogger", "(", "LoggerUtils", "::", "SYSTEM", ")", ")", "{", "$", "this", "->", "getServerContext...
Helper method that writes critical system exceptions to the system logger if configured. @param \Exception $e The exception to be logged @return void
[ "Helper", "method", "that", "writes", "critical", "system", "exceptions", "to", "the", "system", "logger", "if", "configured", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/AbstractServletEngine.php#L249-L254
appserver-io/appserver
src/AppserverIo/Appserver/Core/Listeners/StartConsolesListener.php
StartConsolesListener.handle
public function handle(EventInterface $event) { try { // load the application server instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // and initialize a console for each node found in the configuration /** @var \AppserverIo\Psr\Cli\Configuration\ConsoleConfigurationInterface $consoleNode */ foreach ($applicationServer->getSystemConfiguration()->getConsoles() as $consoleNode) { /** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleFactoryInterface $consoleFactory */ $consoleFactory = $consoleNode->getFactory(); // use the factory if available /** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleInterface $console */ $console = $consoleFactory::factory($applicationServer, $consoleNode); // register the console as service $applicationServer->bindService(ApplicationServerInterface::ADMINISTRATION, $console); } } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
php
public function handle(EventInterface $event) { try { // load the application server instance /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // and initialize a console for each node found in the configuration /** @var \AppserverIo\Psr\Cli\Configuration\ConsoleConfigurationInterface $consoleNode */ foreach ($applicationServer->getSystemConfiguration()->getConsoles() as $consoleNode) { /** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleFactoryInterface $consoleFactory */ $consoleFactory = $consoleNode->getFactory(); // use the factory if available /** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleInterface $console */ $console = $consoleFactory::factory($applicationServer, $consoleNode); // register the console as service $applicationServer->bindService(ApplicationServerInterface::ADMINISTRATION, $console); } } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
[ "public", "function", "handle", "(", "EventInterface", "$", "event", ")", "{", "try", "{", "// load the application server instance", "/** @var \\AppserverIo\\Psr\\ApplicationServer\\ApplicationServerInterface $applicationServer */", "$", "applicationServer", "=", "$", "this", "-...
Handle an event. @param \League\Event\EventInterface $event The triggering event @return void @see \League\Event\ListenerInterface::handle()
[ "Handle", "an", "event", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Listeners/StartConsolesListener.php#L46-L74
appserver-io/appserver
src/AppserverIo/Appserver/Core/Api/Node/SessionConfigNode.php
SessionConfigNode.toArray
public function toArray() { // initialize the array with the session configuration $sessionConfiguration = array(); // query whether or not a value has been available in the deployment descriptor if ($sessionName = $this->getSessionName()) { $sessionConfiguration[ServletSessionInterface::SESSION_NAME] = (string) $sessionName; } if ($sessionSavePath = $this->getSessionSavePath()) { $sessionConfiguration[ServletSessionInterface::SESSION_SAVE_PATH] = (string) $sessionSavePath; } if ($sessionMaximumAge = $this->getSessionMaximumAge()) { $sessionConfiguration[ServletSessionInterface::SESSION_MAXIMUM_AGE] = (string) $sessionMaximumAge; } if ($sessionInactivityTimeout = $this->getSessionInactivityTimeout()) { $sessionConfiguration[ServletSessionInterface::SESSION_INACTIVITY_TIMEOUT] = (string) $sessionInactivityTimeout; } if ($sessionFilePrefix = $this->getSessionFilePrefix()) { $sessionConfiguration[ServletSessionInterface::SESSION_FILE_PREFIX] = (string) $sessionFilePrefix; } if ($sessionCookieSecure = $this->getSessionCookieSecure()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_SECURE] = (string) $sessionCookieSecure; } if ($sessionCookiePath = $this->getSessionCookiePath()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_PATH] = (string) $sessionCookiePath; } if ($sessionCookieLifetime = $this->getSessionCookieLifetime()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_LIFETIME] = (string) $sessionCookieLifetime; } if ($sessionCookieHttpOnly = $this->getSessionCookieHttpOnly()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_HTTP_ONLY] = (string) $sessionCookieHttpOnly; } if ($sessionCookieDomain = $this->getSessionCookieDomain()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_DOMAIN] = (string) $sessionCookieDomain; } if ($garbageCollectionProbability = $this->getGarbageCollectionProbability()) { $sessionConfiguration[ServletSessionInterface::GARBAGE_COLLECTION_PROBABILITY] = (string) $garbageCollectionProbability; } // return the array with the session configuration return $sessionConfiguration; }
php
public function toArray() { // initialize the array with the session configuration $sessionConfiguration = array(); // query whether or not a value has been available in the deployment descriptor if ($sessionName = $this->getSessionName()) { $sessionConfiguration[ServletSessionInterface::SESSION_NAME] = (string) $sessionName; } if ($sessionSavePath = $this->getSessionSavePath()) { $sessionConfiguration[ServletSessionInterface::SESSION_SAVE_PATH] = (string) $sessionSavePath; } if ($sessionMaximumAge = $this->getSessionMaximumAge()) { $sessionConfiguration[ServletSessionInterface::SESSION_MAXIMUM_AGE] = (string) $sessionMaximumAge; } if ($sessionInactivityTimeout = $this->getSessionInactivityTimeout()) { $sessionConfiguration[ServletSessionInterface::SESSION_INACTIVITY_TIMEOUT] = (string) $sessionInactivityTimeout; } if ($sessionFilePrefix = $this->getSessionFilePrefix()) { $sessionConfiguration[ServletSessionInterface::SESSION_FILE_PREFIX] = (string) $sessionFilePrefix; } if ($sessionCookieSecure = $this->getSessionCookieSecure()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_SECURE] = (string) $sessionCookieSecure; } if ($sessionCookiePath = $this->getSessionCookiePath()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_PATH] = (string) $sessionCookiePath; } if ($sessionCookieLifetime = $this->getSessionCookieLifetime()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_LIFETIME] = (string) $sessionCookieLifetime; } if ($sessionCookieHttpOnly = $this->getSessionCookieHttpOnly()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_HTTP_ONLY] = (string) $sessionCookieHttpOnly; } if ($sessionCookieDomain = $this->getSessionCookieDomain()) { $sessionConfiguration[ServletSessionInterface::SESSION_COOKIE_DOMAIN] = (string) $sessionCookieDomain; } if ($garbageCollectionProbability = $this->getGarbageCollectionProbability()) { $sessionConfiguration[ServletSessionInterface::GARBAGE_COLLECTION_PROBABILITY] = (string) $garbageCollectionProbability; } // return the array with the session configuration return $sessionConfiguration; }
[ "public", "function", "toArray", "(", ")", "{", "// initialize the array with the session configuration", "$", "sessionConfiguration", "=", "array", "(", ")", ";", "// query whether or not a value has been available in the deployment descriptor", "if", "(", "$", "sessionName", ...
Returns the session configuration as associative array. @return array The array with the session configuration
[ "Returns", "the", "session", "configuration", "as", "associative", "array", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/SessionConfigNode.php#L242-L285
appserver-io/appserver
src/AppserverIo/Appserver/MessageQueue/QueueWorker.php
QueueWorker.attach
public function attach(\stdClass $jobWrapper) { // attach the job wrapper $this->synchronized(function (QueueWorker $self, \stdClass $jw) { $self->jobsToExecute[$jw->jobId] = $jw; }, $this, $jobWrapper); }
php
public function attach(\stdClass $jobWrapper) { // attach the job wrapper $this->synchronized(function (QueueWorker $self, \stdClass $jw) { $self->jobsToExecute[$jw->jobId] = $jw; }, $this, $jobWrapper); }
[ "public", "function", "attach", "(", "\\", "stdClass", "$", "jobWrapper", ")", "{", "// attach the job wrapper", "$", "this", "->", "synchronized", "(", "function", "(", "QueueWorker", "$", "self", ",", "\\", "stdClass", "$", "jw", ")", "{", "$", "self", "...
Attaches a job for the passed wrapper to the worker instance. @param \stdClass $jobWrapper The job wrapper to attach the job for @return void
[ "Attaches", "a", "job", "for", "the", "passed", "wrapper", "to", "the", "worker", "instance", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/MessageQueue/QueueWorker.php#L166-L173
appserver-io/appserver
src/AppserverIo/Appserver/MessageQueue/QueueWorker.php
QueueWorker.bootstrap
public function bootstrap() { // register the default autoloader require SERVER_AUTOLOADER; // synchronize the application instance and register the class loaders $application = $this->application; $application->registerClassLoaders(); // register the applications annotation registries $application->registerAnnotationRegistries(); // add the application instance to the environment Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $application); // create s simulated request/session ID whereas session equals request ID Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $sessionId = SessionUtils::generateRandomString()); Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $sessionId); // try to load the profile logger if ($this->profileLogger = $application->getInitialContext()->getLogger(\AppserverIo\Logger\LoggerUtils::PROFILE)) { $this->profileLogger->appendThreadContext(sprintf('queue-worker-%s', $this->priorityKey)); } }
php
public function bootstrap() { // register the default autoloader require SERVER_AUTOLOADER; // synchronize the application instance and register the class loaders $application = $this->application; $application->registerClassLoaders(); // register the applications annotation registries $application->registerAnnotationRegistries(); // add the application instance to the environment Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $application); // create s simulated request/session ID whereas session equals request ID Environment::singleton()->setAttribute(EnvironmentKeys::SESSION_ID, $sessionId = SessionUtils::generateRandomString()); Environment::singleton()->setAttribute(EnvironmentKeys::REQUEST_ID, $sessionId); // try to load the profile logger if ($this->profileLogger = $application->getInitialContext()->getLogger(\AppserverIo\Logger\LoggerUtils::PROFILE)) { $this->profileLogger->appendThreadContext(sprintf('queue-worker-%s', $this->priorityKey)); } }
[ "public", "function", "bootstrap", "(", ")", "{", "// register the default autoloader", "require", "SERVER_AUTOLOADER", ";", "// synchronize the application instance and register the class loaders", "$", "application", "=", "$", "this", "->", "application", ";", "$", "applica...
This method will be invoked before the while() loop starts and can be used to implement some bootstrap functionality. @return void
[ "This", "method", "will", "be", "invoked", "before", "the", "while", "()", "loop", "starts", "and", "can", "be", "used", "to", "implement", "some", "bootstrap", "functionality", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/MessageQueue/QueueWorker.php#L195-L219
appserver-io/appserver
src/AppserverIo/Appserver/MessageQueue/QueueWorker.php
QueueWorker.run
public function run() { try { // register shutdown handler register_shutdown_function($this->getDefaultShutdownMethod()); // bootstrap the daemon $this->bootstrap(); // synchronize the application instance and register the class loaders $application = $this->application; // mark the daemon as successfully shutdown $this->synchronized(function ($self) { $self->state = EnumState::get(EnumState::RUNNING); }, $this); // create local instances of the storages $messages = $this->messages; $priorityKey = $this->priorityKey; $jobsToExecute = $this->jobsToExecute; // load the maximum number of jobs to process in parallel $maximumJobsToProcess = $this->getManagerSettings()->getMaximumJobsToProcess(); // initialize the arrays for the message states and the jobs executing $jobsExecuting = array(); $messagesFailed = array(); $retryCounter = array(); $callbacksToExecute = array(); // keep the daemon running while ($this->keepRunning()) { // iterate over all job wrappers foreach ($jobsToExecute as $jobWrapper) { try { // load the message $message = $messages[$jobWrapper->jobId]; // check if we've a message found if ($message instanceof MessageInterface) { // check the message state switch ($message->getState()->getState()) { // message is active and ready to be processed case StateActive::KEY: // set the new state now $message->setState(StateToProcess::get()); break; // message is paused or in progress case StatePaused::KEY: // invoke the callbacks for the state if ($message->hasCallbacks($message->getState())) { $callbacksToExecute[] = new Callback(clone $message, $application); } // log a message that we've a message that has been paused \info(sprintf('Message %s has been paused', $message->getMessageId())); break; case StateInProgress::KEY: // query whether or not the job is still available if (isset($jobsExecuting[$message->getMessageId()])) { // make sure the job has been finished if ($jobsExecuting[$message->getMessageId()] instanceof JobInterface && $jobsExecuting[$message->getMessageId()]->isFinished()) { // log a message that the job is still in progress \info(sprintf('Job %s has been finished', $message->getMessageId())); // set the new state now $message->setState($jobsExecuting[$message->getMessageId()]->getMessage()->getState()); } else { // log a message that the job is still in progress \info(sprintf('Job %s is still in progress', $message->getMessageId())); } } else { // log a message that the job is still in progress \critical(sprintf('Message %s has been deleted, but should still be there', $message->getMessageId())); } break; // message failed case StateFailed::KEY: // remove the old job from the queue unset($jobsExecuting[$message->getMessageId()]); // query whether or not the message has to be processed again if (isset($messagesFailed[$message->getMessageId()]) && $message->getRetryCounter() > 0) { // query whether or not the message has to be processed now if ($messagesFailed[$message->getMessageId()] < time() && $retryCounter[$message->getMessageId()] < $message->getRetryCounter()) { // retry to process the message $message->setState(StateToProcess::get()); // update the execution time and raise the retry counter $messagesFailed[$message->getMessageId()] = time() + $message->getRetryTimeout($retryCounter[$message->getMessageId()]); $retryCounter[$message->getMessageId()]++; } elseif ($messagesFailed[$message->getMessageId()] < time() && $retryCounter[$message->getMessageId()] === $message->getRetryCounter()) { // log a message that we've a message with a unknown state \critical(sprintf('Message %s finally failed after %d retries', $message->getMessageId(), $retryCounter[$message->getMessageId()])); // stop executing the job because we've reached the maximum number of retries unset($jobsToExecute[$messageId = $message->getMessageId()]); unset($messagesFailed[$messageId]); unset($retryCounter[$messageId]); // invoke the callbacks for the state if ($message->hasCallbacks($message->getState())) { $callbacksToExecute[] = new Callback(clone $message, $application); } } else { // wait for the next try here } } elseif (!isset($messagesFailed[$message->getMessageId()]) && $message->getRetryCounter() > 0) { // first retry, so we've to initialize the next execution time and the retry counter $retryCounter[$message->getMessageId()] = 0; $messagesFailed[$message->getMessageId()] = time() + $message->getRetryTimeout($retryCounter[$message->getMessageId()]); } else { // log a message that we've a message with a unknown state \critical(sprintf('Message %s failed with NO retries', $message->getMessageId())); // stop executing the job because we've reached the maximum number of retries unset($jobsToExecute[$messageId = $message->getMessageId()]); // invoke the callbacks for the state if ($message->hasCallbacks($message->getState())) { $callbacksToExecute[] = new Callback(clone $message, $application); } } break; case StateToProcess::KEY: // count messages in queue $inQueue = sizeof($jobsExecuting); // we only process 200 jobs in parallel if ($inQueue < $maximumJobsToProcess) { // set the new message state now $message->setState(StateInProgress::get()); // start the job and add it to the internal array $jobsExecuting[$message->getMessageId()] = new Job(clone $message, $application); } else { // log a message that queue is actually full \info(sprintf('Job queue full - (%d jobs/%d msg wait)', $inQueue, sizeof($messages))); // if the job queue is full, restart iteration to remove processed jobs from queue first continue 2; } break; // message processing has been successfully processed case StateProcessed::KEY: // invoke the callbacks for the state if ($message->hasCallbacks($message->getState())) { $callbacksToExecute[] = new Callback(clone $message, $application); } // remove the job from the queue with jobs that has to be executed unset($jobsToExecute[$messageId = $message->getMessageId()]); // also remove the job + the message from the queue unset($jobsExecuting[$messageId]); unset($messages[$messageId]); break; // message is in an unknown state -> this is weired and should never happen! case StateUnknown::KEY: // log a message that we've a message with a unknown state \critical(sprintf('Message %s has state %s', $message->getMessageId(), $message->getState())); // set new state now $message->setState(StateFailed::get()); break; // we don't know the message state -> this is weired and should never happen! default: // set the failed message state $message->setState(StateFailed::get()); // log a message that we've a message with an invalid state \critical(sprintf('Message %s has an invalid state', $message->getMessageId())); break; } } // add the message back to the stack (because we've a copy here) if (isset($messages[$message->getMessageId()])) { $messages[$jobWrapper->jobId] = $message; } // catch all exceptions } catch (\Exception $e) { $application->getInitialContext()->getSystemLogger()->critical($e->__toString()); } // reduce CPU load depending on queue priority $this->iterate($this->getQueueTimeout()); } // reduce CPU load after each iteration $this->iterate($this->getDefaultTimeout()); // profile the size of the session pool if ($this->profileLogger) { $this->profileLogger->debug( sprintf( 'Processed queue worker with priority %s, size of queue size is: %d', $priorityKey, sizeof($jobsToExecute) ) ); } } // clean up the instances and free memory $this->cleanUp(); // mark the daemon as successfully shutdown $this->synchronized(function ($self) { $self->state = EnumState::get(EnumState::SHUTDOWN); }, $this); } catch (\Exception $e) { \error($e->__toString()); } }
php
public function run() { try { // register shutdown handler register_shutdown_function($this->getDefaultShutdownMethod()); // bootstrap the daemon $this->bootstrap(); // synchronize the application instance and register the class loaders $application = $this->application; // mark the daemon as successfully shutdown $this->synchronized(function ($self) { $self->state = EnumState::get(EnumState::RUNNING); }, $this); // create local instances of the storages $messages = $this->messages; $priorityKey = $this->priorityKey; $jobsToExecute = $this->jobsToExecute; // load the maximum number of jobs to process in parallel $maximumJobsToProcess = $this->getManagerSettings()->getMaximumJobsToProcess(); // initialize the arrays for the message states and the jobs executing $jobsExecuting = array(); $messagesFailed = array(); $retryCounter = array(); $callbacksToExecute = array(); // keep the daemon running while ($this->keepRunning()) { // iterate over all job wrappers foreach ($jobsToExecute as $jobWrapper) { try { // load the message $message = $messages[$jobWrapper->jobId]; // check if we've a message found if ($message instanceof MessageInterface) { // check the message state switch ($message->getState()->getState()) { // message is active and ready to be processed case StateActive::KEY: // set the new state now $message->setState(StateToProcess::get()); break; // message is paused or in progress case StatePaused::KEY: // invoke the callbacks for the state if ($message->hasCallbacks($message->getState())) { $callbacksToExecute[] = new Callback(clone $message, $application); } // log a message that we've a message that has been paused \info(sprintf('Message %s has been paused', $message->getMessageId())); break; case StateInProgress::KEY: // query whether or not the job is still available if (isset($jobsExecuting[$message->getMessageId()])) { // make sure the job has been finished if ($jobsExecuting[$message->getMessageId()] instanceof JobInterface && $jobsExecuting[$message->getMessageId()]->isFinished()) { // log a message that the job is still in progress \info(sprintf('Job %s has been finished', $message->getMessageId())); // set the new state now $message->setState($jobsExecuting[$message->getMessageId()]->getMessage()->getState()); } else { // log a message that the job is still in progress \info(sprintf('Job %s is still in progress', $message->getMessageId())); } } else { // log a message that the job is still in progress \critical(sprintf('Message %s has been deleted, but should still be there', $message->getMessageId())); } break; // message failed case StateFailed::KEY: // remove the old job from the queue unset($jobsExecuting[$message->getMessageId()]); // query whether or not the message has to be processed again if (isset($messagesFailed[$message->getMessageId()]) && $message->getRetryCounter() > 0) { // query whether or not the message has to be processed now if ($messagesFailed[$message->getMessageId()] < time() && $retryCounter[$message->getMessageId()] < $message->getRetryCounter()) { // retry to process the message $message->setState(StateToProcess::get()); // update the execution time and raise the retry counter $messagesFailed[$message->getMessageId()] = time() + $message->getRetryTimeout($retryCounter[$message->getMessageId()]); $retryCounter[$message->getMessageId()]++; } elseif ($messagesFailed[$message->getMessageId()] < time() && $retryCounter[$message->getMessageId()] === $message->getRetryCounter()) { // log a message that we've a message with a unknown state \critical(sprintf('Message %s finally failed after %d retries', $message->getMessageId(), $retryCounter[$message->getMessageId()])); // stop executing the job because we've reached the maximum number of retries unset($jobsToExecute[$messageId = $message->getMessageId()]); unset($messagesFailed[$messageId]); unset($retryCounter[$messageId]); // invoke the callbacks for the state if ($message->hasCallbacks($message->getState())) { $callbacksToExecute[] = new Callback(clone $message, $application); } } else { // wait for the next try here } } elseif (!isset($messagesFailed[$message->getMessageId()]) && $message->getRetryCounter() > 0) { // first retry, so we've to initialize the next execution time and the retry counter $retryCounter[$message->getMessageId()] = 0; $messagesFailed[$message->getMessageId()] = time() + $message->getRetryTimeout($retryCounter[$message->getMessageId()]); } else { // log a message that we've a message with a unknown state \critical(sprintf('Message %s failed with NO retries', $message->getMessageId())); // stop executing the job because we've reached the maximum number of retries unset($jobsToExecute[$messageId = $message->getMessageId()]); // invoke the callbacks for the state if ($message->hasCallbacks($message->getState())) { $callbacksToExecute[] = new Callback(clone $message, $application); } } break; case StateToProcess::KEY: // count messages in queue $inQueue = sizeof($jobsExecuting); // we only process 200 jobs in parallel if ($inQueue < $maximumJobsToProcess) { // set the new message state now $message->setState(StateInProgress::get()); // start the job and add it to the internal array $jobsExecuting[$message->getMessageId()] = new Job(clone $message, $application); } else { // log a message that queue is actually full \info(sprintf('Job queue full - (%d jobs/%d msg wait)', $inQueue, sizeof($messages))); // if the job queue is full, restart iteration to remove processed jobs from queue first continue 2; } break; // message processing has been successfully processed case StateProcessed::KEY: // invoke the callbacks for the state if ($message->hasCallbacks($message->getState())) { $callbacksToExecute[] = new Callback(clone $message, $application); } // remove the job from the queue with jobs that has to be executed unset($jobsToExecute[$messageId = $message->getMessageId()]); // also remove the job + the message from the queue unset($jobsExecuting[$messageId]); unset($messages[$messageId]); break; // message is in an unknown state -> this is weired and should never happen! case StateUnknown::KEY: // log a message that we've a message with a unknown state \critical(sprintf('Message %s has state %s', $message->getMessageId(), $message->getState())); // set new state now $message->setState(StateFailed::get()); break; // we don't know the message state -> this is weired and should never happen! default: // set the failed message state $message->setState(StateFailed::get()); // log a message that we've a message with an invalid state \critical(sprintf('Message %s has an invalid state', $message->getMessageId())); break; } } // add the message back to the stack (because we've a copy here) if (isset($messages[$message->getMessageId()])) { $messages[$jobWrapper->jobId] = $message; } // catch all exceptions } catch (\Exception $e) { $application->getInitialContext()->getSystemLogger()->critical($e->__toString()); } // reduce CPU load depending on queue priority $this->iterate($this->getQueueTimeout()); } // reduce CPU load after each iteration $this->iterate($this->getDefaultTimeout()); // profile the size of the session pool if ($this->profileLogger) { $this->profileLogger->debug( sprintf( 'Processed queue worker with priority %s, size of queue size is: %d', $priorityKey, sizeof($jobsToExecute) ) ); } } // clean up the instances and free memory $this->cleanUp(); // mark the daemon as successfully shutdown $this->synchronized(function ($self) { $self->state = EnumState::get(EnumState::SHUTDOWN); }, $this); } catch (\Exception $e) { \error($e->__toString()); } }
[ "public", "function", "run", "(", ")", "{", "try", "{", "// register shutdown handler", "register_shutdown_function", "(", "$", "this", "->", "getDefaultShutdownMethod", "(", ")", ")", ";", "// bootstrap the daemon", "$", "this", "->", "bootstrap", "(", ")", ";", ...
We process the messages/jobs here. @return void
[ "We", "process", "the", "messages", "/", "jobs", "here", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/MessageQueue/QueueWorker.php#L226-L475
appserver-io/appserver
src/AppserverIo/Appserver/MessageQueue/QueueManagerFactory.php
QueueManagerFactory.visit
public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // initialize the stackable containers $queues = new GenericStackable(); $workers = new GenericStackable(); $messages = new GenericStackable(); // initialize the queue locator $queueLocator = new QueueLocator(); // initialize the default settings for message queue $queueManagerSettings = new QueueManagerSettings(); $queueManagerSettings->mergeWithParams($managerConfiguration->getParamsAsArray()); // initialize the queue manager $queueManager = new QueueManager(); $queueManager->injectQueues($queues); $queueManager->injectWorkers($workers); $queueManager->injectMessages($messages); $queueManager->injectApplication($application); $queueManager->injectResourceLocator($queueLocator); $queueManager->injectManagerSettings($queueManagerSettings); $queueManager->injectManagerConfiguration($managerConfiguration); // attach the instance $application->addManager($queueManager, $managerConfiguration); }
php
public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration) { // initialize the stackable containers $queues = new GenericStackable(); $workers = new GenericStackable(); $messages = new GenericStackable(); // initialize the queue locator $queueLocator = new QueueLocator(); // initialize the default settings for message queue $queueManagerSettings = new QueueManagerSettings(); $queueManagerSettings->mergeWithParams($managerConfiguration->getParamsAsArray()); // initialize the queue manager $queueManager = new QueueManager(); $queueManager->injectQueues($queues); $queueManager->injectWorkers($workers); $queueManager->injectMessages($messages); $queueManager->injectApplication($application); $queueManager->injectResourceLocator($queueLocator); $queueManager->injectManagerSettings($queueManagerSettings); $queueManager->injectManagerConfiguration($managerConfiguration); // attach the instance $application->addManager($queueManager, $managerConfiguration); }
[ "public", "static", "function", "visit", "(", "ApplicationInterface", "$", "application", ",", "ManagerNodeInterface", "$", "managerConfiguration", ")", "{", "// initialize the stackable containers", "$", "queues", "=", "new", "GenericStackable", "(", ")", ";", "$", "...
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
[ "The", "main", "method", "that", "creates", "new", "instances", "in", "a", "separate", "context", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/MessageQueue/QueueManagerFactory.php#L50-L77
appserver-io/appserver
src/AppserverIo/Appserver/ServletEngine/Utils/ErrorUtil.php
ErrorUtil.fromArray
public function fromArray(array $error) { // extract the array with the error information list ($type, $message, $file, $line) = array_values($error); // initialize and return the error instance return new Error($type, $message, $file, $line, ErrorUtil::singleton()->isFatal($type) ? 500 : 0); }
php
public function fromArray(array $error) { // extract the array with the error information list ($type, $message, $file, $line) = array_values($error); // initialize and return the error instance return new Error($type, $message, $file, $line, ErrorUtil::singleton()->isFatal($type) ? 500 : 0); }
[ "public", "function", "fromArray", "(", "array", "$", "error", ")", "{", "// extract the array with the error information", "list", "(", "$", "type", ",", "$", "message", ",", "$", "file", ",", "$", "line", ")", "=", "array_values", "(", "$", "error", ")", ...
Create's a new error instance with the values from the passed array. @param array $error The array containing the error information @return \AppserverIo\Appserver\Core\Utilities\ErrorInterface The error instance
[ "Create", "s", "a", "new", "error", "instance", "with", "the", "values", "from", "the", "passed", "array", "." ]
train
https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Utils/ErrorUtil.php#L64-L72