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/Application/Application.php | Application.search | public function search($name, array $args = array())
{
return $this->getNamingDirectory()->search(sprintf('php:global/%s/%s', $this->getUniqueName(), $name), $args);
} | php | public function search($name, array $args = array())
{
return $this->getNamingDirectory()->search(sprintf('php:global/%s/%s', $this->getUniqueName(), $name), $args);
} | [
"public",
"function",
"search",
"(",
"$",
"name",
",",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getNamingDirectory",
"(",
")",
"->",
"search",
"(",
"sprintf",
"(",
"'php:global/%s/%s'",
",",
"$",
"this",
"->... | Queries the naming directory for the requested name and returns the value
or invokes the bound callback.
@param string $name The name of the requested value
@param array $args The arguments to pass to the callback
@return mixed The requested value
@see \AppserverIo\Appserver\Naming\NamingDirectory::search() | [
"Queries",
"the",
"naming",
"directory",
"for",
"the",
"requested",
"name",
"and",
"returns",
"the",
"value",
"or",
"invokes",
"the",
"bound",
"callback",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Application/Application.php#L948-L951 |
appserver-io/appserver | src/AppserverIo/Appserver/Application/Application.php | Application.run | public function run()
{
try {
// register the default autoloader
require SERVER_AUTOLOADER;
// register shutdown handler
register_shutdown_function(array(&$this, "shutdown"));
// add the application instance to the environment
Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $this);
// 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);
// log a message that we now start to connect the application
$this->getInitialContext()->getSystemLogger()->debug(sprintf('%s wait to be connected', $this->getName()));
// register the class loaders
$this->registerClassLoaders();
// register the annotation registries
$this->registerAnnotationRegistries();
// initialize the managers
$this->initializeManagers();
// provision the application
if ($this->getContainer()->hasProvisioningEnabled()) {
$this->provision();
}
// initialize the profile logger and the thread context
$profileLogger = null;
/** @var \AppserverIo\Logger\ThreadSafeLoggerInterface $profileLogger */
if ($profileLogger = $this->getInitialContext()->getLogger(LoggerUtils::PROFILE)) {
$profileLogger->appendThreadContext('application');
}
// invoke the application's managers postStartup() lifecycle callbacks
$this->postStartupManagers();
// the application has successfully been initialized
$this->synchronized(function ($self) {
$self->applicationState = ApplicationStateKeys::get(ApplicationStateKeys::INITIALIZATION_SUCCESSFUL);
}, $this);
// log a message that we has successfully been connected now
\info(sprintf('%s has successfully been connected', $this->getName()));
// initialize the flag to keep the application running
$keepRunning = true;
// wait till application will be shutdown
while ($keepRunning) {
// query whether we've a profile logger, log resource usage
if ($profileLogger) {
$profileLogger->debug(sprintf('Application %s is running', $this->getName()));
}
// wait a second to lower system load
$keepRunning = $this->synchronized(function ($self) {
$self->wait(100000 * Application::TIME_TO_LIVE);
return $self->applicationState->equals(ApplicationStateKeys::get(ApplicationStateKeys::INITIALIZATION_SUCCESSFUL));
}, $this);
}
// log a message that we has successfully been shutdown now
\info(sprintf('%s start to shutdown managers', $this->getName()));
// array for the manager shutdown threads
$shutdownThreads = array();
// we need to stop all managers, because they've probably running threads
/** @var \AppserverIo\Psr\Application\ManagerInterface $manager */
foreach ($this->getManagers() as $manager) {
$shutdownThreads[] = new ManagerShutdownThread($manager);
}
// wait till all managers have been shutdown
/** @var \AppserverIo\Appserver\Application\ManagerShutdownThread $shutdownThread */
foreach ($shutdownThreads as $shutdownThread) {
$shutdownThread->join();
}
// the application has been shutdown successfully
$this->synchronized(function ($self) {
$self->applicationState = ApplicationStateKeys::get(ApplicationStateKeys::SHUTDOWN);
}, $this);
// cleanup the naming directory with the application entries
$this->unload();
// log a message that we has successfully been shutdown now
\info(sprintf('%s has successfully been shutdown', $this->getName()));
} catch (\Exception $e) {
LoggerUtils::log(LogLevel::ERROR, $e);
}
} | php | public function run()
{
try {
// register the default autoloader
require SERVER_AUTOLOADER;
// register shutdown handler
register_shutdown_function(array(&$this, "shutdown"));
// add the application instance to the environment
Environment::singleton()->setAttribute(EnvironmentKeys::APPLICATION, $this);
// 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);
// log a message that we now start to connect the application
$this->getInitialContext()->getSystemLogger()->debug(sprintf('%s wait to be connected', $this->getName()));
// register the class loaders
$this->registerClassLoaders();
// register the annotation registries
$this->registerAnnotationRegistries();
// initialize the managers
$this->initializeManagers();
// provision the application
if ($this->getContainer()->hasProvisioningEnabled()) {
$this->provision();
}
// initialize the profile logger and the thread context
$profileLogger = null;
/** @var \AppserverIo\Logger\ThreadSafeLoggerInterface $profileLogger */
if ($profileLogger = $this->getInitialContext()->getLogger(LoggerUtils::PROFILE)) {
$profileLogger->appendThreadContext('application');
}
// invoke the application's managers postStartup() lifecycle callbacks
$this->postStartupManagers();
// the application has successfully been initialized
$this->synchronized(function ($self) {
$self->applicationState = ApplicationStateKeys::get(ApplicationStateKeys::INITIALIZATION_SUCCESSFUL);
}, $this);
// log a message that we has successfully been connected now
\info(sprintf('%s has successfully been connected', $this->getName()));
// initialize the flag to keep the application running
$keepRunning = true;
// wait till application will be shutdown
while ($keepRunning) {
// query whether we've a profile logger, log resource usage
if ($profileLogger) {
$profileLogger->debug(sprintf('Application %s is running', $this->getName()));
}
// wait a second to lower system load
$keepRunning = $this->synchronized(function ($self) {
$self->wait(100000 * Application::TIME_TO_LIVE);
return $self->applicationState->equals(ApplicationStateKeys::get(ApplicationStateKeys::INITIALIZATION_SUCCESSFUL));
}, $this);
}
// log a message that we has successfully been shutdown now
\info(sprintf('%s start to shutdown managers', $this->getName()));
// array for the manager shutdown threads
$shutdownThreads = array();
// we need to stop all managers, because they've probably running threads
/** @var \AppserverIo\Psr\Application\ManagerInterface $manager */
foreach ($this->getManagers() as $manager) {
$shutdownThreads[] = new ManagerShutdownThread($manager);
}
// wait till all managers have been shutdown
/** @var \AppserverIo\Appserver\Application\ManagerShutdownThread $shutdownThread */
foreach ($shutdownThreads as $shutdownThread) {
$shutdownThread->join();
}
// the application has been shutdown successfully
$this->synchronized(function ($self) {
$self->applicationState = ApplicationStateKeys::get(ApplicationStateKeys::SHUTDOWN);
}, $this);
// cleanup the naming directory with the application entries
$this->unload();
// log a message that we has successfully been shutdown now
\info(sprintf('%s has successfully been shutdown', $this->getName()));
} catch (\Exception $e) {
LoggerUtils::log(LogLevel::ERROR, $e);
}
} | [
"public",
"function",
"run",
"(",
")",
"{",
"try",
"{",
"// register the default autoloader",
"require",
"SERVER_AUTOLOADER",
";",
"// register shutdown handler",
"register_shutdown_function",
"(",
"array",
"(",
"&",
"$",
"this",
",",
"\"shutdown\"",
")",
")",
";",
... | This is the threads main() method that initializes the application with the autoloader and
instantiates all the necessary manager instances.
@return void
@codeCoverageIgnore | [
"This",
"is",
"the",
"threads",
"main",
"()",
"method",
"that",
"initializes",
"the",
"application",
"with",
"the",
"autoloader",
"and",
"instantiates",
"all",
"the",
"necessary",
"manager",
"instances",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Application/Application.php#L960-L1061 |
appserver-io/appserver | src/AppserverIo/Appserver/Application/Application.php | Application.shutdown | public function shutdown()
{
// check if there was a fatal error caused shutdown
if ($lastError = error_get_last()) {
// initialize error type and 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) {
LoggerUtils::log(LogLevel::CRITICAL, $message);
}
}
} | php | public function shutdown()
{
// check if there was a fatal error caused shutdown
if ($lastError = error_get_last()) {
// initialize error type and 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) {
LoggerUtils::log(LogLevel::CRITICAL, $message);
}
}
} | [
"public",
"function",
"shutdown",
"(",
")",
"{",
"// check if there was a fatal error caused shutdown",
"if",
"(",
"$",
"lastError",
"=",
"error_get_last",
"(",
")",
")",
"{",
"// initialize error type and message",
"$",
"type",
"=",
"0",
";",
"$",
"message",
"=",
... | Shutdown function to log unexpected errors.
@return void
@see http://php.net/register_shutdown_function | [
"Shutdown",
"function",
"to",
"log",
"unexpected",
"errors",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Application/Application.php#L1069-L1084 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Security/Realm.php | Realm.authenticateByUsernameAndCallbackHandler | public function authenticateByUsernameAndCallbackHandler(String $username, CallbackHandlerInterface $callbackHandler)
{
try {
// initialize the subject and the configuration
$subject = new Subject();
$configuration = $this->getConfiguration();
// initialize the LoginContext and try to login the user
$loginContext = new LoginContext($subject, $callbackHandler, $configuration);
$loginContext->login();
// create and return a new Principal of the authenticated user
return $this->createPrincipal($username, $subject, $loginContext);
} catch (\Exception $e) {
// add the exception to the stack
$this->getExceptionStack()->add($e);
// load the system logger and debug log the exception
/** @var \Psr\Log\LoggerInterface $systemLogger */
if ($systemLogger = $this->getAuthenticationManager()->getApplication()->getNamingDirectory()->search(NamingDirectoryKeys::SYSTEM_LOGGER)) {
$systemLogger->error($e->__toString());
}
}
} | php | public function authenticateByUsernameAndCallbackHandler(String $username, CallbackHandlerInterface $callbackHandler)
{
try {
// initialize the subject and the configuration
$subject = new Subject();
$configuration = $this->getConfiguration();
// initialize the LoginContext and try to login the user
$loginContext = new LoginContext($subject, $callbackHandler, $configuration);
$loginContext->login();
// create and return a new Principal of the authenticated user
return $this->createPrincipal($username, $subject, $loginContext);
} catch (\Exception $e) {
// add the exception to the stack
$this->getExceptionStack()->add($e);
// load the system logger and debug log the exception
/** @var \Psr\Log\LoggerInterface $systemLogger */
if ($systemLogger = $this->getAuthenticationManager()->getApplication()->getNamingDirectory()->search(NamingDirectoryKeys::SYSTEM_LOGGER)) {
$systemLogger->error($e->__toString());
}
}
} | [
"public",
"function",
"authenticateByUsernameAndCallbackHandler",
"(",
"String",
"$",
"username",
",",
"CallbackHandlerInterface",
"$",
"callbackHandler",
")",
"{",
"try",
"{",
"// initialize the subject and the configuration",
"$",
"subject",
"=",
"new",
"Subject",
"(",
... | Finally tries to authenticate the user with the passed name.
@param \AppserverIo\Lang\String $username The name of the user to authenticate
@param \AppserverIo\Psr\Security\Auth\Callback\CallbackHandlerInterface $callbackHandler The callback handler used to load the credentials
@return \AppserverIo\Psr\Security\PrincipalInterface|null The authenticated user principal | [
"Finally",
"tries",
"to",
"authenticate",
"the",
"user",
"with",
"the",
"passed",
"name",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Security/Realm.php#L155-L179 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Security/Realm.php | Realm.authenticate | public function authenticate(String $username, String $password)
{
// prepare the callback handler
$callbackHandler = new SecurityAssociationHandler(new SimplePrincipal($username), $password);
// authenticate the passed username/password combination
return $this->authenticateByUsernameAndCallbackHandler($username, $callbackHandler);
} | php | public function authenticate(String $username, String $password)
{
// prepare the callback handler
$callbackHandler = new SecurityAssociationHandler(new SimplePrincipal($username), $password);
// authenticate the passed username/password combination
return $this->authenticateByUsernameAndCallbackHandler($username, $callbackHandler);
} | [
"public",
"function",
"authenticate",
"(",
"String",
"$",
"username",
",",
"String",
"$",
"password",
")",
"{",
"// prepare the callback handler",
"$",
"callbackHandler",
"=",
"new",
"SecurityAssociationHandler",
"(",
"new",
"SimplePrincipal",
"(",
"$",
"username",
... | Finally tries to authenticate the user with the passed name.
@param \AppserverIo\Lang\String $username The name of the user to authenticate
@param \AppserverIo\Lang\String $password The password used for authentication
@return \AppserverIo\Psr\Security\PrincipalInterface|null The authenticated user principal | [
"Finally",
"tries",
"to",
"authenticate",
"the",
"user",
"with",
"the",
"passed",
"name",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Security/Realm.php#L189-L197 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Security/Realm.php | Realm.createPrincipal | protected function createPrincipal(String $username, Subject $subject, LoginContextInterface $loginContext)
{
// initialize the roles and the user principal
$roles = new ArrayList();
$userPrincipal = null;
// scan the Principals for this Subject
foreach ($subject->getPrincipals() as $principal) {
// query whether or not the principal found is a group principal
if ($principal instanceof GroupInterface && $principal->getName()->equals(new String(Util::DEFAULT_GROUP_NAME))) {
// if yes, add the role name
foreach ($principal->getMembers() as $role) {
$roles->add($role->getName());
}
// query whether or not the principal found is a user principal
} elseif ($userPrincipal == null && $principal instanceof PrincipalInterface) {
$userPrincipal = $principal;
} else {
// do nothing, because we've no principal or group to deal with
}
}
// return the resulting Principal for our authenticated user
return new GenericPrincipal($username, null, $roles, $userPrincipal);
} | php | protected function createPrincipal(String $username, Subject $subject, LoginContextInterface $loginContext)
{
// initialize the roles and the user principal
$roles = new ArrayList();
$userPrincipal = null;
// scan the Principals for this Subject
foreach ($subject->getPrincipals() as $principal) {
// query whether or not the principal found is a group principal
if ($principal instanceof GroupInterface && $principal->getName()->equals(new String(Util::DEFAULT_GROUP_NAME))) {
// if yes, add the role name
foreach ($principal->getMembers() as $role) {
$roles->add($role->getName());
}
// query whether or not the principal found is a user principal
} elseif ($userPrincipal == null && $principal instanceof PrincipalInterface) {
$userPrincipal = $principal;
} else {
// do nothing, because we've no principal or group to deal with
}
}
// return the resulting Principal for our authenticated user
return new GenericPrincipal($username, null, $roles, $userPrincipal);
} | [
"protected",
"function",
"createPrincipal",
"(",
"String",
"$",
"username",
",",
"Subject",
"$",
"subject",
",",
"LoginContextInterface",
"$",
"loginContext",
")",
"{",
"// initialize the roles and the user principal",
"$",
"roles",
"=",
"new",
"ArrayList",
"(",
")",
... | Identify and return an instance implementing the PrincipalInterface that represens the
authenticated user for the specified Subject. The Principal is constructed by scanning
the list of Principals returned by the LoginModule. The first Principal object that
matches one of the class names supplied as a "user class" is the user Principal. This
object is returned to the caller. Any remaining principal objects returned by the
LoginModules are mapped to roles, but only if their respective classes match one of the
"role class" classes. If a user Principal cannot be constructed, return NULL.
@param \AppserverIo\Lang\String $username The associated user name
@param \AppserverIo\Psr\Security\Auth\Subject $subject The Subject representing the logged-in user
@param \AppserverIo\Psr\Security\Auth\Login\LoginContextInterface $loginContext Associated with the Principal so {@link LoginContext#logout()} can be called later
@return \AppserverIo\Psr\Security\PrincipalInterface the principal object | [
"Identify",
"and",
"return",
"an",
"instance",
"implementing",
"the",
"PrincipalInterface",
"that",
"represens",
"the",
"authenticated",
"user",
"for",
"the",
"specified",
"Subject",
".",
"The",
"Principal",
"is",
"constructed",
"by",
"scanning",
"the",
"list",
"o... | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Security/Realm.php#L214-L240 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/ExtensionInjectorParameterTrait.php | ExtensionInjectorParameterTrait.initExtensionType | protected function initExtensionType()
{
// We have to get the class of our injector
$class = '';
if (!class_exists($class = $this->extensionType) &&
!class_exists($class = strstr($this->extensionType, '(', true))) {
throw new \Exception('Unknown injector class ' . $class);
}
// We also have to get the parameter
$parameters = array();
preg_match('`\((.+)\)`', $this->getExtensionType(), $parameters);
// Clean them up and separate them
$parameterString = str_replace(array(' ', '\''), array(''), $parameters[1]);
$clearParameters = explode(',', $parameterString);
// Instantiate the injector and init it
$this->injector = new $class($clearParameters[0], $clearParameters[1], $clearParameters[2]);
$this->injector->init();
} | php | protected function initExtensionType()
{
// We have to get the class of our injector
$class = '';
if (!class_exists($class = $this->extensionType) &&
!class_exists($class = strstr($this->extensionType, '(', true))) {
throw new \Exception('Unknown injector class ' . $class);
}
// We also have to get the parameter
$parameters = array();
preg_match('`\((.+)\)`', $this->getExtensionType(), $parameters);
// Clean them up and separate them
$parameterString = str_replace(array(' ', '\''), array(''), $parameters[1]);
$clearParameters = explode(',', $parameterString);
// Instantiate the injector and init it
$this->injector = new $class($clearParameters[0], $clearParameters[1], $clearParameters[2]);
$this->injector->init();
} | [
"protected",
"function",
"initExtensionType",
"(",
")",
"{",
"// We have to get the class of our injector",
"$",
"class",
"=",
"''",
";",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"class",
"=",
"$",
"this",
"->",
"extensionType",
")",
"&&",
"!",
"class_exists",
... | Will init the injector from the given extensionType
@return null
@throws \Exception | [
"Will",
"init",
"the",
"injector",
"from",
"the",
"given",
"extensionType"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/ExtensionInjectorParameterTrait.php#L57-L77 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.chmod | public static function chmod($path, $perm)
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// change the mode
if (chmod($path, $perm) === false) {
throw new \Exception(sprintf('Can\'t change mode for directory %s to %s', $path, $perm));
}
} | php | public static function chmod($path, $perm)
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// change the mode
if (chmod($path, $perm) === false) {
throw new \Exception(sprintf('Can\'t change mode for directory %s to %s', $path, $perm));
}
} | [
"public",
"static",
"function",
"chmod",
"(",
"$",
"path",
",",
"$",
"perm",
")",
"{",
"// don't do anything under Windows",
"if",
"(",
"FileSystem",
"::",
"getOsIdentifier",
"(",
")",
"===",
"self",
"::",
"OS_IDENTIFIER_WIN",
")",
"{",
"return",
";",
"}",
"... | Chmod function
@param string $path Relative or absolute path to a file or directory which should be processed.
@param int $perm The permissions any file or dir should get.
@return bool | [
"Chmod",
"function"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L57-L69 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.chown | public static function chown($path, $user, $group = null)
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// check if the path exists
if (!file_exists($path)) {
return false;
}
// change the owner
if (chown($path, $user) === false) {
throw new \Exception(sprintf('Can\'t change owner for directory/flie %s to %s', $path, $user));
}
// check if group is given too
if (!is_null($group)) {
if (chgrp($path, $group) === false) {
throw new \Exception(sprintf('Can\'t change group for directory/flie %s to %s', $path, $group));
}
}
return true;
} | php | public static function chown($path, $user, $group = null)
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// check if the path exists
if (!file_exists($path)) {
return false;
}
// change the owner
if (chown($path, $user) === false) {
throw new \Exception(sprintf('Can\'t change owner for directory/flie %s to %s', $path, $user));
}
// check if group is given too
if (!is_null($group)) {
if (chgrp($path, $group) === false) {
throw new \Exception(sprintf('Can\'t change group for directory/flie %s to %s', $path, $group));
}
}
return true;
} | [
"public",
"static",
"function",
"chown",
"(",
"$",
"path",
",",
"$",
"user",
",",
"$",
"group",
"=",
"null",
")",
"{",
"// don't do anything under Windows",
"if",
"(",
"FileSystem",
"::",
"getOsIdentifier",
"(",
")",
"===",
"self",
"::",
"OS_IDENTIFIER_WIN",
... | Chown function
@param string $path Relative or absolute path to a file or directory which should be processed.
@param int $user The user that should gain owner rights.
@param int|null $group The group that should gain group rights.
@return bool | [
"Chown",
"function"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L80-L106 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.cleanUpDir | public static function cleanUpDir(\SplFileInfo $dir, $alsoRemoveFiles = true)
{
// first check if the directory exists, if not return immediately
if ($dir->isDir() === false) {
return;
}
// remove old archive from webapps folder recursively
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir->getPathname()),
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
// skip . and .. dirs
if ($file->getFilename() === '.' || $file->getFilename() === '..') {
continue;
}
if ($file->isDir()) {
@rmdir($file->getRealPath());
} elseif ($file->isFile() && $alsoRemoveFiles) {
unlink($file->getRealPath());
} else {
// do nothing, because file should NOT be deleted obviously
}
}
} | php | public static function cleanUpDir(\SplFileInfo $dir, $alsoRemoveFiles = true)
{
// first check if the directory exists, if not return immediately
if ($dir->isDir() === false) {
return;
}
// remove old archive from webapps folder recursively
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir->getPathname()),
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
// skip . and .. dirs
if ($file->getFilename() === '.' || $file->getFilename() === '..') {
continue;
}
if ($file->isDir()) {
@rmdir($file->getRealPath());
} elseif ($file->isFile() && $alsoRemoveFiles) {
unlink($file->getRealPath());
} else {
// do nothing, because file should NOT be deleted obviously
}
}
} | [
"public",
"static",
"function",
"cleanUpDir",
"(",
"\\",
"SplFileInfo",
"$",
"dir",
",",
"$",
"alsoRemoveFiles",
"=",
"true",
")",
"{",
"// first check if the directory exists, if not return immediately",
"if",
"(",
"$",
"dir",
"->",
"isDir",
"(",
")",
"===",
"fal... | Deletes all files and subdirectories from the passed directory.
@param \SplFileInfo $dir The directory to remove
@param bool $alsoRemoveFiles The flag for removing files also
@return void | [
"Deletes",
"all",
"files",
"and",
"subdirectories",
"from",
"the",
"passed",
"directory",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L116-L143 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.removeDir | public static function removeDir($src)
{
// open the directory
$dir = opendir($src);
// remove files/folders recursively
while (false !== ($file = readdir($dir))) {
if (($file != '.') && ($file != '..')) {
$full = $src . '/' . $file;
if (is_dir($full)) {
FileSystem::removeDir($full);
} else {
unlink($full);
}
}
}
// close handle and remove directory itself
closedir($dir);
rmdir($src);
} | php | public static function removeDir($src)
{
// open the directory
$dir = opendir($src);
// remove files/folders recursively
while (false !== ($file = readdir($dir))) {
if (($file != '.') && ($file != '..')) {
$full = $src . '/' . $file;
if (is_dir($full)) {
FileSystem::removeDir($full);
} else {
unlink($full);
}
}
}
// close handle and remove directory itself
closedir($dir);
rmdir($src);
} | [
"public",
"static",
"function",
"removeDir",
"(",
"$",
"src",
")",
"{",
"// open the directory",
"$",
"dir",
"=",
"opendir",
"(",
"$",
"src",
")",
";",
"// remove files/folders recursively",
"while",
"(",
"false",
"!==",
"(",
"$",
"file",
"=",
"readdir",
"("... | Removes a directory recursively.
@param string $src The source directory to be removed
@return void | [
"Removes",
"a",
"directory",
"recursively",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L152-L173 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.copyDir | public static function copyDir($src, $dst)
{
if (is_link($src)) {
symlink(readlink($src), $dst);
} elseif (is_dir($src)) {
if (is_dir($dst) === false) {
mkdir($dst, 0775, true);
}
// copy files recursive
foreach (scandir($src) as $file) {
if ($file != '.' && $file != '..') {
FileSystem::copyDir("$src/$file", "$dst/$file");
}
}
} elseif (is_file($src)) {
copy($src, $dst);
} else {
// do nothing, we didn't have a directory to copy
}
} | php | public static function copyDir($src, $dst)
{
if (is_link($src)) {
symlink(readlink($src), $dst);
} elseif (is_dir($src)) {
if (is_dir($dst) === false) {
mkdir($dst, 0775, true);
}
// copy files recursive
foreach (scandir($src) as $file) {
if ($file != '.' && $file != '..') {
FileSystem::copyDir("$src/$file", "$dst/$file");
}
}
} elseif (is_file($src)) {
copy($src, $dst);
} else {
// do nothing, we didn't have a directory to copy
}
} | [
"public",
"static",
"function",
"copyDir",
"(",
"$",
"src",
",",
"$",
"dst",
")",
"{",
"if",
"(",
"is_link",
"(",
"$",
"src",
")",
")",
"{",
"symlink",
"(",
"readlink",
"(",
"$",
"src",
")",
",",
"$",
"dst",
")",
";",
"}",
"elseif",
"(",
"is_di... | Copies a directory recursively.
@param string $src The source directory to copy
@param string $dst The target directory
@return void | [
"Copies",
"a",
"directory",
"recursively",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L183-L203 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.createDirectory | public static function createDirectory($directoryToCreate, $mode = 0775, $recursive = false)
{
// we don't have a directory to change the user/group permissions for
if (is_dir($directoryToCreate) === false) {
// create the directory if necessary
if (mkdir($directoryToCreate, $mode, $recursive) === false) {
throw new \Exception(sprintf('Directory %s can\'t be created', $directoryToCreate));
}
}
} | php | public static function createDirectory($directoryToCreate, $mode = 0775, $recursive = false)
{
// we don't have a directory to change the user/group permissions for
if (is_dir($directoryToCreate) === false) {
// create the directory if necessary
if (mkdir($directoryToCreate, $mode, $recursive) === false) {
throw new \Exception(sprintf('Directory %s can\'t be created', $directoryToCreate));
}
}
} | [
"public",
"static",
"function",
"createDirectory",
"(",
"$",
"directoryToCreate",
",",
"$",
"mode",
"=",
"0775",
",",
"$",
"recursive",
"=",
"false",
")",
"{",
"// we don't have a directory to change the user/group permissions for",
"if",
"(",
"is_dir",
"(",
"$",
"d... | Creates the passed directory.
@param string $directoryToCreate The directory that should be created
@param integer $mode The mode to create the directory with
@param boolean $recursive TRUE if the directory has to be created recursively, else FALSE
@return void
@throws \Exception Is thrown if the directory can't be created | [
"Creates",
"the",
"passed",
"directory",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L215-L225 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.initUmask | public static function initUmask($umask)
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// set new umask to use
umask($umask);
// query whether the new umask has been set or not
if (umask() != $umask) {
throw new \Exception(sprintf('Can\'t set umask \'%s\' found \'%\' instead', $umask, umask()));
}
} | php | public static function initUmask($umask)
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// set new umask to use
umask($umask);
// query whether the new umask has been set or not
if (umask() != $umask) {
throw new \Exception(sprintf('Can\'t set umask \'%s\' found \'%\' instead', $umask, umask()));
}
} | [
"public",
"static",
"function",
"initUmask",
"(",
"$",
"umask",
")",
"{",
"// don't do anything under Windows",
"if",
"(",
"FileSystem",
"::",
"getOsIdentifier",
"(",
")",
"===",
"self",
"::",
"OS_IDENTIFIER_WIN",
")",
"{",
"return",
";",
"}",
"// set new umask to... | Init the umask to use creating files/directories, either with
the passed value or the one found in the configuration.
@param integer $umask The new umask to set
@return void
@throws \Exception Is thrown if the umask can not be set | [
"Init",
"the",
"umask",
"to",
"use",
"creating",
"files",
"/",
"directories",
"either",
"with",
"the",
"passed",
"value",
"or",
"the",
"one",
"found",
"in",
"the",
"configuration",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L236-L251 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.globDir | public static function globDir($pattern, $flags = 0, $recursive = true)
{
// parse the first directory
$files = glob($pattern, $flags);
// parse all subdirectories, if recursive parsing is wanted
if ($recursive !== false) {
foreach (glob(dirname($pattern). DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR|GLOB_NOSORT|GLOB_BRACE) as $dir) {
$files = array_merge($files, FileSystem::globDir($dir . DIRECTORY_SEPARATOR . basename($pattern), $flags));
}
}
// return the array with the files matching the glob pattern
return $files;
} | php | public static function globDir($pattern, $flags = 0, $recursive = true)
{
// parse the first directory
$files = glob($pattern, $flags);
// parse all subdirectories, if recursive parsing is wanted
if ($recursive !== false) {
foreach (glob(dirname($pattern). DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR|GLOB_NOSORT|GLOB_BRACE) as $dir) {
$files = array_merge($files, FileSystem::globDir($dir . DIRECTORY_SEPARATOR . basename($pattern), $flags));
}
}
// return the array with the files matching the glob pattern
return $files;
} | [
"public",
"static",
"function",
"globDir",
"(",
"$",
"pattern",
",",
"$",
"flags",
"=",
"0",
",",
"$",
"recursive",
"=",
"true",
")",
"{",
"// parse the first directory",
"$",
"files",
"=",
"glob",
"(",
"$",
"pattern",
",",
"$",
"flags",
")",
";",
"// ... | Parses and returns the directories and files that matches
the passed glob pattern in a recursive way (if wanted).
@param string $pattern The glob pattern used to parse the directories
@param integer $flags The flags passed to the glob function
@param boolean $recursive Whether or not to parse directories recursively
@return array The directories matches the passed glob pattern
@link http://php.net/glob | [
"Parses",
"and",
"returns",
"the",
"directories",
"and",
"files",
"that",
"matches",
"the",
"passed",
"glob",
"pattern",
"in",
"a",
"recursive",
"way",
"(",
"if",
"wanted",
")",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L274-L289 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.recursiveChown | public static function recursiveChown($path, $user, $group = null)
{
// we don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// we don't have a directory to change the user/group permissions for
if (is_dir($path) === false) {
return;
}
// get all the files recursively
$files = FileSystem::globDir($path . '/*');
// query whether we've a user passed
if (empty($user) === false) {
// Change the rights of everything within the defined dirs
foreach ($files as $file) {
FileSystem::chown($file, $user, $group);
}
FileSystem::chown($path, $user, $group);
}
} | php | public static function recursiveChown($path, $user, $group = null)
{
// we don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// we don't have a directory to change the user/group permissions for
if (is_dir($path) === false) {
return;
}
// get all the files recursively
$files = FileSystem::globDir($path . '/*');
// query whether we've a user passed
if (empty($user) === false) {
// Change the rights of everything within the defined dirs
foreach ($files as $file) {
FileSystem::chown($file, $user, $group);
}
FileSystem::chown($path, $user, $group);
}
} | [
"public",
"static",
"function",
"recursiveChown",
"(",
"$",
"path",
",",
"$",
"user",
",",
"$",
"group",
"=",
"null",
")",
"{",
"// we don't do anything under Windows",
"if",
"(",
"FileSystem",
"::",
"getOsIdentifier",
"(",
")",
"===",
"self",
"::",
"OS_IDENTI... | Will set the owner and group on the passed directory.
@param string $path The directory to set the rights for
@param string $user The user to set
@param string $group The group to set
@return void | [
"Will",
"set",
"the",
"owner",
"and",
"group",
"on",
"the",
"passed",
"directory",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L300-L324 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Utilities/FileSystem.php | FileSystem.recursiveChmod | public static function recursiveChmod($path, $filePerm = 0644, $dirPerm = 0755)
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// check if the directory exists
if (is_dir($path) === false) {
return false;
}
// get all the files recursively
$files = FileSystem::globDir($path . '/*');
// iterate over all directories and files
foreach ($files as $file) {
// see whether this is a file
if (is_file($file)) {
// chmod the file with our given file permissions
FileSystem::chmod($file, $filePerm);
// if this is a directory...
} elseif (is_dir($file)) {
// chmod the directory itself
FileSystem::chmod($file, $dirPerm);
}
}
// change the permmissions of the directory itself
FileSystem::chmod($path, $dirPerm);
} | php | public static function recursiveChmod($path, $filePerm = 0644, $dirPerm = 0755)
{
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === self::OS_IDENTIFIER_WIN) {
return;
}
// check if the directory exists
if (is_dir($path) === false) {
return false;
}
// get all the files recursively
$files = FileSystem::globDir($path . '/*');
// iterate over all directories and files
foreach ($files as $file) {
// see whether this is a file
if (is_file($file)) {
// chmod the file with our given file permissions
FileSystem::chmod($file, $filePerm);
// if this is a directory...
} elseif (is_dir($file)) {
// chmod the directory itself
FileSystem::chmod($file, $dirPerm);
}
}
// change the permmissions of the directory itself
FileSystem::chmod($path, $dirPerm);
} | [
"public",
"static",
"function",
"recursiveChmod",
"(",
"$",
"path",
",",
"$",
"filePerm",
"=",
"0644",
",",
"$",
"dirPerm",
"=",
"0755",
")",
"{",
"// don't do anything under Windows",
"if",
"(",
"FileSystem",
"::",
"getOsIdentifier",
"(",
")",
"===",
"self",
... | Chmods files and folders with different permissions.
This is an all-PHP alternative to using: \n
<tt>exec("find ".$path." -type f -exec chmod 644 {} \;");</tt> \n
<tt>exec("find ".$path." -type d -exec chmod 755 {} \;");</tt>
@param string $path Relative or absolute path to a file or directory which should be processed.
@param int $filePerm The permissions any found files should get.
@param int $dirPerm The permissions any found folder should get.
@return void | [
"Chmods",
"files",
"and",
"folders",
"with",
"different",
"permissions",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Utilities/FileSystem.php#L339-L370 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Http/Session.php | Session.init | public function init($id, $name, $lifetime, $maximumAge, $domain, $path, $secure, $httpOnly, $lastActivityTimestamp = null)
{
// initialize the session
$this->id = $id;
$this->name = $name;
$this->lifetime = $lifetime;
$this->maximumAge = $maximumAge;
$this->domain = $domain;
$this->path = $path;
$this->secure = $secure;
$this->httpOnly = $httpOnly;
// the UNIX timestamp where the last action on this session happens
if ($lastActivityTimestamp == null) {
$this->lastActivityTimestamp = time();
} else {
$this->lastActivityTimestamp = $lastActivityTimestamp;
}
} | php | public function init($id, $name, $lifetime, $maximumAge, $domain, $path, $secure, $httpOnly, $lastActivityTimestamp = null)
{
// initialize the session
$this->id = $id;
$this->name = $name;
$this->lifetime = $lifetime;
$this->maximumAge = $maximumAge;
$this->domain = $domain;
$this->path = $path;
$this->secure = $secure;
$this->httpOnly = $httpOnly;
// the UNIX timestamp where the last action on this session happens
if ($lastActivityTimestamp == null) {
$this->lastActivityTimestamp = time();
} else {
$this->lastActivityTimestamp = $lastActivityTimestamp;
}
} | [
"public",
"function",
"init",
"(",
"$",
"id",
",",
"$",
"name",
",",
"$",
"lifetime",
",",
"$",
"maximumAge",
",",
"$",
"domain",
",",
"$",
"path",
",",
"$",
"secure",
",",
"$",
"httpOnly",
",",
"$",
"lastActivityTimestamp",
"=",
"null",
")",
"{",
... | Initializes the session with the passed data.
@param mixed $id The session ID
@param string $name The session name
@param integer|\DateTime $lifetime Date and time after the session expires
@param integer|null $maximumAge Number of seconds until the session expires
@param string|null $domain The host to which the user agent will send this cookie
@param string $path The path describing the scope of this cookie
@param boolean $secure If this cookie should only be sent through a "secure" channel by the user agent
@param boolean $httpOnly If this cookie should only be used through the HTTP protocol
@param integer|null $lastActivityTimestamp The timestamp when the session has been touched the last time
@return void | [
"Initializes",
"the",
"session",
"with",
"the",
"passed",
"data",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Session.php#L95-L113 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Http/Session.php | Session.checksum | public function checksum()
{
// create an array with the data we want to add to a checksum
$checksumData = array($this->started, $this->id, $this->name, $this->data);
// create the checksum and return it
return md5(json_encode($checksumData));
} | php | public function checksum()
{
// create an array with the data we want to add to a checksum
$checksumData = array($this->started, $this->id, $this->name, $this->data);
// create the checksum and return it
return md5(json_encode($checksumData));
} | [
"public",
"function",
"checksum",
"(",
")",
"{",
"// create an array with the data we want to add to a checksum",
"$",
"checksumData",
"=",
"array",
"(",
"$",
"this",
"->",
"started",
",",
"$",
"this",
"->",
"id",
",",
"$",
"this",
"->",
"name",
",",
"$",
"thi... | Returns the checksum for this session instance.
@return string The checksum | [
"Returns",
"the",
"checksum",
"for",
"this",
"session",
"instance",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Session.php#L415-L423 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Http/Session.php | Session.resume | public function resume()
{
if ($this->canBeResumed()) {
$lastActivitySecondsAgo = (time() - $this->getLastActivityTimestamp());
$this->lastActivityTimestamp = time();
return $lastActivitySecondsAgo;
}
} | php | public function resume()
{
if ($this->canBeResumed()) {
$lastActivitySecondsAgo = (time() - $this->getLastActivityTimestamp());
$this->lastActivityTimestamp = time();
return $lastActivitySecondsAgo;
}
} | [
"public",
"function",
"resume",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"canBeResumed",
"(",
")",
")",
"{",
"$",
"lastActivitySecondsAgo",
"=",
"(",
"time",
"(",
")",
"-",
"$",
"this",
"->",
"getLastActivityTimestamp",
"(",
")",
")",
";",
"$",
"... | Resumes an existing session, if any.
@return integer If a session was resumed, the inactivity of since the last request is returned | [
"Resumes",
"an",
"existing",
"session",
"if",
"any",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Session.php#L447-L454 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Http/Session.php | Session.emptyInstance | public static function emptyInstance()
{
// extract the values
$id = null;
$name = 'empty';
$lifetime = -1;
$maximumAge = -1;
$domain = '';
$path = '';
$secure = false;
$httpOnly = false;
// initialize and return the empty instance
return new Session($id, $name, $lifetime, $maximumAge, $domain, $path, $secure, $httpOnly);
} | php | public static function emptyInstance()
{
// extract the values
$id = null;
$name = 'empty';
$lifetime = -1;
$maximumAge = -1;
$domain = '';
$path = '';
$secure = false;
$httpOnly = false;
// initialize and return the empty instance
return new Session($id, $name, $lifetime, $maximumAge, $domain, $path, $secure, $httpOnly);
} | [
"public",
"static",
"function",
"emptyInstance",
"(",
")",
"{",
"// extract the values",
"$",
"id",
"=",
"null",
";",
"$",
"name",
"=",
"'empty'",
";",
"$",
"lifetime",
"=",
"-",
"1",
";",
"$",
"maximumAge",
"=",
"-",
"1",
";",
"$",
"domain",
"=",
"'... | Creates a new and empty session instance.
@return \AppserverIo\Psr\Servlet\ServletSessionInterface The empty, but initialized session instance | [
"Creates",
"a",
"new",
"and",
"empty",
"session",
"instance",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Session.php#L461-L476 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Http/Session.php | Session.destroy | public function destroy($reason)
{
$this->id = null;
$this->lifetime = 0;
$this->lastActivityTimestamp = 0;
$this->maximumAge = -1;
} | php | public function destroy($reason)
{
$this->id = null;
$this->lifetime = 0;
$this->lastActivityTimestamp = 0;
$this->maximumAge = -1;
} | [
"public",
"function",
"destroy",
"(",
"$",
"reason",
")",
"{",
"$",
"this",
"->",
"id",
"=",
"null",
";",
"$",
"this",
"->",
"lifetime",
"=",
"0",
";",
"$",
"this",
"->",
"lastActivityTimestamp",
"=",
"0",
";",
"$",
"this",
"->",
"maximumAge",
"=",
... | Explicitly destroys all session data.
@param string $reason The reason why the session has been destroyed
@return void | [
"Explicitly",
"destroys",
"all",
"session",
"data",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Session.php#L485-L491 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Http/Session.php | Session.autoExpire | protected function autoExpire()
{
$lastActivitySecondsAgo = time() - $this->getLastActivityTimestamp();
$expired = false;
if ($this->getMaximumAge() !== 0 && $lastActivitySecondsAgo > $this->getMaximumAge()) {
$this->destroy(sprintf('Session %s was inactive for %s seconds, more than the configured timeout of %s seconds.', $this->getId(), $lastActivitySecondsAgo, $this->getMaximumAge()));
$expired = true;
}
return $expired;
} | php | protected function autoExpire()
{
$lastActivitySecondsAgo = time() - $this->getLastActivityTimestamp();
$expired = false;
if ($this->getMaximumAge() !== 0 && $lastActivitySecondsAgo > $this->getMaximumAge()) {
$this->destroy(sprintf('Session %s was inactive for %s seconds, more than the configured timeout of %s seconds.', $this->getId(), $lastActivitySecondsAgo, $this->getMaximumAge()));
$expired = true;
}
return $expired;
} | [
"protected",
"function",
"autoExpire",
"(",
")",
"{",
"$",
"lastActivitySecondsAgo",
"=",
"time",
"(",
")",
"-",
"$",
"this",
"->",
"getLastActivityTimestamp",
"(",
")",
";",
"$",
"expired",
"=",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"getMaximumAge",... | Automatically expires the session if the user has been inactive for too long.
@return boolean TRUE if the session expired, FALSE if not | [
"Automatically",
"expires",
"the",
"session",
"if",
"the",
"user",
"has",
"been",
"inactive",
"for",
"too",
"long",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Http/Session.php#L498-L507 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php | AbstractScanner.init | public function init()
{
// initialize the service class
$this->service = $this->newService('AppserverIo\Appserver\Core\Api\ContainerService');
//We will check the distribution type by it's release file, as we have problems doing so using php_uname('s').
//These mappings are for the most common platforms. If others are needed see the link below
//@link http://linuxmafia.com/faq/Admin/release-files.html
$this->distroMapping = array(
"Arch" => "arch-release",
"Debian" => "debian_version",
"Fedora" => "fedora-release",
"Ubuntu" => "lsb-release",
'Redhat' => 'redhat-release',
'CentOS' => 'centos-release'
);
// initialize the available restart commands
$this->restartCommands = array(
DeploymentScanner::DARWIN => DeploymentScanner::LAUNCHD_INIT_STRING,
DeploymentScanner::WINDOWS_NT => DeploymentScanner::WIN_NT_INIT_STRING,
'Debian' . DeploymentScanner::LINUX => array(
6 => DeploymentScanner::SYSTEMV_INIT_STRING,
7 => DeploymentScanner::SYSTEMV_INIT_STRING,
'default' => DeploymentScanner::SYSTEMD_INIT_STRING
),
'Ubuntu' . DeploymentScanner::LINUX => array(
12 => DeploymentScanner::SYSTEMV_INIT_STRING,
13 => DeploymentScanner::SYSTEMV_INIT_STRING,
14 => DeploymentScanner::SYSTEMV_INIT_STRING,
'default' => DeploymentScanner::SYSTEMD_INIT_STRING
),
'CentOS' . DeploymentScanner::LINUX => array(
5 => DeploymentScanner::SYSTEMV_INIT_STRING,
6 => DeploymentScanner::SYSTEMV_INIT_STRING,
'default' => DeploymentScanner::SYSTEMD_INIT_STRING
),
'Fedora' . DeploymentScanner::LINUX => DeploymentScanner::SYSTEMD_INIT_STRING
);
} | php | public function init()
{
// initialize the service class
$this->service = $this->newService('AppserverIo\Appserver\Core\Api\ContainerService');
//We will check the distribution type by it's release file, as we have problems doing so using php_uname('s').
//These mappings are for the most common platforms. If others are needed see the link below
//@link http://linuxmafia.com/faq/Admin/release-files.html
$this->distroMapping = array(
"Arch" => "arch-release",
"Debian" => "debian_version",
"Fedora" => "fedora-release",
"Ubuntu" => "lsb-release",
'Redhat' => 'redhat-release',
'CentOS' => 'centos-release'
);
// initialize the available restart commands
$this->restartCommands = array(
DeploymentScanner::DARWIN => DeploymentScanner::LAUNCHD_INIT_STRING,
DeploymentScanner::WINDOWS_NT => DeploymentScanner::WIN_NT_INIT_STRING,
'Debian' . DeploymentScanner::LINUX => array(
6 => DeploymentScanner::SYSTEMV_INIT_STRING,
7 => DeploymentScanner::SYSTEMV_INIT_STRING,
'default' => DeploymentScanner::SYSTEMD_INIT_STRING
),
'Ubuntu' . DeploymentScanner::LINUX => array(
12 => DeploymentScanner::SYSTEMV_INIT_STRING,
13 => DeploymentScanner::SYSTEMV_INIT_STRING,
14 => DeploymentScanner::SYSTEMV_INIT_STRING,
'default' => DeploymentScanner::SYSTEMD_INIT_STRING
),
'CentOS' . DeploymentScanner::LINUX => array(
5 => DeploymentScanner::SYSTEMV_INIT_STRING,
6 => DeploymentScanner::SYSTEMV_INIT_STRING,
'default' => DeploymentScanner::SYSTEMD_INIT_STRING
),
'Fedora' . DeploymentScanner::LINUX => DeploymentScanner::SYSTEMD_INIT_STRING
);
} | [
"public",
"function",
"init",
"(",
")",
"{",
"// initialize the service class",
"$",
"this",
"->",
"service",
"=",
"$",
"this",
"->",
"newService",
"(",
"'AppserverIo\\Appserver\\Core\\Api\\ContainerService'",
")",
";",
"//We will check the distribution type by it's release f... | Initalizes the scanner with the necessary service instance.
@return void
@see \AppserverIo\Appserver\Core\AbstractThread::init() | [
"Initalizes",
"the",
"scanner",
"with",
"the",
"necessary",
"service",
"instance",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php#L122-L161 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php | AbstractScanner.getRestartCommand | public function getRestartCommand($os, $distVersion = null)
{
// check if the restart command is registered
if (array_key_exists($os, $this->restartCommands)) {
// check whether or not we got an array, if so we have to check for the version
$command = $this->restartCommands[$os];
if (is_array($command)) {
// if we do have a certain version we have to determine the command
if (!is_null($distVersion)) {
// floor the dist version for comparison
$distVersion = (int) floor((float) $distVersion);
foreach ($command as $version => $potentialCommand) {
if ($distVersion === $version) {
$command = $potentialCommand;
break;
}
}
}
// if we did not find anything we have to take the default command
if (is_array($command)) {
$command = $command['default'];
}
}
// for Mac OS X the base directory has to be appended
if ($os === DeploymentScanner::DARWIN) {
$command = $this->getService()->realpath($command);
}
// return the command
return $command;
}
// throw an exception if the restart command is not available
throw new \Exception("Can't find restart command for OS $os");
} | php | public function getRestartCommand($os, $distVersion = null)
{
// check if the restart command is registered
if (array_key_exists($os, $this->restartCommands)) {
// check whether or not we got an array, if so we have to check for the version
$command = $this->restartCommands[$os];
if (is_array($command)) {
// if we do have a certain version we have to determine the command
if (!is_null($distVersion)) {
// floor the dist version for comparison
$distVersion = (int) floor((float) $distVersion);
foreach ($command as $version => $potentialCommand) {
if ($distVersion === $version) {
$command = $potentialCommand;
break;
}
}
}
// if we did not find anything we have to take the default command
if (is_array($command)) {
$command = $command['default'];
}
}
// for Mac OS X the base directory has to be appended
if ($os === DeploymentScanner::DARWIN) {
$command = $this->getService()->realpath($command);
}
// return the command
return $command;
}
// throw an exception if the restart command is not available
throw new \Exception("Can't find restart command for OS $os");
} | [
"public",
"function",
"getRestartCommand",
"(",
"$",
"os",
",",
"$",
"distVersion",
"=",
"null",
")",
"{",
"// check if the restart command is registered",
"if",
"(",
"array_key_exists",
"(",
"$",
"os",
",",
"$",
"this",
"->",
"restartCommands",
")",
")",
"{",
... | Returns the restart command for the passed OS
if available.
@param string $os The OS to return the restart command for
@param string|null $distVersion Version of the operating system to get the restart command for
@return string The restart command
@throws \Exception Is thrown if the restart command for the passed OS is can't found | [
"Returns",
"the",
"restart",
"command",
"for",
"the",
"passed",
"OS",
"if",
"available",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php#L206-L243 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php | AbstractScanner.restart | public function restart()
{
// load the OS signature
$os = php_uname('s');
// log the found OS
$this->getSystemLogger()->debug(
"Found operating system: $os"
);
// check what OS we are running on
switch ($os) {
// If we got a Linux distribution we have to check which one
case DeploymentScanner::LINUX:
// Get the distribution
$distribution = $this->getLinuxDistribution();
// If we did not get anything
if (!$distribution) {
// Log the error
$this->getSystemLogger()->error(
"The used Linux distribution could not be determined, it might not be supported."
);
// End here
return;
}
// determine the version of the found distribution
$distVersion = $this->getDistributionVersion($distribution);
// log the found distribution
$this->getSystemLogger()->debug(
"Found Linux distribution: $distribution"
);
// Execute the restart command for the distribution
exec($this->getRestartCommand($distribution . $os, $distVersion));
break;
// Restart with the Mac or Windows command
case DeploymentScanner::DARWIN:
case DeploymentScanner::WINDOWS_NT:
exec($this->getRestartCommand($os));
break;
// all other OS are NOT supported actually
default:
$this->getSystemLogger()->error(
"OS $os does not support auto restart"
);
break;
}
} | php | public function restart()
{
// load the OS signature
$os = php_uname('s');
// log the found OS
$this->getSystemLogger()->debug(
"Found operating system: $os"
);
// check what OS we are running on
switch ($os) {
// If we got a Linux distribution we have to check which one
case DeploymentScanner::LINUX:
// Get the distribution
$distribution = $this->getLinuxDistribution();
// If we did not get anything
if (!$distribution) {
// Log the error
$this->getSystemLogger()->error(
"The used Linux distribution could not be determined, it might not be supported."
);
// End here
return;
}
// determine the version of the found distribution
$distVersion = $this->getDistributionVersion($distribution);
// log the found distribution
$this->getSystemLogger()->debug(
"Found Linux distribution: $distribution"
);
// Execute the restart command for the distribution
exec($this->getRestartCommand($distribution . $os, $distVersion));
break;
// Restart with the Mac or Windows command
case DeploymentScanner::DARWIN:
case DeploymentScanner::WINDOWS_NT:
exec($this->getRestartCommand($os));
break;
// all other OS are NOT supported actually
default:
$this->getSystemLogger()->error(
"OS $os does not support auto restart"
);
break;
}
} | [
"public",
"function",
"restart",
"(",
")",
"{",
"// load the OS signature",
"$",
"os",
"=",
"php_uname",
"(",
"'s'",
")",
";",
"// log the found OS",
"$",
"this",
"->",
"getSystemLogger",
"(",
")",
"->",
"debug",
"(",
"\"Found operating system: $os\"",
")",
";",... | Restart the appserver using the appserverctl file in the sbin folder.
@return void | [
"Restart",
"the",
"appserver",
"using",
"the",
"appserverctl",
"file",
"in",
"the",
"sbin",
"folder",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php#L250-L305 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php | AbstractScanner.getLinuxDistribution | protected function getLinuxDistribution($etcList = array())
{
// Get everything from /etc directory and flip the result for faster search,
// but only if there is no list provided already
$etcDir = '/etc';
if (empty($etcList)) {
$etcList = scandir($etcDir);
$etcList = array_flip($etcList);
}
// Loop through our mapping and look if we have a match
$distributionCandidates = array();
foreach ($this->distroMapping as $distribution => $releaseFile) {
// Do we have a match which is not just a soft link on the actual file? If so collect the distro
if (isset($etcList[$releaseFile]) && !is_link($etcDir . DIRECTORY_SEPARATOR . $releaseFile)) {
$distributionCandidates[$releaseFile] = $distribution;
}
}
// If we have several matches we might have to resort
if (count($distributionCandidates) === 1) {
return array_pop($distributionCandidates);
} elseif (count($distributionCandidates) > 1) {
// the file lsb-release might be existent in several Linux systems, filter it out
if (isset($distributionCandidates['lsb-release'])) {
unset($distributionCandidates['lsb-release']);
}
} else {
// It does not make sense to check any further
return false;
}
// Recursively filter the found files
return $this->getLinuxDistribution($distributionCandidates);
} | php | protected function getLinuxDistribution($etcList = array())
{
// Get everything from /etc directory and flip the result for faster search,
// but only if there is no list provided already
$etcDir = '/etc';
if (empty($etcList)) {
$etcList = scandir($etcDir);
$etcList = array_flip($etcList);
}
// Loop through our mapping and look if we have a match
$distributionCandidates = array();
foreach ($this->distroMapping as $distribution => $releaseFile) {
// Do we have a match which is not just a soft link on the actual file? If so collect the distro
if (isset($etcList[$releaseFile]) && !is_link($etcDir . DIRECTORY_SEPARATOR . $releaseFile)) {
$distributionCandidates[$releaseFile] = $distribution;
}
}
// If we have several matches we might have to resort
if (count($distributionCandidates) === 1) {
return array_pop($distributionCandidates);
} elseif (count($distributionCandidates) > 1) {
// the file lsb-release might be existent in several Linux systems, filter it out
if (isset($distributionCandidates['lsb-release'])) {
unset($distributionCandidates['lsb-release']);
}
} else {
// It does not make sense to check any further
return false;
}
// Recursively filter the found files
return $this->getLinuxDistribution($distributionCandidates);
} | [
"protected",
"function",
"getLinuxDistribution",
"(",
"$",
"etcList",
"=",
"array",
"(",
")",
")",
"{",
"// Get everything from /etc directory and flip the result for faster search,",
"// but only if there is no list provided already",
"$",
"etcDir",
"=",
"'/etc'",
";",
"if",
... | This method will check for the Linux release file normally stored in /etc and will return
the corresponding distribution
@param array $etcList List of already collected AND flipped release files we need to filter
@return string|boolean | [
"This",
"method",
"will",
"check",
"for",
"the",
"Linux",
"release",
"file",
"normally",
"stored",
"in",
"/",
"etc",
"and",
"will",
"return",
"the",
"corresponding",
"distribution"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php#L315-L351 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php | AbstractScanner.getDistributionVersion | protected function getDistributionVersion($distribution = null, $etcList = array())
{
// Get everything from /etc directory and flip the result for faster search,
// but only if there is no list provided already
$etcDir = $this->getEtcDir();
if (empty($etcList)) {
$etcList = scandir($etcDir);
$etcList = array_flip($etcList);
}
// check if we got a distribution to specifically look for, if not determine it first
if (is_null($distribution)) {
$distribution = $this->getLinuxDistribution($etcList);
}
// check if the distribution was properly provided/found, if not return FALSE
if (!isset($this->distroMapping[$distribution])) {
return false;
}
// loop through our mapping and look if we have a match
$releaseFile = $this->distroMapping[$distribution];
// do we have a match which is not just a soft link on the actual file? If so collect the file content
$potentialVersion = '';
if (isset($etcList[$releaseFile]) && !is_link($etcDir . DIRECTORY_SEPARATOR . $releaseFile)) {
// retrieve the version string and try to determine the actual version from it
$potentialVersion = file_get_contents($etcDir . DIRECTORY_SEPARATOR . $releaseFile);
$matches = array();
preg_match('/(\d+\.*)+/', $potentialVersion, $matches);
// filter our findings
if (!isset($matches[0])) {
return false;
}
$potentialVersion = $matches[0];
}
// return what we got
return $potentialVersion;
} | php | protected function getDistributionVersion($distribution = null, $etcList = array())
{
// Get everything from /etc directory and flip the result for faster search,
// but only if there is no list provided already
$etcDir = $this->getEtcDir();
if (empty($etcList)) {
$etcList = scandir($etcDir);
$etcList = array_flip($etcList);
}
// check if we got a distribution to specifically look for, if not determine it first
if (is_null($distribution)) {
$distribution = $this->getLinuxDistribution($etcList);
}
// check if the distribution was properly provided/found, if not return FALSE
if (!isset($this->distroMapping[$distribution])) {
return false;
}
// loop through our mapping and look if we have a match
$releaseFile = $this->distroMapping[$distribution];
// do we have a match which is not just a soft link on the actual file? If so collect the file content
$potentialVersion = '';
if (isset($etcList[$releaseFile]) && !is_link($etcDir . DIRECTORY_SEPARATOR . $releaseFile)) {
// retrieve the version string and try to determine the actual version from it
$potentialVersion = file_get_contents($etcDir . DIRECTORY_SEPARATOR . $releaseFile);
$matches = array();
preg_match('/(\d+\.*)+/', $potentialVersion, $matches);
// filter our findings
if (!isset($matches[0])) {
return false;
}
$potentialVersion = $matches[0];
}
// return what we got
return $potentialVersion;
} | [
"protected",
"function",
"getDistributionVersion",
"(",
"$",
"distribution",
"=",
"null",
",",
"$",
"etcList",
"=",
"array",
"(",
")",
")",
"{",
"// Get everything from /etc directory and flip the result for faster search,",
"// but only if there is no list provided already",
"... | This method will check for the Linux release file normally stored in /etc and will return
the version of the distribution
@param string|null $distribution Distribution to search a version for
@param array $etcList List of already collected AND flipped release files we need to filter
@return string|boolean | [
"This",
"method",
"will",
"check",
"for",
"the",
"Linux",
"release",
"file",
"normally",
"stored",
"in",
"/",
"etc",
"and",
"will",
"return",
"the",
"version",
"of",
"the",
"distribution"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php#L372-L411 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php | AbstractScanner.getLastFileTouch | protected function getLastFileTouch($file)
{
// initialize the file's mtime to 0
$mtime = 0;
// clear the stat cache to get real mtime if changed
clearstatcache();
// return the change date (last successful deployment date)
if (is_file($file)) {
$mtime = filemtime($file);
}
// return the file's mtime
return $mtime;
} | php | protected function getLastFileTouch($file)
{
// initialize the file's mtime to 0
$mtime = 0;
// clear the stat cache to get real mtime if changed
clearstatcache();
// return the change date (last successful deployment date)
if (is_file($file)) {
$mtime = filemtime($file);
}
// return the file's mtime
return $mtime;
} | [
"protected",
"function",
"getLastFileTouch",
"(",
"$",
"file",
")",
"{",
"// initialize the file's mtime to 0",
"$",
"mtime",
"=",
"0",
";",
"// clear the stat cache to get real mtime if changed",
"clearstatcache",
"(",
")",
";",
"// return the change date (last successful depl... | Returns the time when the contents of the file were changed. The time
returned is a UNIX timestamp.
If the file doesn't exists, the method returns 0 to signal that the no
successfull depolyment has been processed so far, e. g. the server has
been installed and not been started yet.
@param string $file The deployment directory
@return integer The UNIX timestamp with the last successfully deployment date or 0 if no successful
deployment has been processed | [
"Returns",
"the",
"time",
"when",
"the",
"contents",
"of",
"the",
"file",
"were",
"changed",
".",
"The",
"time",
"returned",
"is",
"a",
"UNIX",
"timestamp",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php#L426-L441 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Scanner/AbstractScanner.php | AbstractScanner.getDirectoryHash | protected function getDirectoryHash(\SplFileInfo $directory)
{
// prepare the array
$files = new \ArrayObject();
// prepare the array with the file extensions of the files used to build the hash
$extensionsToWatch = $this->getExtensionsToWatch();
// clear the cache
clearstatcache();
// add all files with the found extensions to the array
foreach (glob($directory . '/*.{' . implode(',', $extensionsToWatch) . '}', GLOB_BRACE) as $filename) {
$files->append($filename);
}
// calculate and return the hash value for the array
return md5($files->serialize());
} | php | protected function getDirectoryHash(\SplFileInfo $directory)
{
// prepare the array
$files = new \ArrayObject();
// prepare the array with the file extensions of the files used to build the hash
$extensionsToWatch = $this->getExtensionsToWatch();
// clear the cache
clearstatcache();
// add all files with the found extensions to the array
foreach (glob($directory . '/*.{' . implode(',', $extensionsToWatch) . '}', GLOB_BRACE) as $filename) {
$files->append($filename);
}
// calculate and return the hash value for the array
return md5($files->serialize());
} | [
"protected",
"function",
"getDirectoryHash",
"(",
"\\",
"SplFileInfo",
"$",
"directory",
")",
"{",
"// prepare the array",
"$",
"files",
"=",
"new",
"\\",
"ArrayObject",
"(",
")",
";",
"// prepare the array with the file extensions of the files used to build the hash",
"$",... | 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/AbstractScanner.php#L461-L480 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.getReflectionClass | public function getReflectionClass($className)
{
// check if we've already initialized the reflection class
if (isset($this->reflectionClasses[$className]) === false) {
$this->reflectionClasses[$className] = $this->newReflectionClass($className);
}
// return the reflection class instance
return $this->reflectionClasses[$className];
} | php | public function getReflectionClass($className)
{
// check if we've already initialized the reflection class
if (isset($this->reflectionClasses[$className]) === false) {
$this->reflectionClasses[$className] = $this->newReflectionClass($className);
}
// return the reflection class instance
return $this->reflectionClasses[$className];
} | [
"public",
"function",
"getReflectionClass",
"(",
"$",
"className",
")",
"{",
"// check if we've already initialized the reflection class",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"reflectionClasses",
"[",
"$",
"className",
"]",
")",
"===",
"false",
")",
"{",
"... | Returns a new reflection class intance for the passed class name.
@param string $className The class name to return the reflection class instance for
@return \AppserverIo\Lang\Reflection\ReflectionClass The reflection instance | [
"Returns",
"a",
"new",
"reflection",
"class",
"intance",
"for",
"the",
"passed",
"class",
"name",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L204-L214 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.loadDependencies | public function loadDependencies(NameAwareDescriptorInterface $objectDescriptor)
{
if ($objectDescriptor instanceof \AppserverIo\Description\FactoryDescriptor) {
throw new \Exception(print_r($objectDescriptor, true));
}
// query whether or not the dependencies have been loaded
if (isset($this->dependencies[$name = $objectDescriptor->getName()])) {
return $this->dependencies[$name];
}
// initialize the array with the dependencies
$dependencies = array('method' => array(), 'property' => array());
// check for declared EPB and resource references
/** @var \AppserverIo\Psr\EnterpriseBeans\Description\ReferenceDescriptorInterface $reference */
foreach ($objectDescriptor->getReferences() as $reference) {
// check if we've a reflection target defined
if ($injectionTarget = $reference->getInjectionTarget()) {
// add the dependency to the array
if ($targetName = $injectionTarget->getTargetProperty()) {
// append the property dependency
$dependencies['property'][$targetName] = $this->loadDependency($reference);
} elseif ($targetName = $injectionTarget->getTargetMethod()) {
// prepare the array with the method dependencies
if (!isset($dependencies['method'][$targetName])) {
$dependencies['method'][$targetName] = array();
}
// append the method/constructor dependency
$dependencies['method'][$targetName][] = $this->loadDependency($reference);
} else {
// throw an exception
throw new DependencyInjectionException(
sprintf('Can\'t find property or method %s in class "%s"', $targetName, $name)
);
}
}
}
// return the array with the loaded dependencies
return $this->dependencies[$name] = $dependencies;
} | php | public function loadDependencies(NameAwareDescriptorInterface $objectDescriptor)
{
if ($objectDescriptor instanceof \AppserverIo\Description\FactoryDescriptor) {
throw new \Exception(print_r($objectDescriptor, true));
}
// query whether or not the dependencies have been loaded
if (isset($this->dependencies[$name = $objectDescriptor->getName()])) {
return $this->dependencies[$name];
}
// initialize the array with the dependencies
$dependencies = array('method' => array(), 'property' => array());
// check for declared EPB and resource references
/** @var \AppserverIo\Psr\EnterpriseBeans\Description\ReferenceDescriptorInterface $reference */
foreach ($objectDescriptor->getReferences() as $reference) {
// check if we've a reflection target defined
if ($injectionTarget = $reference->getInjectionTarget()) {
// add the dependency to the array
if ($targetName = $injectionTarget->getTargetProperty()) {
// append the property dependency
$dependencies['property'][$targetName] = $this->loadDependency($reference);
} elseif ($targetName = $injectionTarget->getTargetMethod()) {
// prepare the array with the method dependencies
if (!isset($dependencies['method'][$targetName])) {
$dependencies['method'][$targetName] = array();
}
// append the method/constructor dependency
$dependencies['method'][$targetName][] = $this->loadDependency($reference);
} else {
// throw an exception
throw new DependencyInjectionException(
sprintf('Can\'t find property or method %s in class "%s"', $targetName, $name)
);
}
}
}
// return the array with the loaded dependencies
return $this->dependencies[$name] = $dependencies;
} | [
"public",
"function",
"loadDependencies",
"(",
"NameAwareDescriptorInterface",
"$",
"objectDescriptor",
")",
"{",
"if",
"(",
"$",
"objectDescriptor",
"instanceof",
"\\",
"AppserverIo",
"\\",
"Description",
"\\",
"FactoryDescriptor",
")",
"{",
"throw",
"new",
"\\",
"... | Loads the dependencies for the passed object descriptor.
@param \AppserverIo\Psr\EnterpriseBeans\Description\NameAwareDescriptorInterface $objectDescriptor The object descriptor to load the dependencies for
@throws \AppserverIo\Psr\Di\DependencyInjectionException Is thrown, if the dependencies can not be loaded
@return array The array with the initialized dependencies | [
"Loads",
"the",
"dependencies",
"for",
"the",
"passed",
"object",
"descriptor",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L250-L294 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.loadDependency | public function loadDependency(ReferenceDescriptorInterface $referenceDescriptor)
{
// load the session ID from the execution environment
$sessionId = Environment::singleton()->getAttribute(EnvironmentKeys::SESSION_ID);
// prepare the lookup name
$lookupName = sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), $referenceDescriptor->getRefName());
// at least we need a type for instanciation, if we've a bean reference
if ($referenceDescriptor instanceof BeanReferenceDescriptorInterface && $type = $referenceDescriptor->getType()) {
// load the object manager instance
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $this->getNamingDirectory()->search(
sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), ObjectManagerInterface::IDENTIFIER)
);
// try to directly instanciate the class by its defined type
return $this->get($objectManager->getPreference($type), $sessionId);
}
// query if the instance is available, if yes load the instance by lookup the initial context
if ($this->getNamingDirectory()->isBound($lookupName)) {
return $this->getNamingDirectory()->search($lookupName, array($sessionId));
}
// throw an exception if the dependency can't be instanciated
throw new \Exception(sprintf('Can\'t lookup bean "%s" nor find a DI type definition', $lookupName));
} | php | public function loadDependency(ReferenceDescriptorInterface $referenceDescriptor)
{
// load the session ID from the execution environment
$sessionId = Environment::singleton()->getAttribute(EnvironmentKeys::SESSION_ID);
// prepare the lookup name
$lookupName = sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), $referenceDescriptor->getRefName());
// at least we need a type for instanciation, if we've a bean reference
if ($referenceDescriptor instanceof BeanReferenceDescriptorInterface && $type = $referenceDescriptor->getType()) {
// load the object manager instance
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $this->getNamingDirectory()->search(
sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), ObjectManagerInterface::IDENTIFIER)
);
// try to directly instanciate the class by its defined type
return $this->get($objectManager->getPreference($type), $sessionId);
}
// query if the instance is available, if yes load the instance by lookup the initial context
if ($this->getNamingDirectory()->isBound($lookupName)) {
return $this->getNamingDirectory()->search($lookupName, array($sessionId));
}
// throw an exception if the dependency can't be instanciated
throw new \Exception(sprintf('Can\'t lookup bean "%s" nor find a DI type definition', $lookupName));
} | [
"public",
"function",
"loadDependency",
"(",
"ReferenceDescriptorInterface",
"$",
"referenceDescriptor",
")",
"{",
"// load the session ID from the execution environment",
"$",
"sessionId",
"=",
"Environment",
"::",
"singleton",
"(",
")",
"->",
"getAttribute",
"(",
"Environ... | Load's and return's the dependency instance for the passed reference.
@param \AppserverIo\Psr\EnterpriseBeans\Description\ReferenceDescriptorInterface $referenceDescriptor The reference descriptor
@return object The reference instance
@throws \Exception Is thrown, if no DI type definition for the passed reference is available | [
"Load",
"s",
"and",
"return",
"s",
"the",
"dependency",
"instance",
"for",
"the",
"passed",
"reference",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L304-L332 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.loadDependenciesByReflectionMethod | public function loadDependenciesByReflectionMethod(ReflectionMethod $reflectionMethod)
{
// initialize the array for the dependencies
$dependencies = array();
// load the object manager instance
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $this->getNamingDirectory()->search(
sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), ObjectManagerInterface::IDENTIFIER)
);
// iterate over the constructor parameters
/** @var \AppserverIo\Lang\Reflection\ParameterInterface $reflectionParameter */
foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
$dependencies[] = $this->get($objectManager->getPreference($reflectionParameter->getType()));
}
// return the initialized dependencies
return $dependencies;
} | php | public function loadDependenciesByReflectionMethod(ReflectionMethod $reflectionMethod)
{
// initialize the array for the dependencies
$dependencies = array();
// load the object manager instance
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $this->getNamingDirectory()->search(
sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), ObjectManagerInterface::IDENTIFIER)
);
// iterate over the constructor parameters
/** @var \AppserverIo\Lang\Reflection\ParameterInterface $reflectionParameter */
foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
$dependencies[] = $this->get($objectManager->getPreference($reflectionParameter->getType()));
}
// return the initialized dependencies
return $dependencies;
} | [
"public",
"function",
"loadDependenciesByReflectionMethod",
"(",
"ReflectionMethod",
"$",
"reflectionMethod",
")",
"{",
"// initialize the array for the dependencies",
"$",
"dependencies",
"=",
"array",
"(",
")",
";",
"// load the object manager instance",
"/** @var \\AppserverIo... | Loads the dependencies for the passed reflection method.
@param \AppserverIo\Lang\Reflection\ReflectionMethod $reflectionMethod The reflection method to load the dependencies for
@return array The array with the initialized dependencies | [
"Loads",
"the",
"dependencies",
"for",
"the",
"passed",
"reflection",
"method",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L341-L361 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.loadDependenciesByMethodInvocation | public function loadDependenciesByMethodInvocation(MethodInvocationDescriptorInterface $descriptor)
{
// initialize the array with the dependencies
$dependencies = array();
// load the dependencies from the DI provider
foreach ($descriptor->getArguments() as $argument) {
$dependencies[] = $this->get((string) $argument);
}
// return the dependencies
return $dependencies;
} | php | public function loadDependenciesByMethodInvocation(MethodInvocationDescriptorInterface $descriptor)
{
// initialize the array with the dependencies
$dependencies = array();
// load the dependencies from the DI provider
foreach ($descriptor->getArguments() as $argument) {
$dependencies[] = $this->get((string) $argument);
}
// return the dependencies
return $dependencies;
} | [
"public",
"function",
"loadDependenciesByMethodInvocation",
"(",
"MethodInvocationDescriptorInterface",
"$",
"descriptor",
")",
"{",
"// initialize the array with the dependencies",
"$",
"dependencies",
"=",
"array",
"(",
")",
";",
"// load the dependencies from the DI provider",
... | Loads the dependencies for the passed method invocation descriptor.
@param \AppserverIo\Psr\EnterpriseBeans\Description\MethodInvocationDescriptorInterface $descriptor The descriptor to load the dependencies for
@return array The array with the initialized dependencies | [
"Loads",
"the",
"dependencies",
"for",
"the",
"passed",
"method",
"invocation",
"descriptor",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L370-L383 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.createInstance | public function createInstance(NameAwareDescriptorInterface $objectDescriptor)
{
// try to load the reflection class
$reflectionClass = $this->getReflectionClass($objectDescriptor->getClassName());
// load the dependencies for the passed descriptor
$dependencies = $this->loadDependencies($objectDescriptor);
// check if we've a constructor
if ($reflectionClass->hasMethod($methodName = '__construct') &&
$reflectionClass->getMethod($methodName)->getParameters()
) {
// query whether or not constructor parameters are available
if (isset($dependencies['method'][$methodName])) {
// create a new instance and pass the constructor args
return $reflectionClass->newInstanceArgs($dependencies['method'][$methodName]);
}
}
// create a new instance
$instance = $reflectionClass->newInstance();
// inject the dependencies using properties/methods
$this->injectDependencies($objectDescriptor, $instance);
// return the initialized instance
return $instance;
} | php | public function createInstance(NameAwareDescriptorInterface $objectDescriptor)
{
// try to load the reflection class
$reflectionClass = $this->getReflectionClass($objectDescriptor->getClassName());
// load the dependencies for the passed descriptor
$dependencies = $this->loadDependencies($objectDescriptor);
// check if we've a constructor
if ($reflectionClass->hasMethod($methodName = '__construct') &&
$reflectionClass->getMethod($methodName)->getParameters()
) {
// query whether or not constructor parameters are available
if (isset($dependencies['method'][$methodName])) {
// create a new instance and pass the constructor args
return $reflectionClass->newInstanceArgs($dependencies['method'][$methodName]);
}
}
// create a new instance
$instance = $reflectionClass->newInstance();
// inject the dependencies using properties/methods
$this->injectDependencies($objectDescriptor, $instance);
// return the initialized instance
return $instance;
} | [
"public",
"function",
"createInstance",
"(",
"NameAwareDescriptorInterface",
"$",
"objectDescriptor",
")",
"{",
"// try to load the reflection class",
"$",
"reflectionClass",
"=",
"$",
"this",
"->",
"getReflectionClass",
"(",
"$",
"objectDescriptor",
"->",
"getClassName",
... | Creates a new instance with the dependencies defined by the passed descriptor.
@param \AppserverIo\Psr\EnterpriseBeans\Description\NameAwareDescriptorInterface $objectDescriptor The object descriptor with the dependencies
@return object The instance | [
"Creates",
"a",
"new",
"instance",
"with",
"the",
"dependencies",
"defined",
"by",
"the",
"passed",
"descriptor",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L392-L420 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.injectDependencies | public function injectDependencies(DescriptorInterface $objectDescriptor, $instance)
{
// try to load the reflection class
$reflectionClass = $this->getReflectionClass($objectDescriptor->getClassName());
// load the dependencies for the passed descriptor
$dependencies = $this->loadDependencies($objectDescriptor);
// iterate over all methods and inject the dependencies
foreach ($dependencies['method'] as $methodName => $toInject) {
// query whether or not the method exists
if ($reflectionClass->hasMethod($methodName)) {
// inject the target by invoking the method
call_user_func_array(array($instance, $methodName), $toInject);
}
}
// inject dependencies by property
foreach ($dependencies['property'] as $propertyName => $toInject) {
// query whether or not the property exists
if ($reflectionClass->hasProperty($propertyName)) {
// load the reflection property
$reflectionProperty = $reflectionClass->getProperty($propertyName);
// load the PHP ReflectionProperty instance to inject the bean instance
$phpReflectionProperty = $reflectionProperty->toPhpReflectionProperty();
$phpReflectionProperty->setAccessible(true);
$phpReflectionProperty->setValue($instance, $toInject);
}
}
} | php | public function injectDependencies(DescriptorInterface $objectDescriptor, $instance)
{
// try to load the reflection class
$reflectionClass = $this->getReflectionClass($objectDescriptor->getClassName());
// load the dependencies for the passed descriptor
$dependencies = $this->loadDependencies($objectDescriptor);
// iterate over all methods and inject the dependencies
foreach ($dependencies['method'] as $methodName => $toInject) {
// query whether or not the method exists
if ($reflectionClass->hasMethod($methodName)) {
// inject the target by invoking the method
call_user_func_array(array($instance, $methodName), $toInject);
}
}
// inject dependencies by property
foreach ($dependencies['property'] as $propertyName => $toInject) {
// query whether or not the property exists
if ($reflectionClass->hasProperty($propertyName)) {
// load the reflection property
$reflectionProperty = $reflectionClass->getProperty($propertyName);
// load the PHP ReflectionProperty instance to inject the bean instance
$phpReflectionProperty = $reflectionProperty->toPhpReflectionProperty();
$phpReflectionProperty->setAccessible(true);
$phpReflectionProperty->setValue($instance, $toInject);
}
}
} | [
"public",
"function",
"injectDependencies",
"(",
"DescriptorInterface",
"$",
"objectDescriptor",
",",
"$",
"instance",
")",
"{",
"// try to load the reflection class",
"$",
"reflectionClass",
"=",
"$",
"this",
"->",
"getReflectionClass",
"(",
"$",
"objectDescriptor",
"-... | Injects the dependencies of the passed instance defined in the object descriptor.
@param \AppserverIo\Psr\Deployment\DescriptorInterface $objectDescriptor The object descriptor with the dependencies
@param object $instance The instance to inject the dependencies for
@return void | [
"Injects",
"the",
"dependencies",
"of",
"the",
"passed",
"instance",
"defined",
"in",
"the",
"object",
"descriptor",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L431-L462 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.newInstance | public function newInstance($className, array $args = array())
{
// load the reflection data for the passed class name
$reflectionClass = $this->getReflectionClass($className);
// query whether or not the class has a constructor
if ($reflectionClass->hasMethod($methodName = '__construct') &&
$reflectionClass->getMethod($methodName)->getParameters() &&
sizeof($args) > 0
) {
return $reflectionClass->newInstanceArgs($args);
}
// return the instance without calling the constructor
return $reflectionClass->newInstance();
} | php | public function newInstance($className, array $args = array())
{
// load the reflection data for the passed class name
$reflectionClass = $this->getReflectionClass($className);
// query whether or not the class has a constructor
if ($reflectionClass->hasMethod($methodName = '__construct') &&
$reflectionClass->getMethod($methodName)->getParameters() &&
sizeof($args) > 0
) {
return $reflectionClass->newInstanceArgs($args);
}
// return the instance without calling the constructor
return $reflectionClass->newInstance();
} | [
"public",
"function",
"newInstance",
"(",
"$",
"className",
",",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"// load the reflection data for the passed class name",
"$",
"reflectionClass",
"=",
"$",
"this",
"->",
"getReflectionClass",
"(",
"$",
"class... | 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/DependencyInjectionContainer/Provider.php#L472-L488 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.get | public function get($id)
{
// query whether or not the instance can be created
if ($this->has($id)) {
// query the request context whether or not an instance has already been loaded
if (Environment::singleton()->hasAttribute($id)) {
return Environment::singleton()->getAttribute($id);
}
try {
// load the object manager instance
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $this->getNamingDirectory()->search(
sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), ObjectManagerInterface::IDENTIFIER)
);
// query whether or not the passed ID has a descriptor
if ($objectManager->hasObjectDescriptor($id)) {
// load the object descriptor instance
$objectDescriptor = $objectManager->getObjectDescriptor($id);
// query if the simple bean has to be initialized by a factory
if ($objectDescriptor instanceof FactoryAwareDescriptorInterface && $factory = $objectDescriptor->getFactory()) {
// query whether or not the factory is a simple class or a bean
if ($className = $factory->getClassName()) {
$factoryInstance = $this->get($className);
} else {
$factoryInstance = $this->get($factory->getName());
}
// create the instance by invoking the factory method
$instance = call_user_func(array($factoryInstance, $factory->getMethod()));
} else {
// create the instance and inject the dependencies
$instance = $this->createInstance($objectDescriptor);
}
// query whether or not method invocations has been configured
if ($objectDescriptor instanceof MethodInvocationAwareDescriptorInterface) {
// iterate over all configured method invocations
foreach ($objectDescriptor->getMethodInvocations() as $methodInvocation) {
// invoke the method with the configured arguments
call_user_func_array(
array($instance, $methodInvocation->getMethodName()),
$this->loadDependenciesByMethodInvocation($methodInvocation)
);
}
}
// add the initialized instance to the request context if has to be shared
if ($objectDescriptor->isShared()) {
$this->set($id, $instance);
}
// immediately return the instance
return $instance;
}
// initialize the array for the dependencies
$dependencies = array();
// assume, that the passed ID is a FQCN
$reflectionClass = $this->getReflectionClass($id);
// query whether or not the class has a constructor that expects parameters
if ($reflectionClass->hasMethod($methodName = '__construct') &&
$reflectionClass->getMethod($methodName)->getParameters()
) {
// if yes, load them by the the reflection method
$dependencies = $this->loadDependenciesByReflectionMethod($reflectionClass->getMethod($methodName));
}
// create and ddd the initialized instance to the request context
$this->set($id, $instance = $this->newInstance($id, $dependencies));
// finally return the instance
return $instance;
} catch (\Exception $e) {
throw new NotFoundException(sprintf('DI error when try to inject dependencies for identifier "%s"', $id), null, $e);
}
}
// throw an exception if no entry was found for **this** identifier
throw new NotFoundException(sprintf('DI definition for identifier "%s" is not available', $id));
} | php | public function get($id)
{
// query whether or not the instance can be created
if ($this->has($id)) {
// query the request context whether or not an instance has already been loaded
if (Environment::singleton()->hasAttribute($id)) {
return Environment::singleton()->getAttribute($id);
}
try {
// load the object manager instance
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $this->getNamingDirectory()->search(
sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), ObjectManagerInterface::IDENTIFIER)
);
// query whether or not the passed ID has a descriptor
if ($objectManager->hasObjectDescriptor($id)) {
// load the object descriptor instance
$objectDescriptor = $objectManager->getObjectDescriptor($id);
// query if the simple bean has to be initialized by a factory
if ($objectDescriptor instanceof FactoryAwareDescriptorInterface && $factory = $objectDescriptor->getFactory()) {
// query whether or not the factory is a simple class or a bean
if ($className = $factory->getClassName()) {
$factoryInstance = $this->get($className);
} else {
$factoryInstance = $this->get($factory->getName());
}
// create the instance by invoking the factory method
$instance = call_user_func(array($factoryInstance, $factory->getMethod()));
} else {
// create the instance and inject the dependencies
$instance = $this->createInstance($objectDescriptor);
}
// query whether or not method invocations has been configured
if ($objectDescriptor instanceof MethodInvocationAwareDescriptorInterface) {
// iterate over all configured method invocations
foreach ($objectDescriptor->getMethodInvocations() as $methodInvocation) {
// invoke the method with the configured arguments
call_user_func_array(
array($instance, $methodInvocation->getMethodName()),
$this->loadDependenciesByMethodInvocation($methodInvocation)
);
}
}
// add the initialized instance to the request context if has to be shared
if ($objectDescriptor->isShared()) {
$this->set($id, $instance);
}
// immediately return the instance
return $instance;
}
// initialize the array for the dependencies
$dependencies = array();
// assume, that the passed ID is a FQCN
$reflectionClass = $this->getReflectionClass($id);
// query whether or not the class has a constructor that expects parameters
if ($reflectionClass->hasMethod($methodName = '__construct') &&
$reflectionClass->getMethod($methodName)->getParameters()
) {
// if yes, load them by the the reflection method
$dependencies = $this->loadDependenciesByReflectionMethod($reflectionClass->getMethod($methodName));
}
// create and ddd the initialized instance to the request context
$this->set($id, $instance = $this->newInstance($id, $dependencies));
// finally return the instance
return $instance;
} catch (\Exception $e) {
throw new NotFoundException(sprintf('DI error when try to inject dependencies for identifier "%s"', $id), null, $e);
}
}
// throw an exception if no entry was found for **this** identifier
throw new NotFoundException(sprintf('DI definition for identifier "%s" is not available', $id));
} | [
"public",
"function",
"get",
"(",
"$",
"id",
")",
"{",
"// query whether or not the instance can be created",
"if",
"(",
"$",
"this",
"->",
"has",
"(",
"$",
"id",
")",
")",
"{",
"// query the request context whether or not an instance has already been loaded",
"if",
"("... | Finds an entry of the container by its identifier and returns it.
@param string $id Identifier of the entry to look for
@throws \Psr\Container\NotFoundExceptionInterface No entry was found for **this** identifier.
@throws \Psr\Container\ContainerExceptionInterface Error while retrieving the entry.
@return mixed Entry. | [
"Finds",
"an",
"entry",
"of",
"the",
"container",
"by",
"its",
"identifier",
"and",
"returns",
"it",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L500-L587 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.has | public function has($id)
{
// load the object manager instance
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $this->getNamingDirectory()->search(
sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), ObjectManagerInterface::IDENTIFIER)
);
// query whether or not a object descriptor or the class definition exists
return class_exists($id) || $objectManager->hasObjectDescriptor($id) || Environment::singleton()->hasAttribute($id);
} | php | public function has($id)
{
// load the object manager instance
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $this->getNamingDirectory()->search(
sprintf('php:global/%s/%s', $this->getApplication()->getUniqueName(), ObjectManagerInterface::IDENTIFIER)
);
// query whether or not a object descriptor or the class definition exists
return class_exists($id) || $objectManager->hasObjectDescriptor($id) || Environment::singleton()->hasAttribute($id);
} | [
"public",
"function",
"has",
"(",
"$",
"id",
")",
"{",
"// load the object manager instance",
"/** @var \\AppserverIo\\Psr\\Di\\ObjectManagerInterface $objectManager */",
"$",
"objectManager",
"=",
"$",
"this",
"->",
"getNamingDirectory",
"(",
")",
"->",
"search",
"(",
"s... | Returns TRUE if the container can return an entry for the given identifier.
Returns FALSE otherwise.
`has($id)` returning TRUE does not mean that `get($id)` will not throw an exception.
It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
@param string $id Identifier of the entry to look for.
@return boolean TRUE if an entry for the given identifier exists, else FALSE | [
"Returns",
"TRUE",
"if",
"the",
"container",
"can",
"return",
"an",
"entry",
"for",
"the",
"given",
"identifier",
".",
"Returns",
"FALSE",
"otherwise",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L600-L611 |
appserver-io/appserver | src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php | Provider.set | public function set($id, $value)
{
// query whether or not a value with the passed ID already exists
if (Environment::singleton()->hasAttribute($id)) {
throw new ContainerException(sprintf('A value for identifier "%s" has already been added to the DI container', $id));
}
// add the value to the environment
Environment::singleton()->setAttribute($id, $value);
} | php | public function set($id, $value)
{
// query whether or not a value with the passed ID already exists
if (Environment::singleton()->hasAttribute($id)) {
throw new ContainerException(sprintf('A value for identifier "%s" has already been added to the DI container', $id));
}
// add the value to the environment
Environment::singleton()->setAttribute($id, $value);
} | [
"public",
"function",
"set",
"(",
"$",
"id",
",",
"$",
"value",
")",
"{",
"// query whether or not a value with the passed ID already exists",
"if",
"(",
"Environment",
"::",
"singleton",
"(",
")",
"->",
"hasAttribute",
"(",
"$",
"id",
")",
")",
"{",
"throw",
... | Register's the passed value with the passed ID.
@param string $id The ID of the value to add
@param string $value The value to add
@return void
@throws \AppserverIo\Appserver\DependencyInjectionContainer\ContainerException Is thrown, if a value with the passed key has already been added | [
"Register",
"s",
"the",
"passed",
"value",
"with",
"the",
"passed",
"ID",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/DependencyInjectionContainer/Provider.php#L622-L632 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/Node/AppNode.php | AppNode.initFromApplication | public function initFromApplication(ApplicationInterface $application)
{
$this->setNodeName(self::NODE_NAME);
$this->name = $application->getName();
$this->webappPath = $application->getWebappPath();
$this->setUuid($this->newUuid());
} | php | public function initFromApplication(ApplicationInterface $application)
{
$this->setNodeName(self::NODE_NAME);
$this->name = $application->getName();
$this->webappPath = $application->getWebappPath();
$this->setUuid($this->newUuid());
} | [
"public",
"function",
"initFromApplication",
"(",
"ApplicationInterface",
"$",
"application",
")",
"{",
"$",
"this",
"->",
"setNodeName",
"(",
"self",
"::",
"NODE_NAME",
")",
";",
"$",
"this",
"->",
"name",
"=",
"$",
"application",
"->",
"getName",
"(",
")",... | Will initialize an existing app node from a given application
@param ApplicationInterface $application The application to init from
@return null | [
"Will",
"initialize",
"an",
"existing",
"app",
"node",
"from",
"a",
"given",
"application"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/AppNode.php#L107-L113 |
appserver-io/appserver | src/AppserverIo/Appserver/PersistenceContainer/RemoteMethodInvocation/RemoteProxyGenerator.php | RemoteProxyGenerator.generate | public function generate(DescriptorInterface $descriptor)
{
// start generating the proxy
ob_start();
require __DIR__ . DIRECTORY_SEPARATOR . 'Proxy' . DIRECTORY_SEPARATOR . 'RemoteProxy.dhtml';
$content = ob_get_clean();
// prepare the proxy's filename
$filename = sprintf('%s/%s', $this->getApplication()->getCacheDir(), $this->generateRemoteProxyFilename($descriptor));
// query whether or not proxy's directory has to be created
if (!is_dir($directory = dirname($filename))) {
FileSystem::createDirectory($directory, 0755, true);
}
// write the proxy to the filesystem
file_put_contents($filename, $content);
// load the application instance
$application = $this->getApplication();
// register the proxy in the naming directory
$application->getNamingDirectory()
->bind(
sprintf('php:global/%s/%s/proxy', $application->getUniqueName(), $descriptor->getName()),
sprintf('%sRemoteProxy', $descriptor->getClassName())
);
} | php | public function generate(DescriptorInterface $descriptor)
{
// start generating the proxy
ob_start();
require __DIR__ . DIRECTORY_SEPARATOR . 'Proxy' . DIRECTORY_SEPARATOR . 'RemoteProxy.dhtml';
$content = ob_get_clean();
// prepare the proxy's filename
$filename = sprintf('%s/%s', $this->getApplication()->getCacheDir(), $this->generateRemoteProxyFilename($descriptor));
// query whether or not proxy's directory has to be created
if (!is_dir($directory = dirname($filename))) {
FileSystem::createDirectory($directory, 0755, true);
}
// write the proxy to the filesystem
file_put_contents($filename, $content);
// load the application instance
$application = $this->getApplication();
// register the proxy in the naming directory
$application->getNamingDirectory()
->bind(
sprintf('php:global/%s/%s/proxy', $application->getUniqueName(), $descriptor->getName()),
sprintf('%sRemoteProxy', $descriptor->getClassName())
);
} | [
"public",
"function",
"generate",
"(",
"DescriptorInterface",
"$",
"descriptor",
")",
"{",
"// start generating the proxy",
"ob_start",
"(",
")",
";",
"require",
"__DIR__",
".",
"DIRECTORY_SEPARATOR",
".",
"'Proxy'",
".",
"DIRECTORY_SEPARATOR",
".",
"'RemoteProxy.dhtml'... | Generate's a RMI proxy based on the passe descriptor information and
registers it in the naming directory.
@param \AppserverIo\Psr\Deployment\DescriptorInterface $descriptor The descriptor with the proxy data used for generation
@return void
@link https://github.com/appserver-io/rmi | [
"Generate",
"s",
"a",
"RMI",
"proxy",
"based",
"on",
"the",
"passe",
"descriptor",
"information",
"and",
"registers",
"it",
"in",
"the",
"naming",
"directory",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/RemoteMethodInvocation/RemoteProxyGenerator.php#L77-L105 |
appserver-io/appserver | src/AppserverIo/Appserver/PersistenceContainer/RemoteMethodInvocation/RemoteProxyGenerator.php | RemoteProxyGenerator.generateMethodSignature | protected function generateMethodSignature(\ReflectionMethod $reflectionMethod)
{
// initialize the array for the method params
$params = array();
// iterate over the reflection method's parameters
foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
// initialize the param
$param = '';
// add the type hint, if specified
if ($typeHint = $reflectionParameter->getClass()) {
$param .= sprintf('\%s ', $typeHint->getName());
}
// add the array type hint, if specified
if ($reflectionParameter->isArray()) {
$param .= 'array ';
}
// add the by reference symbol, if necessary
if ($reflectionParameter->isPassedByReference()) {
$param .= '&';
}
// prepare the parameter name
$param .= sprintf('$%s', $reflectionParameter->getName());
// query whether or not the parameter has a default value
if ($reflectionParameter->isDefaultValueAvailable()) {
// if yes, try to load the type
$type = gettype($defaultValue = $reflectionParameter->getDefaultValue());
// qoute it, if it's a string
switch ($type) {
case 'string':
$param .= sprintf(' = "%s"', $defaultValue);
break;
case 'array':
$param .= ' = array(';
foreach ($defaultValue as $value) {
$param .= $value . ', ';
}
$param .= ')';
break;
case 'boolean':
$param .= sprintf(' = %s', $defaultValue ? 'true' : 'false');
break;
case 'integer':
$param .= sprintf(' = %s', $defaultValue);
break;
case 'double':
$param .= sprintf(' = %s', $defaultValue);
break;
default:
$param .= sprintf(' = null');
}
}
// append the parameter to the array
$params[] = $param;
}
// implode the paramters and return them as string
return implode(', ', $params);
} | php | protected function generateMethodSignature(\ReflectionMethod $reflectionMethod)
{
// initialize the array for the method params
$params = array();
// iterate over the reflection method's parameters
foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
// initialize the param
$param = '';
// add the type hint, if specified
if ($typeHint = $reflectionParameter->getClass()) {
$param .= sprintf('\%s ', $typeHint->getName());
}
// add the array type hint, if specified
if ($reflectionParameter->isArray()) {
$param .= 'array ';
}
// add the by reference symbol, if necessary
if ($reflectionParameter->isPassedByReference()) {
$param .= '&';
}
// prepare the parameter name
$param .= sprintf('$%s', $reflectionParameter->getName());
// query whether or not the parameter has a default value
if ($reflectionParameter->isDefaultValueAvailable()) {
// if yes, try to load the type
$type = gettype($defaultValue = $reflectionParameter->getDefaultValue());
// qoute it, if it's a string
switch ($type) {
case 'string':
$param .= sprintf(' = "%s"', $defaultValue);
break;
case 'array':
$param .= ' = array(';
foreach ($defaultValue as $value) {
$param .= $value . ', ';
}
$param .= ')';
break;
case 'boolean':
$param .= sprintf(' = %s', $defaultValue ? 'true' : 'false');
break;
case 'integer':
$param .= sprintf(' = %s', $defaultValue);
break;
case 'double':
$param .= sprintf(' = %s', $defaultValue);
break;
default:
$param .= sprintf(' = null');
}
}
// append the parameter to the array
$params[] = $param;
}
// implode the paramters and return them as string
return implode(', ', $params);
} | [
"protected",
"function",
"generateMethodSignature",
"(",
"\\",
"ReflectionMethod",
"$",
"reflectionMethod",
")",
"{",
"// initialize the array for the method params",
"$",
"params",
"=",
"array",
"(",
")",
";",
"// iterate over the reflection method's parameters",
"foreach",
... | Generates the method signature based on the passed reflection method.
@param \ReflectionMethod $reflectionMethod The reflection method to generate the proxy for
@return string The method signature as string | [
"Generates",
"the",
"method",
"signature",
"based",
"on",
"the",
"passed",
"reflection",
"method",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/RemoteMethodInvocation/RemoteProxyGenerator.php#L114-L181 |
appserver-io/appserver | src/AppserverIo/Appserver/PersistenceContainer/RemoteMethodInvocation/RemoteProxyGenerator.php | RemoteProxyGenerator.generateMethodParams | protected function generateMethodParams(\ReflectionMethod $reflectionMethod)
{
// initialize the array for the params
$params = array();
// assembler the parameters
foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
$params[] = sprintf('$%s', $reflectionParameter->getName());
}
// implode and return them
return implode(', ', $params);
} | php | protected function generateMethodParams(\ReflectionMethod $reflectionMethod)
{
// initialize the array for the params
$params = array();
// assembler the parameters
foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
$params[] = sprintf('$%s', $reflectionParameter->getName());
}
// implode and return them
return implode(', ', $params);
} | [
"protected",
"function",
"generateMethodParams",
"(",
"\\",
"ReflectionMethod",
"$",
"reflectionMethod",
")",
"{",
"// initialize the array for the params",
"$",
"params",
"=",
"array",
"(",
")",
";",
"// assembler the parameters",
"foreach",
"(",
"$",
"reflectionMethod",... | Generate the method parameters that'll be passed to the __call method.
@param \ReflectionMethod $reflectionMethod The reflection method to generate the parameters for
@return string The method parameters as string | [
"Generate",
"the",
"method",
"parameters",
"that",
"ll",
"be",
"passed",
"to",
"the",
"__call",
"method",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/RemoteMethodInvocation/RemoteProxyGenerator.php#L190-L203 |
appserver-io/appserver | src/AppserverIo/Appserver/PersistenceContainer/RemoteMethodInvocation/RemoteProxyGenerator.php | RemoteProxyGenerator.generateImplements | protected function generateImplements(\ReflectionClass $reflectionClass)
{
// load the class interfaces
$interfaces = $reflectionClass->getInterfaces();
// initialize the array for the
$generateInterfaces = array();
// iterate over the specified interfaces
foreach ($interfaces as $interfaceName => $interface) {
// clean them up to avoid doubles
foreach ($generateInterfaces as $obj) {
if ($obj->isSubclassOf($interface)) {
continue 2;
}
}
// traversable interface can not be implemented directly, so ignore it
if ($interface->getName() === 'Traversable') {
continue;
}
// append the interface
$generateInterfaces[sprintf('\\%s', $interfaceName)] = $interface;
}
// implode the interfaces and return them as string
return implode(', ', array_keys($generateInterfaces));
} | php | protected function generateImplements(\ReflectionClass $reflectionClass)
{
// load the class interfaces
$interfaces = $reflectionClass->getInterfaces();
// initialize the array for the
$generateInterfaces = array();
// iterate over the specified interfaces
foreach ($interfaces as $interfaceName => $interface) {
// clean them up to avoid doubles
foreach ($generateInterfaces as $obj) {
if ($obj->isSubclassOf($interface)) {
continue 2;
}
}
// traversable interface can not be implemented directly, so ignore it
if ($interface->getName() === 'Traversable') {
continue;
}
// append the interface
$generateInterfaces[sprintf('\\%s', $interfaceName)] = $interface;
}
// implode the interfaces and return them as string
return implode(', ', array_keys($generateInterfaces));
} | [
"protected",
"function",
"generateImplements",
"(",
"\\",
"ReflectionClass",
"$",
"reflectionClass",
")",
"{",
"// load the class interfaces",
"$",
"interfaces",
"=",
"$",
"reflectionClass",
"->",
"getInterfaces",
"(",
")",
";",
"// initialize the array for the",
"$",
"... | Generate the implements part of the class definition.
@param \ReflectionClass $reflectionClass The reflection class to generate the implements part for
@return string The implements part of the class definition | [
"Generate",
"the",
"implements",
"part",
"of",
"the",
"class",
"definition",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/RemoteMethodInvocation/RemoteProxyGenerator.php#L212-L241 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Security/StandardAuthenticationManagerFactory.php | StandardAuthenticationManagerFactory.visit | public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration)
{
// initialize the storage instances
$authenticators = new StackableStorage();
$mappings = new StackableStorage();
// initialize the authentication manager
$authenticationManager = new StandardAuthenticationManager();
$authenticationManager->injectMappings($mappings);
$authenticationManager->injectApplication($application);
$authenticationManager->injectAuthenticators($authenticators);
$authenticationManager->injectManagerConfiguration($managerConfiguration);
// attach the instance
$application->addManager($authenticationManager, $managerConfiguration);
} | php | public static function visit(ApplicationInterface $application, ManagerNodeInterface $managerConfiguration)
{
// initialize the storage instances
$authenticators = new StackableStorage();
$mappings = new StackableStorage();
// initialize the authentication manager
$authenticationManager = new StandardAuthenticationManager();
$authenticationManager->injectMappings($mappings);
$authenticationManager->injectApplication($application);
$authenticationManager->injectAuthenticators($authenticators);
$authenticationManager->injectManagerConfiguration($managerConfiguration);
// attach the instance
$application->addManager($authenticationManager, $managerConfiguration);
} | [
"public",
"static",
"function",
"visit",
"(",
"ApplicationInterface",
"$",
"application",
",",
"ManagerNodeInterface",
"$",
"managerConfiguration",
")",
"{",
"// initialize the storage instances",
"$",
"authenticators",
"=",
"new",
"StackableStorage",
"(",
")",
";",
"$"... | 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/Security/StandardAuthenticationManagerFactory.php#L48-L64 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Security/StandardAuthenticationManager.php | StandardAuthenticationManager.getAuthenticator | public function getAuthenticator(MappingInterface $mapping = null)
{
// query whether or not a mapping has been passed
if ($mapping != null) {
// query whether or not we've an authentication manager with the passed key
if (isset($this->authenticators[$authenticatorSerial = $mapping->getAuthenticatorSerial()])) {
return $this->authenticators[$authenticatorSerial];
}
// throw an exception if not
throw new AuthenticationException(sprintf('Can\'t find authenticator serial %s', $authenticatorSerial));
}
// try to find the default authenticator instead
foreach ($this->authenticators as $authenticator) {
if ($authenticator->isDefaultAuthenticator()) {
return $authenticator;
}
}
// throw an exception if we can't find a default authenticator also
throw new AuthenticationException('Can\'t find a default authenticator');
} | php | public function getAuthenticator(MappingInterface $mapping = null)
{
// query whether or not a mapping has been passed
if ($mapping != null) {
// query whether or not we've an authentication manager with the passed key
if (isset($this->authenticators[$authenticatorSerial = $mapping->getAuthenticatorSerial()])) {
return $this->authenticators[$authenticatorSerial];
}
// throw an exception if not
throw new AuthenticationException(sprintf('Can\'t find authenticator serial %s', $authenticatorSerial));
}
// try to find the default authenticator instead
foreach ($this->authenticators as $authenticator) {
if ($authenticator->isDefaultAuthenticator()) {
return $authenticator;
}
}
// throw an exception if we can't find a default authenticator also
throw new AuthenticationException('Can\'t find a default authenticator');
} | [
"public",
"function",
"getAuthenticator",
"(",
"MappingInterface",
"$",
"mapping",
"=",
"null",
")",
"{",
"// query whether or not a mapping has been passed",
"if",
"(",
"$",
"mapping",
"!=",
"null",
")",
"{",
"// query whether or not we've an authentication manager with the ... | Returns the configured authenticator for the passed URL pattern authenticator mapping.
@param \AppserverIo\Psr\Auth\MappingInterface|null $mapping The URL pattern to authenticator mapping
@return \AppserverIo\Storage\StorageInterface The storage with the authentication types
@throws \AppserverIo\Http\Authentication\AuthenticationException Is thrown if the authenticator with the passed key is not available | [
"Returns",
"the",
"configured",
"authenticator",
"for",
"the",
"passed",
"URL",
"pattern",
"authenticator",
"mapping",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Security/StandardAuthenticationManager.php#L136-L159 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Security/StandardAuthenticationManager.php | StandardAuthenticationManager.handleRequest | public function handleRequest(HttpServletRequestInterface $servletRequest, HttpServletResponseInterface $servletResponse)
{
// initialize authenticated flag
$authenticated = true;
// iterate over all servlets and return the matching one
/** @var \AppserverIo\Appserver\ServletEngine\Security\MappingInterface $mapping */
foreach ($this->getMappings() as $mapping) {
// query whether or not the URI matches against the URL pattern
if ($mapping->match($servletRequest)) {
// query whether or not the the HTTP method has to be denied or authenticated
if (in_array($servletRequest->getMethod(), $mapping->getHttpMethodOmissions())) {
// this resource has to be omitted
$authenticated = false;
} elseif (in_array($servletRequest->getMethod(), $mapping->getHttpMethods()) || sizeof($mapping->getHttpMethods()) === 0) {
// load the authentication method and authenticate the request
$authenticator = $this->getAuthenticator($mapping);
// if we've an user principal, query the roles
if ($authenticator->authenticate($servletRequest, $servletResponse)) {
// query whether or not the mapping has roles the user has to be assigned to
if (sizeof($mapping->getRoleNames()) === 0) {
// if not, we're authenticated
return $authenticated;
}
// initialize the roles flag
$inRole = false;
// query whether or not the user has at least one of the requested roles
foreach ($mapping->getRoleNames() as $role) {
if ($servletRequest->isUserInRole(new String($role))) {
$inRole = true;
break;
}
}
// if not, throw an SecurityException
if ($inRole === false) {
throw new SecurityException(sprintf('User doesn\'t have necessary privileges for resource %s', $servletRequest->getUri()), 403);
}
}
}
// load the session
if ($session = $servletRequest->getSession(true)) {
// start it, if not already done
if ($session->isStarted() === false) {
$session->start();
}
// and query whether or not the session contains a user principal
if ($session->hasKey(Constants::PRINCIPAL)) {
$servletRequest->setUserPrincipal($session->getData(Constants::PRINCIPAL));
}
}
// stop processing, because we're authenticated
break;
}
}
// we did not find an adapter for that URI pattern, no authentication required then
return $authenticated;
} | php | public function handleRequest(HttpServletRequestInterface $servletRequest, HttpServletResponseInterface $servletResponse)
{
// initialize authenticated flag
$authenticated = true;
// iterate over all servlets and return the matching one
/** @var \AppserverIo\Appserver\ServletEngine\Security\MappingInterface $mapping */
foreach ($this->getMappings() as $mapping) {
// query whether or not the URI matches against the URL pattern
if ($mapping->match($servletRequest)) {
// query whether or not the the HTTP method has to be denied or authenticated
if (in_array($servletRequest->getMethod(), $mapping->getHttpMethodOmissions())) {
// this resource has to be omitted
$authenticated = false;
} elseif (in_array($servletRequest->getMethod(), $mapping->getHttpMethods()) || sizeof($mapping->getHttpMethods()) === 0) {
// load the authentication method and authenticate the request
$authenticator = $this->getAuthenticator($mapping);
// if we've an user principal, query the roles
if ($authenticator->authenticate($servletRequest, $servletResponse)) {
// query whether or not the mapping has roles the user has to be assigned to
if (sizeof($mapping->getRoleNames()) === 0) {
// if not, we're authenticated
return $authenticated;
}
// initialize the roles flag
$inRole = false;
// query whether or not the user has at least one of the requested roles
foreach ($mapping->getRoleNames() as $role) {
if ($servletRequest->isUserInRole(new String($role))) {
$inRole = true;
break;
}
}
// if not, throw an SecurityException
if ($inRole === false) {
throw new SecurityException(sprintf('User doesn\'t have necessary privileges for resource %s', $servletRequest->getUri()), 403);
}
}
}
// load the session
if ($session = $servletRequest->getSession(true)) {
// start it, if not already done
if ($session->isStarted() === false) {
$session->start();
}
// and query whether or not the session contains a user principal
if ($session->hasKey(Constants::PRINCIPAL)) {
$servletRequest->setUserPrincipal($session->getData(Constants::PRINCIPAL));
}
}
// stop processing, because we're authenticated
break;
}
}
// we did not find an adapter for that URI pattern, no authentication required then
return $authenticated;
} | [
"public",
"function",
"handleRequest",
"(",
"HttpServletRequestInterface",
"$",
"servletRequest",
",",
"HttpServletResponseInterface",
"$",
"servletResponse",
")",
"{",
"// initialize authenticated flag",
"$",
"authenticated",
"=",
"true",
";",
"// iterate over all servlets and... | Handles request in order to authenticate.
@param \AppserverIo\Psr\Servlet\Http\HttpServletRequestInterface $servletRequest The request instance
@param \AppserverIo\Psr\Servlet\Http\HttpServletResponseInterface $servletResponse The response instance
@return boolean TRUE if the authentication has been successful, else FALSE
@throws \Exception | [
"Handles",
"request",
"in",
"order",
"to",
"authenticate",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Security/StandardAuthenticationManager.php#L203-L269 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Security/StandardAuthenticationManager.php | StandardAuthenticationManager.initialize | public function initialize(ApplicationInterface $application)
{
// query whether or not the web application folder exists
if (is_dir($this->getWebappPath()) === false) {
return;
}
// initialize the map for the realms
$realms = new HashMap();
// query whether or not we've manager configuration found
/** @var \AppserverIo\Appserver\Core\Api\Node\ManagerNodeInterface $managerNode */
if ($managerNode = $this->getManagerConfiguration()) {
// initialize the security domains found in the manager configuration
/** @var \AppserverIo\Appserver\Core\Api\Node\SecurityDomainNodeInterface $securityDomainNode */
foreach ($this->getManagerConfiguration()->getSecurityDomains() as $securityDomainNode) {
// create the realm instance
$realm = new Realm($this, $securityDomainNode->getName());
$realm->injectConfiguration($securityDomainNode);
// add the initialized security domain to the map
$realms->add($realm->getName(), $realm);
}
}
// inject the map with the realms
$this->injectRealms($realms);
// initialize the deployment descriptor parser and parse the web application's deployment descriptor for servlets
$deploymentDescriptorParser = new DeploymentDescriptorParser();
$deploymentDescriptorParser->injectAuthenticationContext($this);
$deploymentDescriptorParser->parse();
} | php | public function initialize(ApplicationInterface $application)
{
// query whether or not the web application folder exists
if (is_dir($this->getWebappPath()) === false) {
return;
}
// initialize the map for the realms
$realms = new HashMap();
// query whether or not we've manager configuration found
/** @var \AppserverIo\Appserver\Core\Api\Node\ManagerNodeInterface $managerNode */
if ($managerNode = $this->getManagerConfiguration()) {
// initialize the security domains found in the manager configuration
/** @var \AppserverIo\Appserver\Core\Api\Node\SecurityDomainNodeInterface $securityDomainNode */
foreach ($this->getManagerConfiguration()->getSecurityDomains() as $securityDomainNode) {
// create the realm instance
$realm = new Realm($this, $securityDomainNode->getName());
$realm->injectConfiguration($securityDomainNode);
// add the initialized security domain to the map
$realms->add($realm->getName(), $realm);
}
}
// inject the map with the realms
$this->injectRealms($realms);
// initialize the deployment descriptor parser and parse the web application's deployment descriptor for servlets
$deploymentDescriptorParser = new DeploymentDescriptorParser();
$deploymentDescriptorParser->injectAuthenticationContext($this);
$deploymentDescriptorParser->parse();
} | [
"public",
"function",
"initialize",
"(",
"ApplicationInterface",
"$",
"application",
")",
"{",
"// query whether or not the web application folder exists",
"if",
"(",
"is_dir",
"(",
"$",
"this",
"->",
"getWebappPath",
"(",
")",
")",
"===",
"false",
")",
"{",
"return... | Initializes the manager instance.
@param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance
@return void
@see \AppserverIo\Psr\Application\ManagerInterface::initialize()
@throws \Exception | [
"Initializes",
"the",
"manager",
"instance",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Security/StandardAuthenticationManager.php#L292-L324 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/Node/AccessesNodeTrait.php | AccessesNodeTrait.getAccessesAsArray | public function getAccessesAsArray()
{
// initialize the array for the accesses
$accesses = array();
// iterate over the access nodes and sort them into an array
/** @var \AppserverIo\Appserver\Core\Api\Node\AccessNode $accessNode */
foreach ($this->getAccesses() as $accessNode) {
$accesses[$accessNode->getType()][] = $accessNode->getParamsAsArray();
}
// return the array
return $accesses;
} | php | public function getAccessesAsArray()
{
// initialize the array for the accesses
$accesses = array();
// iterate over the access nodes and sort them into an array
/** @var \AppserverIo\Appserver\Core\Api\Node\AccessNode $accessNode */
foreach ($this->getAccesses() as $accessNode) {
$accesses[$accessNode->getType()][] = $accessNode->getParamsAsArray();
}
// return the array
return $accesses;
} | [
"public",
"function",
"getAccessesAsArray",
"(",
")",
"{",
"// initialize the array for the accesses",
"$",
"accesses",
"=",
"array",
"(",
")",
";",
"// iterate over the access nodes and sort them into an array",
"/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\AccessNode $accessNo... | 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/AccessesNodeTrait.php#L60-L74 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/Node/EnvironmentVariablesNodeTrait.php | EnvironmentVariablesNodeTrait.getEnvironmentVariable | public function getEnvironmentVariable($definition)
{
// Iterate over all environmentVariables
/** @var \AppserverIo\Appserver\Core\Api\Node\EnvironmentVariableNode $environmentVariableNode */
foreach ($this->getEnvironmentVariables() as $environmentVariableNode) {
// If we found one with a matching definition we will return it
if ($environmentVariableNode->getDefinition() === $definition) {
return $environmentVariableNode;
}
}
// Still here? Seems we did not find anything
return false;
} | php | public function getEnvironmentVariable($definition)
{
// Iterate over all environmentVariables
/** @var \AppserverIo\Appserver\Core\Api\Node\EnvironmentVariableNode $environmentVariableNode */
foreach ($this->getEnvironmentVariables() as $environmentVariableNode) {
// If we found one with a matching definition we will return it
if ($environmentVariableNode->getDefinition() === $definition) {
return $environmentVariableNode;
}
}
// Still here? Seems we did not find anything
return false;
} | [
"public",
"function",
"getEnvironmentVariable",
"(",
"$",
"definition",
")",
"{",
"// Iterate over all environmentVariables",
"/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\EnvironmentVariableNode $environmentVariableNode */",
"foreach",
"(",
"$",
"this",
"->",
"getEnvironmentVar... | Will return the environmentVariable node with the specified definition and if nothing could
be found we will return false.
@param string $definition The definition of the environmentVariable in question
@return \AppserverIo\Appserver\Core\Api\Node\EnvironmentVariableNode|boolean The requested environmentVariable node | [
"Will",
"return",
"the",
"environmentVariable",
"node",
"with",
"the",
"specified",
"definition",
"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/EnvironmentVariablesNodeTrait.php#L64-L77 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/Node/EnvironmentVariablesNodeTrait.php | EnvironmentVariablesNodeTrait.getEnvironmentVariablesAsArray | public function getEnvironmentVariablesAsArray()
{
// Iterate over the environmentVariable nodes and sort them into an array
$environmentVariables = array();
/** @var \AppserverIo\Appserver\Core\Api\Node\EnvironmentVariableNode $environmentVariableNode */
foreach ($this->getEnvironmentVariables() as $environmentVariableNode) {
// Restructure to an array
$environmentVariables[] = array(
'condition' => $environmentVariableNode->getCondition(),
'definition' => $environmentVariableNode->getDefinition()
);
}
// Return what we got
return $environmentVariables;
} | php | public function getEnvironmentVariablesAsArray()
{
// Iterate over the environmentVariable nodes and sort them into an array
$environmentVariables = array();
/** @var \AppserverIo\Appserver\Core\Api\Node\EnvironmentVariableNode $environmentVariableNode */
foreach ($this->getEnvironmentVariables() as $environmentVariableNode) {
// Restructure to an array
$environmentVariables[] = array(
'condition' => $environmentVariableNode->getCondition(),
'definition' => $environmentVariableNode->getDefinition()
);
}
// Return what we got
return $environmentVariables;
} | [
"public",
"function",
"getEnvironmentVariablesAsArray",
"(",
")",
"{",
"// Iterate over the environmentVariable nodes and sort them into an array",
"$",
"environmentVariables",
"=",
"array",
"(",
")",
";",
"/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\EnvironmentVariableNode $envi... | Returns the environmentVariables as an associative array.
@return array The array with the sorted environmentVariables | [
"Returns",
"the",
"environmentVariables",
"as",
"an",
"associative",
"array",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/EnvironmentVariablesNodeTrait.php#L84-L99 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/LoggerFactory.php | LoggerFactory.factory | public static function factory($loggerNode)
{
// initialize the processors
$processors = array();
/** @var \AppserverIo\Appserver\Core\Api\Node\ProcessorNode $processorNode */
foreach ($loggerNode->getProcessors() as $processorNode) {
$reflectionClass = new \ReflectionClass($processorNode->getType());
$processors[] = $reflectionClass->newInstanceArgs($processorNode->getParamsAsArray());
}
// initialize the handlers
$handlers = array();
/** @var \AppserverIo\Appserver\Core\Api\Node\HandlerNode $handlerNode */
foreach ($loggerNode->getHandlers() as $handlerNode) {
// initialize the handler node
$reflectionClass = new \ReflectionClass($handlerNode->getType());
$handler = $reflectionClass->newInstanceArgs($handlerNode->getParamsAsArray());
// if we've a formatter, initialize the formatter also
if ($formatterNode = $handlerNode->getFormatter()) {
$reflectionClass = new \ReflectionClass($formatterNode->getType());
$handler->setFormatter($reflectionClass->newInstanceArgs($formatterNode->getParamsAsArray()));
}
// add the handler
$handlers[] = $handler;
}
// prepare the logger params
$loggerParams = array($loggerNode->getChannelName(), $handlers, $processors);
$loggerParams = array_merge($loggerParams, $loggerNode->getParamsAsArray());
// initialize the logger instance itself
$reflectionClass = new \ReflectionClass($loggerNode->getType());
$loggerInstance = $reflectionClass->newInstanceArgs($loggerParams);
// return the instance
return $loggerInstance;
} | php | public static function factory($loggerNode)
{
// initialize the processors
$processors = array();
/** @var \AppserverIo\Appserver\Core\Api\Node\ProcessorNode $processorNode */
foreach ($loggerNode->getProcessors() as $processorNode) {
$reflectionClass = new \ReflectionClass($processorNode->getType());
$processors[] = $reflectionClass->newInstanceArgs($processorNode->getParamsAsArray());
}
// initialize the handlers
$handlers = array();
/** @var \AppserverIo\Appserver\Core\Api\Node\HandlerNode $handlerNode */
foreach ($loggerNode->getHandlers() as $handlerNode) {
// initialize the handler node
$reflectionClass = new \ReflectionClass($handlerNode->getType());
$handler = $reflectionClass->newInstanceArgs($handlerNode->getParamsAsArray());
// if we've a formatter, initialize the formatter also
if ($formatterNode = $handlerNode->getFormatter()) {
$reflectionClass = new \ReflectionClass($formatterNode->getType());
$handler->setFormatter($reflectionClass->newInstanceArgs($formatterNode->getParamsAsArray()));
}
// add the handler
$handlers[] = $handler;
}
// prepare the logger params
$loggerParams = array($loggerNode->getChannelName(), $handlers, $processors);
$loggerParams = array_merge($loggerParams, $loggerNode->getParamsAsArray());
// initialize the logger instance itself
$reflectionClass = new \ReflectionClass($loggerNode->getType());
$loggerInstance = $reflectionClass->newInstanceArgs($loggerParams);
// return the instance
return $loggerInstance;
} | [
"public",
"static",
"function",
"factory",
"(",
"$",
"loggerNode",
")",
"{",
"// initialize the processors",
"$",
"processors",
"=",
"array",
"(",
")",
";",
"/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\ProcessorNode $processorNode */",
"foreach",
"(",
"$",
"loggerNo... | Creates a new logger instance based on the passed logger configuration.
@param object $loggerNode The logger configuration
@return \Psr\Log\LoggerInterface The logger instance | [
"Creates",
"a",
"new",
"logger",
"instance",
"based",
"on",
"the",
"passed",
"logger",
"configuration",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/LoggerFactory.php#L42-L81 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php | FilesystemSessionHandler.load | public function load($id)
{
try {
// prepare the pathname to the file containing the session data
$filename = $this->getSessionSettings()->getSessionFilePrefix() . $id;
$pathname = $this->getSessionSavePath($filename);
// unpersist and return the session from the file system
return $this->unpersist($pathname);
} catch (SessionDataNotReadableException $sdnre) {
$this->delete($id);
throw $sdnre;
}
} | php | public function load($id)
{
try {
// prepare the pathname to the file containing the session data
$filename = $this->getSessionSettings()->getSessionFilePrefix() . $id;
$pathname = $this->getSessionSavePath($filename);
// unpersist and return the session from the file system
return $this->unpersist($pathname);
} catch (SessionDataNotReadableException $sdnre) {
$this->delete($id);
throw $sdnre;
}
} | [
"public",
"function",
"load",
"(",
"$",
"id",
")",
"{",
"try",
"{",
"// prepare the pathname to the file containing the session data",
"$",
"filename",
"=",
"$",
"this",
"->",
"getSessionSettings",
"(",
")",
"->",
"getSessionFilePrefix",
"(",
")",
".",
"$",
"id",
... | Loads the session with the passed ID from the persistence layer and
returns it.
@param string $id The ID of the session we want to unpersist
@return \AppserverIo\Psr\Servlet\ServletSessionInterface The unpersisted session | [
"Loads",
"the",
"session",
"with",
"the",
"passed",
"ID",
"from",
"the",
"persistence",
"layer",
"and",
"returns",
"it",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php#L49-L64 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php | FilesystemSessionHandler.delete | public function delete($id)
{
// prepare the pathname to the file containing the session data
$filename = $this->getSessionSettings()->getSessionFilePrefix() . $id;
$pathname = $this->getSessionSavePath($filename);
// remove the session from the file system
if ($this->removeSessionFile($pathname) === false) {
throw new SessionCanNotBeDeletedException(
sprintf('Session with ID %s can not be deleted', $id)
);
}
} | php | public function delete($id)
{
// prepare the pathname to the file containing the session data
$filename = $this->getSessionSettings()->getSessionFilePrefix() . $id;
$pathname = $this->getSessionSavePath($filename);
// remove the session from the file system
if ($this->removeSessionFile($pathname) === false) {
throw new SessionCanNotBeDeletedException(
sprintf('Session with ID %s can not be deleted', $id)
);
}
} | [
"public",
"function",
"delete",
"(",
"$",
"id",
")",
"{",
"// prepare the pathname to the file containing the session data",
"$",
"filename",
"=",
"$",
"this",
"->",
"getSessionSettings",
"(",
")",
"->",
"getSessionFilePrefix",
"(",
")",
".",
"$",
"id",
";",
"$",
... | Deletes the session with the passed ID from the persistence layer.
@param string $id The ID of the session we want to delete
@return void
@throws \AppserverIo\Appserver\ServletEngine\SessionCanNotBeDeletedException Is thrown if the session can't be deleted | [
"Deletes",
"the",
"session",
"with",
"the",
"passed",
"ID",
"from",
"the",
"persistence",
"layer",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php#L74-L87 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php | FilesystemSessionHandler.save | public function save(ServletSessionInterface $session)
{
// don't save the session if it has been destroyed
if ($session->getId() == null) {
return;
}
// prepare the session filename
$sessionFilename = $this->getSessionSavePath($this->getSessionSettings()->getSessionFilePrefix() . $session->getId());
// marshall the session
$marshalledSession = $this->marshall($session);
// decode the session from the filesystem
$fh = fopen($sessionFilename, 'w+');
// try to lock the session file
if (flock($fh, LOCK_EX) === false) {
throw new SessionCanNotBeSavedException(sprintf('Can\'t get lock to save session data to file "%s"', $sessionFilename));
}
// finally try to write the session data to the file
if (fwrite($fh, $marshalledSession) === false) {
throw new SessionCanNotBeSavedException(sprintf('Session with ID "%s" can\'t be saved', $session->getId()));
}
// try to unlock the session file
if (flock($fh, LOCK_UN) === false) {
throw new SessionCanNotBeSavedException(sprintf('Can\'t unlock session file "%s" after saving data', $sessionFilename));
}
} | php | public function save(ServletSessionInterface $session)
{
// don't save the session if it has been destroyed
if ($session->getId() == null) {
return;
}
// prepare the session filename
$sessionFilename = $this->getSessionSavePath($this->getSessionSettings()->getSessionFilePrefix() . $session->getId());
// marshall the session
$marshalledSession = $this->marshall($session);
// decode the session from the filesystem
$fh = fopen($sessionFilename, 'w+');
// try to lock the session file
if (flock($fh, LOCK_EX) === false) {
throw new SessionCanNotBeSavedException(sprintf('Can\'t get lock to save session data to file "%s"', $sessionFilename));
}
// finally try to write the session data to the file
if (fwrite($fh, $marshalledSession) === false) {
throw new SessionCanNotBeSavedException(sprintf('Session with ID "%s" can\'t be saved', $session->getId()));
}
// try to unlock the session file
if (flock($fh, LOCK_UN) === false) {
throw new SessionCanNotBeSavedException(sprintf('Can\'t unlock session file "%s" after saving data', $sessionFilename));
}
} | [
"public",
"function",
"save",
"(",
"ServletSessionInterface",
"$",
"session",
")",
"{",
"// don't save the session if it has been destroyed",
"if",
"(",
"$",
"session",
"->",
"getId",
"(",
")",
"==",
"null",
")",
"{",
"return",
";",
"}",
"// prepare the session file... | Saves the passed session to the persistence layer.
@param \AppserverIo\Psr\Servlet\ServletSessionInterface $session The session to save
@return void
@throws \AppserverIo\Appserver\ServletEngine\SessionCanNotBeSavedException Is thrown if the session can't be saved or no lock for the session file can be obtained | [
"Saves",
"the",
"passed",
"session",
"to",
"the",
"persistence",
"layer",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php#L97-L128 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php | FilesystemSessionHandler.unpersist | protected function unpersist($pathname)
{
// the requested session file is not a valid file
if ($this->sessionFileExists($pathname) === false) {
return;
}
// initialize the variable for the marshalled session data
$marshalled = null;
// decode the session from the filesystem
$fh = fopen($pathname, 'r');
// try to lock the session file
if (flock($fh, LOCK_EX) === false) {
throw new SessionDataNotReadableException(sprintf('Can\'t get lock to load session data from file "%s"', $pathname));
}
// read the marshalled session data from the file
while (feof($fh) === false) {
$marshalled .= fread($fh, 1024);
}
// try to unlock the session file
if (flock($fh, LOCK_UN) === false) {
throw new SessionDataNotReadableException(sprintf('Can\'t unlock session file "%s" after reading data', $pathname));
}
// query whether or not the session has been unmarshalled successfully
if ($marshalled === null) {
throw new SessionDataNotReadableException(sprintf('Can\'t load any session data from file %s', $pathname));
}
// unmarshall and return the session data
return $this->unmarshall($marshalled);
} | php | protected function unpersist($pathname)
{
// the requested session file is not a valid file
if ($this->sessionFileExists($pathname) === false) {
return;
}
// initialize the variable for the marshalled session data
$marshalled = null;
// decode the session from the filesystem
$fh = fopen($pathname, 'r');
// try to lock the session file
if (flock($fh, LOCK_EX) === false) {
throw new SessionDataNotReadableException(sprintf('Can\'t get lock to load session data from file "%s"', $pathname));
}
// read the marshalled session data from the file
while (feof($fh) === false) {
$marshalled .= fread($fh, 1024);
}
// try to unlock the session file
if (flock($fh, LOCK_UN) === false) {
throw new SessionDataNotReadableException(sprintf('Can\'t unlock session file "%s" after reading data', $pathname));
}
// query whether or not the session has been unmarshalled successfully
if ($marshalled === null) {
throw new SessionDataNotReadableException(sprintf('Can\'t load any session data from file %s', $pathname));
}
// unmarshall and return the session data
return $this->unmarshall($marshalled);
} | [
"protected",
"function",
"unpersist",
"(",
"$",
"pathname",
")",
"{",
"// the requested session file is not a valid file",
"if",
"(",
"$",
"this",
"->",
"sessionFileExists",
"(",
"$",
"pathname",
")",
"===",
"false",
")",
"{",
"return",
";",
"}",
"// initialize th... | Tries to load the session data from the passed filename.
@param string $pathname The path of the file to load the session data from
@return \AppserverIo\Psr\Servlet\Http\HttpSessionInterface The unmarshalled session
@throws \AppserverIo\Appserver\ServletEngine\SessionDataNotReadableException Is thrown if the file containing the session data is not readable or no lock for the session file can be obtained | [
"Tries",
"to",
"load",
"the",
"session",
"data",
"from",
"the",
"passed",
"filename",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php#L138-L174 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php | FilesystemSessionHandler.collectGarbage | public function collectGarbage()
{
// counter to store the number of removed sessions
$sessionRemovalCount = 0;
// prepare the expression to select the session files
$globExpression = sprintf('%s*', $this->getSessionSavePath($this->getSessionSettings()->getSessionFilePrefix()));
// iterate over the found session files
foreach (glob($globExpression) as $pathname) {
// unpersist the session
$session = $this->unpersist($pathname);
// query whether or not the session has been expired
if ($this->sessionTimedOut($session)) {
// if yes, delete the session + raise the session removal count
$this->delete($session->getId());
$sessionRemovalCount++;
}
}
// return the number of removed sessions
return $sessionRemovalCount;
} | php | public function collectGarbage()
{
// counter to store the number of removed sessions
$sessionRemovalCount = 0;
// prepare the expression to select the session files
$globExpression = sprintf('%s*', $this->getSessionSavePath($this->getSessionSettings()->getSessionFilePrefix()));
// iterate over the found session files
foreach (glob($globExpression) as $pathname) {
// unpersist the session
$session = $this->unpersist($pathname);
// query whether or not the session has been expired
if ($this->sessionTimedOut($session)) {
// if yes, delete the session + raise the session removal count
$this->delete($session->getId());
$sessionRemovalCount++;
}
}
// return the number of removed sessions
return $sessionRemovalCount;
} | [
"public",
"function",
"collectGarbage",
"(",
")",
"{",
"// counter to store the number of removed sessions",
"$",
"sessionRemovalCount",
"=",
"0",
";",
"// prepare the expression to select the session files",
"$",
"globExpression",
"=",
"sprintf",
"(",
"'%s*'",
",",
"$",
"t... | Collects the garbage by deleting expired sessions.
@return integer The number of removed sessions | [
"Collects",
"the",
"garbage",
"by",
"deleting",
"expired",
"sessions",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php#L181-L205 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php | FilesystemSessionHandler.getSessionSavePath | protected function getSessionSavePath($toAppend = null)
{
// load the default path
$sessionSavePath = $this->getSessionSettings()->getSessionSavePath();
// check if we've something to append
if ($toAppend != null) {
$sessionSavePath = $sessionSavePath . DIRECTORY_SEPARATOR . $toAppend;
}
// return the session save path
return $sessionSavePath;
} | php | protected function getSessionSavePath($toAppend = null)
{
// load the default path
$sessionSavePath = $this->getSessionSettings()->getSessionSavePath();
// check if we've something to append
if ($toAppend != null) {
$sessionSavePath = $sessionSavePath . DIRECTORY_SEPARATOR . $toAppend;
}
// return the session save path
return $sessionSavePath;
} | [
"protected",
"function",
"getSessionSavePath",
"(",
"$",
"toAppend",
"=",
"null",
")",
"{",
"// load the default path",
"$",
"sessionSavePath",
"=",
"$",
"this",
"->",
"getSessionSettings",
"(",
")",
"->",
"getSessionSavePath",
"(",
")",
";",
"// check if we've some... | Returns the default path to persist sessions.
@param string $toAppend A relative path to append to the session save path
@return string The default path to persist session | [
"Returns",
"the",
"default",
"path",
"to",
"persist",
"sessions",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Session/FilesystemSessionHandler.php#L241-L253 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Listeners/SwitchUserListener.php | SwitchUserListener.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());
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === 'WIN') {
$applicationServer->getSystemLogger()->info('Don\'t switch UID to \'%s\' because OS is Windows');
return;
}
// initialize the variable for user/group
$uid = 0;
$gid = 0;
// throw an exception if the POSIX extension is not available
if (extension_loaded('posix') === false) {
throw new \Exception('Can\'t switch user, because POSIX extension is not available');
}
// print a message with the old UID/EUID
$applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid());
// extract the user and group name as variables
extract(posix_getgrnam($applicationServer->getSystemConfiguration()->getGroup()));
extract(posix_getpwnam($applicationServer->getSystemConfiguration()->getUser()));
// switch the effective GID to the passed group
if (posix_setegid($gid) === false) {
$applicationServer->getSystemLogger()->error(sprintf('Can\'t switch GID to \'%s\'', $gid));
}
// print a message with the new GID/EGID
$applicationServer->getSystemLogger()->info("Running as group " . posix_getgid() . "/" . posix_getegid());
// switch the effective UID to the passed user
if (posix_seteuid($uid) === false) {
$applicationServer->getSystemLogger()->error(sprintf('Can\'t switch UID to \'%s\'', $uid));
}
// print a message with the new UID/EUID
$applicationServer->getSystemLogger()->info("Running as user " . posix_getuid() . "/" . posix_geteuid());
} 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());
// don't do anything under Windows
if (FileSystem::getOsIdentifier() === 'WIN') {
$applicationServer->getSystemLogger()->info('Don\'t switch UID to \'%s\' because OS is Windows');
return;
}
// initialize the variable for user/group
$uid = 0;
$gid = 0;
// throw an exception if the POSIX extension is not available
if (extension_loaded('posix') === false) {
throw new \Exception('Can\'t switch user, because POSIX extension is not available');
}
// print a message with the old UID/EUID
$applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid());
// extract the user and group name as variables
extract(posix_getgrnam($applicationServer->getSystemConfiguration()->getGroup()));
extract(posix_getpwnam($applicationServer->getSystemConfiguration()->getUser()));
// switch the effective GID to the passed group
if (posix_setegid($gid) === false) {
$applicationServer->getSystemLogger()->error(sprintf('Can\'t switch GID to \'%s\'', $gid));
}
// print a message with the new GID/EGID
$applicationServer->getSystemLogger()->info("Running as group " . posix_getgid() . "/" . posix_getegid());
// switch the effective UID to the passed user
if (posix_seteuid($uid) === false) {
$applicationServer->getSystemLogger()->error(sprintf('Can\'t switch UID to \'%s\'', $uid));
}
// print a message with the new UID/EUID
$applicationServer->getSystemLogger()->info("Running as user " . posix_getuid() . "/" . posix_geteuid());
} 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/SwitchUserListener.php#L46-L98 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/Node/VirtualHostsNodeTrait.php | VirtualHostsNodeTrait.getVirtualHostsAsArray | public function getVirtualHostsAsArray()
{
// prepare the array containing the virtual host configuration
$virtualHosts = array();
// iterate hosts
/** @var \AppserverIo\Appserver\Core\Api\Node\VirtualHostNode $virtualHost */
foreach ($this->getVirtualHosts() as $virtualHost) {
// explode the virtual host names
$virtualHostNames = explode(' ', $virtualHost->getName());
// Some virtual hosts might have an extensionType to expand their name attribute, check for that
if ($virtualHost->hasInjector()) {
$virtualHostNames = array_merge($virtualHostNames, explode(' ', $virtualHost->getInjection()));
}
// prepare the virtual hosts
foreach ($virtualHostNames as $virtualHostName) {
// set all virtual hosts params per key for faster matching later on
$virtualHosts[trim($virtualHostName)] = array(
'params' => $virtualHost->getParamsAsArray(),
'headers' => $virtualHost->getHeadersAsArray(),
'rewriteMaps' => $virtualHost->getRewriteMapsAsArray(),
'rewrites' => $virtualHost->getRewritesAsArray(),
'environmentVariables' => $virtualHost->getEnvironmentVariablesAsArray(),
'accesses' => $virtualHost->getAccessesAsArray(),
'locations' => $virtualHost->getLocationsAsArray(),
'authentications' => $virtualHost->getAuthenticationsAsArray(),
'analytics' => $virtualHost->getAnalyticsAsArray()
);
}
}
// return the virtual host configuration
return $virtualHosts;
} | php | public function getVirtualHostsAsArray()
{
// prepare the array containing the virtual host configuration
$virtualHosts = array();
// iterate hosts
/** @var \AppserverIo\Appserver\Core\Api\Node\VirtualHostNode $virtualHost */
foreach ($this->getVirtualHosts() as $virtualHost) {
// explode the virtual host names
$virtualHostNames = explode(' ', $virtualHost->getName());
// Some virtual hosts might have an extensionType to expand their name attribute, check for that
if ($virtualHost->hasInjector()) {
$virtualHostNames = array_merge($virtualHostNames, explode(' ', $virtualHost->getInjection()));
}
// prepare the virtual hosts
foreach ($virtualHostNames as $virtualHostName) {
// set all virtual hosts params per key for faster matching later on
$virtualHosts[trim($virtualHostName)] = array(
'params' => $virtualHost->getParamsAsArray(),
'headers' => $virtualHost->getHeadersAsArray(),
'rewriteMaps' => $virtualHost->getRewriteMapsAsArray(),
'rewrites' => $virtualHost->getRewritesAsArray(),
'environmentVariables' => $virtualHost->getEnvironmentVariablesAsArray(),
'accesses' => $virtualHost->getAccessesAsArray(),
'locations' => $virtualHost->getLocationsAsArray(),
'authentications' => $virtualHost->getAuthenticationsAsArray(),
'analytics' => $virtualHost->getAnalyticsAsArray()
);
}
}
// return the virtual host configuration
return $virtualHosts;
} | [
"public",
"function",
"getVirtualHostsAsArray",
"(",
")",
"{",
"// prepare the array containing the virtual host configuration",
"$",
"virtualHosts",
"=",
"array",
"(",
")",
";",
"// iterate hosts",
"/** @var \\AppserverIo\\Appserver\\Core\\Api\\Node\\VirtualHostNode $virtualHost */",
... | Returns the virtual hosts as an associative array
@return array The array with the sorted virtual hosts | [
"Returns",
"the",
"virtual",
"hosts",
"as",
"an",
"associative",
"array"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/VirtualHostsNodeTrait.php#L61-L97 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Listeners/ExtractArchivesListener.php | ExtractArchivesListener.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());
// add the configured extractors to the internal array
/** @var \AppserverIo\Appserver\Core\Api\Node\ExtractorNodeInterface $extractorNode */
foreach ($applicationServer->getSystemConfiguration()->getExtractors() as $extractorNode) {
/** @var \AppserverIo\Appserver\Core\Extractors\ExtractorFactoryInterface $extractorFactory */
$extractorFactory = $extractorNode->getFactory();
// use the factory if available
/** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleInterface $console */
$extractor = $extractorFactory::factory($applicationServer, $extractorNode);
// deploy the found application archives
$extractor->deployWebapps();
// log that the extractor has successfully been initialized and executed
$applicationServer->getSystemLogger()->debug(
sprintf('Extractor %s successfully initialized and executed', $extractorNode->getName())
);
}
} 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());
// add the configured extractors to the internal array
/** @var \AppserverIo\Appserver\Core\Api\Node\ExtractorNodeInterface $extractorNode */
foreach ($applicationServer->getSystemConfiguration()->getExtractors() as $extractorNode) {
/** @var \AppserverIo\Appserver\Core\Extractors\ExtractorFactoryInterface $extractorFactory */
$extractorFactory = $extractorNode->getFactory();
// use the factory if available
/** @var \AppserverIo\Appserver\Core\Interfaces\ConsoleInterface $console */
$extractor = $extractorFactory::factory($applicationServer, $extractorNode);
// deploy the found application archives
$extractor->deployWebapps();
// log that the extractor has successfully been initialized and executed
$applicationServer->getSystemLogger()->debug(
sprintf('Extractor %s successfully initialized and executed', $extractorNode->getName())
);
}
} 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/ExtractArchivesListener.php#L45-L78 |
appserver-io/appserver | src/AppserverIo/Appserver/Naming/NamingDirectory.php | NamingDirectory.bind | public function bind($name, $value, array $args = array())
{
try {
// strip off the schema
$key = $this->stripSchema($name);
// bind the value, if possible
if ($this->hasAttribute($key) === false) {
$this->setAttribute($key, array($value, $args));
return;
}
// throw an exeception if the name has already been bound
throw new \Exception(sprintf('A value with name %s has already been bound to naming directory %s', $name, $this->getIdentifier()));
} catch (\Exception $e) {
throw new NamingException(sprintf('Cant\'t bind %s to naming directory %s', $name, $this->getIdentifier()), null, $e);
}
} | php | public function bind($name, $value, array $args = array())
{
try {
// strip off the schema
$key = $this->stripSchema($name);
// bind the value, if possible
if ($this->hasAttribute($key) === false) {
$this->setAttribute($key, array($value, $args));
return;
}
// throw an exeception if the name has already been bound
throw new \Exception(sprintf('A value with name %s has already been bound to naming directory %s', $name, $this->getIdentifier()));
} catch (\Exception $e) {
throw new NamingException(sprintf('Cant\'t bind %s to naming directory %s', $name, $this->getIdentifier()), null, $e);
}
} | [
"public",
"function",
"bind",
"(",
"$",
"name",
",",
"$",
"value",
",",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"// strip off the schema",
"$",
"key",
"=",
"$",
"this",
"->",
"stripSchema",
"(",
"$",
"name",
")",
";",
"/... | Binds the passed instance with the name to the naming directory.
@param string $name The name to bind the value with
@param mixed $value The object instance to bind
@param array $args The array with the arguments
@return void
@throws \AppserverIo\Psr\Naming\NamingException Is thrown if the value can't be bound ot the directory | [
"Binds",
"the",
"passed",
"instance",
"with",
"the",
"name",
"to",
"the",
"naming",
"directory",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Naming/NamingDirectory.php#L136-L155 |
appserver-io/appserver | src/AppserverIo/Appserver/Naming/NamingDirectory.php | NamingDirectory.unbind | public function unbind($name)
{
try {
// strip off the schema
$key = $this->stripSchema($name);
$this->removeAttribute($key);
} catch (\Exception $e) {
throw new NamingException(sprintf('Cant\'t unbind %s from naming directory %s', $name, $this->getIdentifier()), null, $e);
}
} | php | public function unbind($name)
{
try {
// strip off the schema
$key = $this->stripSchema($name);
$this->removeAttribute($key);
} catch (\Exception $e) {
throw new NamingException(sprintf('Cant\'t unbind %s from naming directory %s', $name, $this->getIdentifier()), null, $e);
}
} | [
"public",
"function",
"unbind",
"(",
"$",
"name",
")",
"{",
"try",
"{",
"// strip off the schema",
"$",
"key",
"=",
"$",
"this",
"->",
"stripSchema",
"(",
"$",
"name",
")",
";",
"$",
"this",
"->",
"removeAttribute",
"(",
"$",
"key",
")",
";",
"}",
"c... | Unbinds the named object from the naming directory.
@param string $name The name of the object to unbind
@return void | [
"Unbinds",
"the",
"named",
"object",
"from",
"the",
"naming",
"directory",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Naming/NamingDirectory.php#L193-L204 |
appserver-io/appserver | src/AppserverIo/Appserver/Naming/NamingDirectory.php | NamingDirectory.search | public function search($name, array $args = array())
{
try {
// strip off the schema
$key = $this->stripSchema($name);
// throw an exception if we can't find a value
if ($this->hasAttribute($key) === false) {
throw new \Exception(sprintf('Requested value %s has not been bound to naming directory %s', $name, $this->getIdentifier()));
}
// try to load the value, which may also be NULL
if (($found = $this->getAttribute($key)) == null) {
return;
}
// load the binded value/args
list ($value, $bindArgs) = $found;
// check if we've a callback method
if (is_callable($value)) {
// if yes, merge the params and invoke the callback
foreach ($args as $arg) {
$bindArgs[] = $arg;
}
// invoke the callback
return call_user_func_array($value, $bindArgs);
}
// simply return the value
return $value;
} catch (\Exception $e) {
throw new NamingException(sprintf('Cant\'t resolve %s in naming directory %s', $name, $this->getIdentifier()), null, $e);
}
} | php | public function search($name, array $args = array())
{
try {
// strip off the schema
$key = $this->stripSchema($name);
// throw an exception if we can't find a value
if ($this->hasAttribute($key) === false) {
throw new \Exception(sprintf('Requested value %s has not been bound to naming directory %s', $name, $this->getIdentifier()));
}
// try to load the value, which may also be NULL
if (($found = $this->getAttribute($key)) == null) {
return;
}
// load the binded value/args
list ($value, $bindArgs) = $found;
// check if we've a callback method
if (is_callable($value)) {
// if yes, merge the params and invoke the callback
foreach ($args as $arg) {
$bindArgs[] = $arg;
}
// invoke the callback
return call_user_func_array($value, $bindArgs);
}
// simply return the value
return $value;
} catch (\Exception $e) {
throw new NamingException(sprintf('Cant\'t resolve %s in naming directory %s', $name, $this->getIdentifier()), null, $e);
}
} | [
"public",
"function",
"search",
"(",
"$",
"name",
",",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"// strip off the schema",
"$",
"key",
"=",
"$",
"this",
"->",
"stripSchema",
"(",
"$",
"name",
")",
";",
"// throw an exception if... | Queries the naming directory for the requested name and returns the value
or invokes the bound callback.
@param string $name The name of the requested value
@param array $args The arguments to pass to the callback
@return mixed The requested value
@throws \AppserverIo\Psr\Naming\NamingException Is thrown if the requested name can't be resolved in the directory | [
"Queries",
"the",
"naming",
"directory",
"for",
"the",
"requested",
"name",
"and",
"returns",
"the",
"value",
"or",
"invokes",
"the",
"bound",
"callback",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Naming/NamingDirectory.php#L216-L253 |
appserver-io/appserver | src/AppserverIo/Appserver/Naming/NamingDirectory.php | NamingDirectory.getIdentifier | public function getIdentifier()
{
// check if we've a parent directory
if ($parent = $this->getParent()) {
return $parent->getIdentifier() . $this->getName() . '/';
}
// load the scheme to prerpare the identifier with
if ($scheme = $this->getScheme()) {
return $scheme . ':' . $this->getName();
}
// the root node needs a scheme
throw new NamingException(sprintf('Missing scheme for naming directory', $this->getName()));
} | php | public function getIdentifier()
{
// check if we've a parent directory
if ($parent = $this->getParent()) {
return $parent->getIdentifier() . $this->getName() . '/';
}
// load the scheme to prerpare the identifier with
if ($scheme = $this->getScheme()) {
return $scheme . ':' . $this->getName();
}
// the root node needs a scheme
throw new NamingException(sprintf('Missing scheme for naming directory', $this->getName()));
} | [
"public",
"function",
"getIdentifier",
"(",
")",
"{",
"// check if we've a parent directory",
"if",
"(",
"$",
"parent",
"=",
"$",
"this",
"->",
"getParent",
"(",
")",
")",
"{",
"return",
"$",
"parent",
"->",
"getIdentifier",
"(",
")",
".",
"$",
"this",
"->... | The unique identifier of this directory. That'll be build up
recursive from the scheme and the root directory.
@return string The unique identifier
@see \AppserverIo\Storage\StorageInterface::getIdentifier()
@throws \AppserverIo\Psr\Naming\NamingException | [
"The",
"unique",
"identifier",
"of",
"this",
"directory",
".",
"That",
"ll",
"be",
"build",
"up",
"recursive",
"from",
"the",
"scheme",
"and",
"the",
"root",
"directory",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Naming/NamingDirectory.php#L264-L279 |
appserver-io/appserver | src/AppserverIo/Appserver/Naming/NamingDirectory.php | NamingDirectory.createSubdirectory | public function createSubdirectory($name, array $filter = array())
{
try {
// query whether or not the passed directory is relative or absolute
if ($this->containsScheme($name)) {
$this->setAttribute($this->stripSchema($name), '.');
} else {
// if the directory is relative, append it
if ($directory = $this->getDirectory()) {
$directory = $this->appendDirectory($name);
} else {
$this->setDirectory($directory = $name);
}
// bind the default value
$this->bind($directory, '.');
}
// return the instance itself
return $this;
} catch (\Exception $e) {
throw new NamingException(sprintf('Can\'t create subdirectory %s', $name), null, $e);
}
} | php | public function createSubdirectory($name, array $filter = array())
{
try {
// query whether or not the passed directory is relative or absolute
if ($this->containsScheme($name)) {
$this->setAttribute($this->stripSchema($name), '.');
} else {
// if the directory is relative, append it
if ($directory = $this->getDirectory()) {
$directory = $this->appendDirectory($name);
} else {
$this->setDirectory($directory = $name);
}
// bind the default value
$this->bind($directory, '.');
}
// return the instance itself
return $this;
} catch (\Exception $e) {
throw new NamingException(sprintf('Can\'t create subdirectory %s', $name), null, $e);
}
} | [
"public",
"function",
"createSubdirectory",
"(",
"$",
"name",
",",
"array",
"$",
"filter",
"=",
"array",
"(",
")",
")",
"{",
"try",
"{",
"// query whether or not the passed directory is relative or absolute",
"if",
"(",
"$",
"this",
"->",
"containsScheme",
"(",
"$... | Create and return a new naming subdirectory with the attributes
of this one.
@param string $name The name of the new subdirectory
@param array $filter Array with filters that will be applied when copy the attributes
@return \AppserverIo\Appserver\Naming\NamingDirectory The new naming subdirectory | [
"Create",
"and",
"return",
"a",
"new",
"naming",
"subdirectory",
"with",
"the",
"attributes",
"of",
"this",
"one",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Naming/NamingDirectory.php#L324-L348 |
appserver-io/appserver | src/AppserverIo/Appserver/Naming/NamingDirectory.php | NamingDirectory.prepareDirectory | public function prepareDirectory($name)
{
// query whether or not the passed name is a absolute directory
if ($this->containsScheme($name)) {
return $this->stripSchema($name);
}
// if not, only append it and return the new path
return $this->appendDirectory($name);
} | php | public function prepareDirectory($name)
{
// query whether or not the passed name is a absolute directory
if ($this->containsScheme($name)) {
return $this->stripSchema($name);
}
// if not, only append it and return the new path
return $this->appendDirectory($name);
} | [
"public",
"function",
"prepareDirectory",
"(",
"$",
"name",
")",
"{",
"// query whether or not the passed name is a absolute directory",
"if",
"(",
"$",
"this",
"->",
"containsScheme",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"this",
"->",
"stripSchema",
"(... | Prepare's and return's the path either by stripping of the scheme
if it is absolute or append the name, if it is relative.
@param string $name The name to prepare the directory with
@return string The prepared path | [
"Prepare",
"s",
"and",
"return",
"s",
"the",
"path",
"either",
"by",
"stripping",
"of",
"the",
"scheme",
"if",
"it",
"is",
"absolute",
"or",
"append",
"the",
"name",
"if",
"it",
"is",
"relative",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Naming/NamingDirectory.php#L380-L390 |
appserver-io/appserver | src/AppserverIo/Appserver/ServletEngine/Security/Mapping.php | Mapping.match | public function match(HttpServletRequestInterface $servletRequest)
{
return fnmatch($this->getUrlPattern(), $servletRequest->getServletPath() . $servletRequest->getPathInfo());
} | php | public function match(HttpServletRequestInterface $servletRequest)
{
return fnmatch($this->getUrlPattern(), $servletRequest->getServletPath() . $servletRequest->getPathInfo());
} | [
"public",
"function",
"match",
"(",
"HttpServletRequestInterface",
"$",
"servletRequest",
")",
"{",
"return",
"fnmatch",
"(",
"$",
"this",
"->",
"getUrlPattern",
"(",
")",
",",
"$",
"servletRequest",
"->",
"getServletPath",
"(",
")",
".",
"$",
"servletRequest",
... | Return's TRUE if the passed request matches the mappings URL patter.
@param \AppserverIo\Psr\Servlet\Http\HttpServletRequestInterface $servletRequest The request to match
@return boolean TRUE if the request matches, else FALSE | [
"Return",
"s",
"TRUE",
"if",
"the",
"passed",
"request",
"matches",
"the",
"mappings",
"URL",
"patter",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/ServletEngine/Security/Mapping.php#L153-L156 |
appserver-io/appserver | src/AppserverIo/Appserver/PersistenceContainer/BeanLocator.php | BeanLocator.lookup | public function lookup(BeanContextInterface $beanManager, $className, array $args = array())
{
// load the object manager
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $beanManager->getApplication()->search(ObjectManagerInterface::IDENTIFIER);
// load the session ID from the environment
$sessionId = Environment::singleton()->getAttribute(EnvironmentKeys::SESSION_ID);
// query whether or not an object descriptor is available
if ($objectManager->hasObjectDescriptor($className)) {
// load the bean descriptor
$descriptor = $objectManager->getObjectDescriptor($className);
// query whether we've a SFSB
if ($descriptor instanceof StatefulSessionBeanDescriptorInterface) {
// try to load the stateful session bean from the bean manager
if ($instance = $beanManager->lookupStatefulSessionBean($sessionId, $className)) {
// load the object manager and re-inject the dependencies
/** @var \AppserverIo\Psr\Di\ProviderInterface $provider */
$provider = $beanManager->getApplication()->search(ProviderInterface::IDENTIFIER);
$provider->injectDependencies($descriptor, $instance);
// we've to check for post-detach callbacks
foreach ($descriptor->getPostDetachCallbacks() as $postDetachCallback) {
$instance->$postDetachCallback();
}
// return the instance
return $instance;
}
// if not create a new instance and return it
$instance = $beanManager->get($className);
// we've to check for post-construct callbacks
foreach ($descriptor->getPostConstructCallbacks() as $postConstructCallback) {
$instance->$postConstructCallback();
}
// return the instance
return $instance;
}
// query whether we've a SSB
if ($descriptor instanceof SingletonSessionBeanDescriptorInterface) {
// try to load the singleton session bean from the bean manager
if ($instance = $beanManager->lookupSingletonSessionBean($className)) {
// load the object manager and re-inject the dependencies
/** @var \AppserverIo\Psr\Di\ProviderInterface $provider */
$provider = $beanManager->getApplication()->search(ProviderInterface::IDENTIFIER);
$provider->injectDependencies($descriptor, $instance);
// we've to check for post-detach callbacks
foreach ($descriptor->getPostDetachCallbacks() as $postDetachCallback) {
$instance->$postDetachCallback();
}
// return the instance
return $instance;
}
// singleton session beans MUST extends \Stackable
if (is_subclass_of($descriptor->getClassName(), '\Stackable') === false) {
throw new EnterpriseBeansException(sprintf('Singleton session bean %s MUST extend \Stackable', $descriptor->getClassName()));
}
// if not create a new instance and return it
$instance = $beanManager->newSingletonSessionBeanInstance($className);
// add the singleton session bean to the container
$beanManager->getSingletonSessionBeans()->set($className, $instance);
// we've to check for post-construct callback
foreach ($descriptor->getPostConstructCallbacks() as $postConstructCallback) {
$instance->$postConstructCallback();
}
// return the instance
return $instance;
}
// query whether we've a SLSB
if ($descriptor instanceof StatelessSessionBeanDescriptorInterface) {
// if not create a new instance and return it
$instance = $beanManager->get($className);
// we've to check for post-construct callback
foreach ($descriptor->getPostConstructCallbacks() as $postConstructCallback) {
$instance->$postConstructCallback();
}
// return the instance
return $instance;
}
// query whether we've a MDB
if ($descriptor instanceof MessageDrivenBeanDescriptorInterface) {
// create a new instance and return it
return $beanManager->get($className);
}
// query whether we simply have a bean
if ($descriptor instanceof BeanDescriptorInterface) {
// create the bean instance without the factory
return $beanManager->get($className);
}
}
// finally try to let the container create a new instance of the bean
return $beanManager->newInstance($className);
} | php | public function lookup(BeanContextInterface $beanManager, $className, array $args = array())
{
// load the object manager
/** @var \AppserverIo\Psr\Di\ObjectManagerInterface $objectManager */
$objectManager = $beanManager->getApplication()->search(ObjectManagerInterface::IDENTIFIER);
// load the session ID from the environment
$sessionId = Environment::singleton()->getAttribute(EnvironmentKeys::SESSION_ID);
// query whether or not an object descriptor is available
if ($objectManager->hasObjectDescriptor($className)) {
// load the bean descriptor
$descriptor = $objectManager->getObjectDescriptor($className);
// query whether we've a SFSB
if ($descriptor instanceof StatefulSessionBeanDescriptorInterface) {
// try to load the stateful session bean from the bean manager
if ($instance = $beanManager->lookupStatefulSessionBean($sessionId, $className)) {
// load the object manager and re-inject the dependencies
/** @var \AppserverIo\Psr\Di\ProviderInterface $provider */
$provider = $beanManager->getApplication()->search(ProviderInterface::IDENTIFIER);
$provider->injectDependencies($descriptor, $instance);
// we've to check for post-detach callbacks
foreach ($descriptor->getPostDetachCallbacks() as $postDetachCallback) {
$instance->$postDetachCallback();
}
// return the instance
return $instance;
}
// if not create a new instance and return it
$instance = $beanManager->get($className);
// we've to check for post-construct callbacks
foreach ($descriptor->getPostConstructCallbacks() as $postConstructCallback) {
$instance->$postConstructCallback();
}
// return the instance
return $instance;
}
// query whether we've a SSB
if ($descriptor instanceof SingletonSessionBeanDescriptorInterface) {
// try to load the singleton session bean from the bean manager
if ($instance = $beanManager->lookupSingletonSessionBean($className)) {
// load the object manager and re-inject the dependencies
/** @var \AppserverIo\Psr\Di\ProviderInterface $provider */
$provider = $beanManager->getApplication()->search(ProviderInterface::IDENTIFIER);
$provider->injectDependencies($descriptor, $instance);
// we've to check for post-detach callbacks
foreach ($descriptor->getPostDetachCallbacks() as $postDetachCallback) {
$instance->$postDetachCallback();
}
// return the instance
return $instance;
}
// singleton session beans MUST extends \Stackable
if (is_subclass_of($descriptor->getClassName(), '\Stackable') === false) {
throw new EnterpriseBeansException(sprintf('Singleton session bean %s MUST extend \Stackable', $descriptor->getClassName()));
}
// if not create a new instance and return it
$instance = $beanManager->newSingletonSessionBeanInstance($className);
// add the singleton session bean to the container
$beanManager->getSingletonSessionBeans()->set($className, $instance);
// we've to check for post-construct callback
foreach ($descriptor->getPostConstructCallbacks() as $postConstructCallback) {
$instance->$postConstructCallback();
}
// return the instance
return $instance;
}
// query whether we've a SLSB
if ($descriptor instanceof StatelessSessionBeanDescriptorInterface) {
// if not create a new instance and return it
$instance = $beanManager->get($className);
// we've to check for post-construct callback
foreach ($descriptor->getPostConstructCallbacks() as $postConstructCallback) {
$instance->$postConstructCallback();
}
// return the instance
return $instance;
}
// query whether we've a MDB
if ($descriptor instanceof MessageDrivenBeanDescriptorInterface) {
// create a new instance and return it
return $beanManager->get($className);
}
// query whether we simply have a bean
if ($descriptor instanceof BeanDescriptorInterface) {
// create the bean instance without the factory
return $beanManager->get($className);
}
}
// finally try to let the container create a new instance of the bean
return $beanManager->newInstance($className);
} | [
"public",
"function",
"lookup",
"(",
"BeanContextInterface",
"$",
"beanManager",
",",
"$",
"className",
",",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"// load the object manager",
"/** @var \\AppserverIo\\Psr\\Di\\ObjectManagerInterface $objectManager */",
... | Runs a lookup for the session bean with the passed class name
If the passed class name is a session bean an instance
will be returned.
@param \AppserverIo\Psr\EnterpriseBeans\BeanContextInterface $beanManager The bean manager instance
@param string $className The name of the session bean's class
@param array $args The arguments passed to the session beans constructor
@return object The requested session bean | [
"Runs",
"a",
"lookup",
"for",
"the",
"session",
"bean",
"with",
"the",
"passed",
"class",
"name"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/BeanLocator.php#L60-L172 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Listeners/UnloadLoggersListener.php | UnloadLoggersListener.handle | public function handle(EventInterface $event)
{
try {
// load the application server instance
/** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
$applicationServer = $this->getApplicationServer();
// unbind the loggers from the naming directory
foreach (array_keys($applicationServer->getLoggers()) as $name) {
$applicationServer->getNamingDirectory()->unbind(sprintf('php:global/log/%s', $name));
}
// set the initialized loggers finally
$applicationServer->setLoggers(array());
} catch (\Exception $e) {
error_log($e->__toString());
}
} | php | public function handle(EventInterface $event)
{
try {
// load the application server instance
/** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
$applicationServer = $this->getApplicationServer();
// unbind the loggers from the naming directory
foreach (array_keys($applicationServer->getLoggers()) as $name) {
$applicationServer->getNamingDirectory()->unbind(sprintf('php:global/log/%s', $name));
}
// set the initialized loggers finally
$applicationServer->setLoggers(array());
} catch (\Exception $e) {
error_log($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/UnloadLoggersListener.php#L45-L64 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/ServiceFactory.php | ServiceFactory.get | public function get($serviceType, $refInstance = null)
{
if (!isset($this->services[$serviceType::getName()])) {
if (is_null($refInstance)) {
$this->services[$serviceType::getName()] = new $serviceType();
} else {
$this->services[$serviceType::getName()] = new $serviceType($refInstance);
}
}
return $this->services[$serviceType::getName()];
} | php | public function get($serviceType, $refInstance = null)
{
if (!isset($this->services[$serviceType::getName()])) {
if (is_null($refInstance)) {
$this->services[$serviceType::getName()] = new $serviceType();
} else {
$this->services[$serviceType::getName()] = new $serviceType($refInstance);
}
}
return $this->services[$serviceType::getName()];
} | [
"public",
"function",
"get",
"(",
"$",
"serviceType",
",",
"$",
"refInstance",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"services",
"[",
"$",
"serviceType",
"::",
"getName",
"(",
")",
"]",
")",
")",
"{",
"if",
"(",
... | Returns or creates the given service type instance with optional
refInstance injection on ctor
@param string $serviceType The service classname to instantiate
@param string $refInstance The optional refInstance class to inject on ctor
@return object The requested service
@Synchronized | [
"Returns",
"or",
"creates",
"the",
"given",
"service",
"type",
"instance",
"with",
"optional",
"refInstance",
"injection",
"on",
"ctor"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/ServiceFactory.php#L52-L62 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/AbstractFileOperationService.php | AbstractFileOperationService.setUserRight | public function setUserRight(\SplFileInfo $fileInfo, $user = null, $group = null)
{
// Get our system configuration as it contains the user and group to set
$systemConfiguration = $this->getInitialContext()->getSystemConfiguration();
// Check for the existence of a user
if ($user == null) {
$user = $systemConfiguration->getParam('user');
}
// Check for the existence of a group
if ($group == null) {
$group = $systemConfiguration->getParam('group');
}
// change the owner for the passed file/directory
FileSystem::chown($fileInfo, $user, $group);
} | php | public function setUserRight(\SplFileInfo $fileInfo, $user = null, $group = null)
{
// Get our system configuration as it contains the user and group to set
$systemConfiguration = $this->getInitialContext()->getSystemConfiguration();
// Check for the existence of a user
if ($user == null) {
$user = $systemConfiguration->getParam('user');
}
// Check for the existence of a group
if ($group == null) {
$group = $systemConfiguration->getParam('group');
}
// change the owner for the passed file/directory
FileSystem::chown($fileInfo, $user, $group);
} | [
"public",
"function",
"setUserRight",
"(",
"\\",
"SplFileInfo",
"$",
"fileInfo",
",",
"$",
"user",
"=",
"null",
",",
"$",
"group",
"=",
"null",
")",
"{",
"// Get our system configuration as it contains the user and group to set",
"$",
"systemConfiguration",
"=",
"$",
... | Sets the configured user/group settings on the passed file.
@param \SplFileInfo $fileInfo The file to set user/group for
@param string $user The user that has to own the passed file
@param string $group The group that has to own the passed file
@return void | [
"Sets",
"the",
"configured",
"user",
"/",
"group",
"settings",
"on",
"the",
"passed",
"file",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/AbstractFileOperationService.php#L51-L70 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/AbstractFileOperationService.php | AbstractFileOperationService.setUserRights | public function setUserRights(\SplFileInfo $targetDir, $user = null, $group = null)
{
// Get our system configuration as it contains the user and group to set
$systemConfiguration = $this->getInitialContext()->getSystemConfiguration();
// check for the existence of a user
if ($user == null) {
$user = $systemConfiguration->getParam('user');
}
// check for the existence of a group
if ($group == null) {
$group = $systemConfiguration->getParam('group');
}
// change the owner for the passed directory
FileSystem::recursiveChown($targetDir, $user, $group);
} | php | public function setUserRights(\SplFileInfo $targetDir, $user = null, $group = null)
{
// Get our system configuration as it contains the user and group to set
$systemConfiguration = $this->getInitialContext()->getSystemConfiguration();
// check for the existence of a user
if ($user == null) {
$user = $systemConfiguration->getParam('user');
}
// check for the existence of a group
if ($group == null) {
$group = $systemConfiguration->getParam('group');
}
// change the owner for the passed directory
FileSystem::recursiveChown($targetDir, $user, $group);
} | [
"public",
"function",
"setUserRights",
"(",
"\\",
"SplFileInfo",
"$",
"targetDir",
",",
"$",
"user",
"=",
"null",
",",
"$",
"group",
"=",
"null",
")",
"{",
"// Get our system configuration as it contains the user and group to set",
"$",
"systemConfiguration",
"=",
"$"... | Will set the owner and group on the passed directory recursively.
@param \SplFileInfo $targetDir The directory to set the rights for
@param string $user The user that has to own the passed directory
@param string $group The group that has to own the passed directory
@return void | [
"Will",
"set",
"the",
"owner",
"and",
"group",
"on",
"the",
"passed",
"directory",
"recursively",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/AbstractFileOperationService.php#L81-L99 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/AbstractFileOperationService.php | AbstractFileOperationService.initUmask | public function initUmask($umask = null)
{
// check if a umask has been passed
if ($umask == null) {
$umask = $this->getInitialContext()->getSystemConfiguration()->getParam('umask');
}
// initialize the umask
FileSystem::initUmask($umask);
} | php | public function initUmask($umask = null)
{
// check if a umask has been passed
if ($umask == null) {
$umask = $this->getInitialContext()->getSystemConfiguration()->getParam('umask');
}
// initialize the umask
FileSystem::initUmask($umask);
} | [
"public",
"function",
"initUmask",
"(",
"$",
"umask",
"=",
"null",
")",
"{",
"// check if a umask has been passed",
"if",
"(",
"$",
"umask",
"==",
"null",
")",
"{",
"$",
"umask",
"=",
"$",
"this",
"->",
"getInitialContext",
"(",
")",
"->",
"getSystemConfigur... | Init the umask to use creating files/directories, either with
the passed value or the one found in the configuration.
@param integer $umask The new umask to set
@return void
@throws \Exception Is thrown if the umask can not be set | [
"Init",
"the",
"umask",
"to",
"use",
"creating",
"files",
"/",
"directories",
"either",
"with",
"the",
"passed",
"value",
"or",
"the",
"one",
"found",
"in",
"the",
"configuration",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/AbstractFileOperationService.php#L110-L120 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/AbstractFileOperationService.php | AbstractFileOperationService.createDirectory | public function createDirectory(\SplFileInfo $directoryToCreate, $mode = 0775, $recursively = true, $user = null, $group = null, $umask = null)
{
// set the umask that is necessary to create the directory
$this->initUmask($umask);
// create the directory itself
FileSystem::createDirectory($directoryToCreate, $mode, $recursively);
// load the deployment service
$this->setUserRights($directoryToCreate, $user, $group);
} | php | public function createDirectory(\SplFileInfo $directoryToCreate, $mode = 0775, $recursively = true, $user = null, $group = null, $umask = null)
{
// set the umask that is necessary to create the directory
$this->initUmask($umask);
// create the directory itself
FileSystem::createDirectory($directoryToCreate, $mode, $recursively);
// load the deployment service
$this->setUserRights($directoryToCreate, $user, $group);
} | [
"public",
"function",
"createDirectory",
"(",
"\\",
"SplFileInfo",
"$",
"directoryToCreate",
",",
"$",
"mode",
"=",
"0775",
",",
"$",
"recursively",
"=",
"true",
",",
"$",
"user",
"=",
"null",
",",
"$",
"group",
"=",
"null",
",",
"$",
"umask",
"=",
"nu... | Creates the passed directory recursively with the umask specified in the system
configuration and sets the user permissions.
@param \SplFileInfo $directoryToCreate The directory that should be created
@param integer $mode The mode to create the directory with
@param boolean $recursively TRUE if the directory has to be created recursively, else FALSE
@param string $user The user that has to own the passed directory
@param string $group The group that has to own the passed directory
@param integer $umask The new umask to set
@return void
@throws \Exception Is thrown if the directory can't be created | [
"Creates",
"the",
"passed",
"directory",
"recursively",
"with",
"the",
"umask",
"specified",
"in",
"the",
"system",
"configuration",
"and",
"sets",
"the",
"user",
"permissions",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/AbstractFileOperationService.php#L136-L147 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractContainerThread.php | AbstractContainerThread.getServerNodeConfiguration | public function getServerNodeConfiguration(ServerNodeInterface $serverNode)
{
// query whether a server signature (software) has been configured
if ($serverNode->getParam('software') == null) {
$serverNode->setParam('software', ParamNode::TYPE_STRING, $this->getService()->getServerSignature());
}
// add the server node configuration
return new ServerNodeConfiguration($serverNode);
} | php | public function getServerNodeConfiguration(ServerNodeInterface $serverNode)
{
// query whether a server signature (software) has been configured
if ($serverNode->getParam('software') == null) {
$serverNode->setParam('software', ParamNode::TYPE_STRING, $this->getService()->getServerSignature());
}
// add the server node configuration
return new ServerNodeConfiguration($serverNode);
} | [
"public",
"function",
"getServerNodeConfiguration",
"(",
"ServerNodeInterface",
"$",
"serverNode",
")",
"{",
"// query whether a server signature (software) has been configured",
"if",
"(",
"$",
"serverNode",
"->",
"getParam",
"(",
"'software'",
")",
"==",
"null",
")",
"{... | Return's the prepared server node configuration.
@param \AppserverIo\Appserver\Core\Api\Node\ServerNodeInterface $serverNode The server node
@return \AppserverIo\Appserver\Core\ServerNodeConfiguration The server node configuration | [
"Return",
"s",
"the",
"prepared",
"server",
"node",
"configuration",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractContainerThread.php#L115-L125 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractContainerThread.php | AbstractContainerThread.main | public function main()
{
// register the default autoloader
require SERVER_AUTOLOADER;
// initialize the container state
$this->containerState = ContainerStateKeys::get(ContainerStateKeys::WAITING_FOR_INITIALIZATION);
// create a new API app service instance
$this->service = $this->newService('AppserverIo\Appserver\Core\Api\AppService');
// initialize the container for the configured class laoders
$classLoaders = new GenericStackable();
// register the configured class loaders
$this->registerClassLoaders($classLoaders);
// register shutdown handler
register_shutdown_function(array(&$this, "shutdown"));
// query whether the container's directories exists and are readable
$this->validateDirectories();
// initialize the naming directory with the environment data
$this->namingDirectory->createSubdirectory(sprintf('php:env/%s', $this->getName()));
$this->namingDirectory->createSubdirectory(sprintf('php:global/%s', $this->getName()));
$this->namingDirectory->createSubdirectory(sprintf('php:global/log/%s', $this->getName()));
$this->namingDirectory->bind(sprintf('php:env/%s/appBase', $this->getName()), $this->getAppBase());
$this->namingDirectory->bind(sprintf('php:global/%s/runlevel', $this->getName()), $this->getRunlevel());
// initialize the container state
$this->containerState = ContainerStateKeys::get(ContainerStateKeys::INITIALIZATION_SUCCESSFUL);
// initialize instance that contains the applications
$this->applications = new GenericStackable();
// initialize the profile logger and the thread context
if ($profileLogger = $this->getInitialContext()->getLogger(LoggerUtils::PROFILE)) {
$profileLogger->appendThreadContext($this->getContainerNode()->getName());
}
// initialize the array for the server configurations
$serverConfigurations = array();
// load the server configurations and query whether a server signatures has been set
/** @var \AppserverIo\Appserver\Core\Api\Node\ServerNodeInterface $serverNode */
foreach ($this->getContainerNode()->getServers() as $serverNode) {
$serverConfigurations[] = $this->getServerNodeConfiguration($serverNode);
}
// init upstreams
$upstreams = array();
if ($this->getContainerNode()->getUpstreams()) {
$upstreams = $this->getContainerNode()->getUpstreams();
foreach ($this->getContainerNode()->getUpstreams() as $upstreamNode) {
// get upstream type
$upstreamType = $upstreamNode->getType();
// init upstream instance
$upstream = new $upstreamType();
// init upstream servers
$servers = array();
// get upstream servers from upstream
foreach ($upstreamNode->getUpstreamServers() as $upstreamServerNode) {
$upstreamServerType = $upstreamServerNode->getType();
$upstreamServerParams = $upstreamServerNode->getParamsAsArray();
$servers[$upstreamServerNode->getName()] = new $upstreamServerType($upstreamServerParams);
}
// inject server instances to upstream
$upstream->injectServers($servers);
// set upstream by name
$upstreams[$upstreamNode->getName()] = $upstream;
}
}
// init server array
$this->servers = new GenericStackable();
// start servers by given configurations
/** @var \AppserverIo\Server\Interfaces\ServerConfigurationInterface $serverConfig */
foreach ($serverConfigurations as $serverConfig) {
// get type definitions
$serverType = $serverConfig->getType();
$serverContextType = $serverConfig->getServerContextType();
// create a new instance server context
/** @var \AppserverIo\Server\Interfaces\ServerContextInterface $serverContext */
$serverContext = new $serverContextType();
// inject container to be available in specific mods etc. and initialize the module
$serverContext->injectContainer($this);
// init server context by config
$serverContext->init($serverConfig);
// inject upstreams
$serverContext->injectUpstreams($upstreams);
// inject loggers
$serverContext->injectLoggers($this->getInitialContext()->getLoggers());
// create the server (which should start it automatically)
/** @var \AppserverIo\Server\Interfaces\ServerInterface $server */
$server = new $serverType($serverContext);
// collect the servers we started
$this->servers[$serverConfig->getName()] = $server;
}
// wait for all servers to be started
$waitForServers = true;
while ($waitForServers === true) {
// iterate over all servers to check the state
foreach ($this->servers as $server) {
if ($server->serverState === ServerStateKeys::WORKERS_INITIALIZED) {
$waitForServers = false;
} else {
$waitForServers = true;
}
}
usleep(10000);
}
// the container has successfully been initialized
$this->synchronized(function ($self) {
$self->containerState = ContainerStateKeys::get(ContainerStateKeys::SERVERS_STARTED_SUCCESSFUL);
}, $this);
// initialize the flag to keep the application running
$keepRunning = true;
// wait till container will be shutdown
while ($keepRunning) {
// query whether we've a profile logger, log resource usage
if ($profileLogger) {
$profileLogger->debug(sprintf('Container %s still waiting for shutdown', $this->getContainerNode()->getName()));
}
// wait a second to lower system load
$keepRunning = $this->synchronized(function ($self) {
$self->wait(1000000 * AbstractContainerThread::TIME_TO_LIVE);
return $self->containerState->equals(ContainerStateKeys::get(ContainerStateKeys::SERVERS_STARTED_SUCCESSFUL));
}, $this);
}
// we need to stop all servers before we can shutdown the container
/** @var \AppserverIo\Server\Interfaces\ServerInterface $server */
foreach ($this->servers as $server) {
$server->stop();
}
// mark the container as successfully shutdown
$this->synchronized(function ($self) {
$self->containerState = ContainerStateKeys::get(ContainerStateKeys::SHUTDOWN);
}, $this);
// send log message that the container has been shutdown
$this->getInitialContext()->getSystemLogger()->info(
sprintf('Successfully shutdown container %s', $this->getContainerNode()->getName())
);
} | php | public function main()
{
// register the default autoloader
require SERVER_AUTOLOADER;
// initialize the container state
$this->containerState = ContainerStateKeys::get(ContainerStateKeys::WAITING_FOR_INITIALIZATION);
// create a new API app service instance
$this->service = $this->newService('AppserverIo\Appserver\Core\Api\AppService');
// initialize the container for the configured class laoders
$classLoaders = new GenericStackable();
// register the configured class loaders
$this->registerClassLoaders($classLoaders);
// register shutdown handler
register_shutdown_function(array(&$this, "shutdown"));
// query whether the container's directories exists and are readable
$this->validateDirectories();
// initialize the naming directory with the environment data
$this->namingDirectory->createSubdirectory(sprintf('php:env/%s', $this->getName()));
$this->namingDirectory->createSubdirectory(sprintf('php:global/%s', $this->getName()));
$this->namingDirectory->createSubdirectory(sprintf('php:global/log/%s', $this->getName()));
$this->namingDirectory->bind(sprintf('php:env/%s/appBase', $this->getName()), $this->getAppBase());
$this->namingDirectory->bind(sprintf('php:global/%s/runlevel', $this->getName()), $this->getRunlevel());
// initialize the container state
$this->containerState = ContainerStateKeys::get(ContainerStateKeys::INITIALIZATION_SUCCESSFUL);
// initialize instance that contains the applications
$this->applications = new GenericStackable();
// initialize the profile logger and the thread context
if ($profileLogger = $this->getInitialContext()->getLogger(LoggerUtils::PROFILE)) {
$profileLogger->appendThreadContext($this->getContainerNode()->getName());
}
// initialize the array for the server configurations
$serverConfigurations = array();
// load the server configurations and query whether a server signatures has been set
/** @var \AppserverIo\Appserver\Core\Api\Node\ServerNodeInterface $serverNode */
foreach ($this->getContainerNode()->getServers() as $serverNode) {
$serverConfigurations[] = $this->getServerNodeConfiguration($serverNode);
}
// init upstreams
$upstreams = array();
if ($this->getContainerNode()->getUpstreams()) {
$upstreams = $this->getContainerNode()->getUpstreams();
foreach ($this->getContainerNode()->getUpstreams() as $upstreamNode) {
// get upstream type
$upstreamType = $upstreamNode->getType();
// init upstream instance
$upstream = new $upstreamType();
// init upstream servers
$servers = array();
// get upstream servers from upstream
foreach ($upstreamNode->getUpstreamServers() as $upstreamServerNode) {
$upstreamServerType = $upstreamServerNode->getType();
$upstreamServerParams = $upstreamServerNode->getParamsAsArray();
$servers[$upstreamServerNode->getName()] = new $upstreamServerType($upstreamServerParams);
}
// inject server instances to upstream
$upstream->injectServers($servers);
// set upstream by name
$upstreams[$upstreamNode->getName()] = $upstream;
}
}
// init server array
$this->servers = new GenericStackable();
// start servers by given configurations
/** @var \AppserverIo\Server\Interfaces\ServerConfigurationInterface $serverConfig */
foreach ($serverConfigurations as $serverConfig) {
// get type definitions
$serverType = $serverConfig->getType();
$serverContextType = $serverConfig->getServerContextType();
// create a new instance server context
/** @var \AppserverIo\Server\Interfaces\ServerContextInterface $serverContext */
$serverContext = new $serverContextType();
// inject container to be available in specific mods etc. and initialize the module
$serverContext->injectContainer($this);
// init server context by config
$serverContext->init($serverConfig);
// inject upstreams
$serverContext->injectUpstreams($upstreams);
// inject loggers
$serverContext->injectLoggers($this->getInitialContext()->getLoggers());
// create the server (which should start it automatically)
/** @var \AppserverIo\Server\Interfaces\ServerInterface $server */
$server = new $serverType($serverContext);
// collect the servers we started
$this->servers[$serverConfig->getName()] = $server;
}
// wait for all servers to be started
$waitForServers = true;
while ($waitForServers === true) {
// iterate over all servers to check the state
foreach ($this->servers as $server) {
if ($server->serverState === ServerStateKeys::WORKERS_INITIALIZED) {
$waitForServers = false;
} else {
$waitForServers = true;
}
}
usleep(10000);
}
// the container has successfully been initialized
$this->synchronized(function ($self) {
$self->containerState = ContainerStateKeys::get(ContainerStateKeys::SERVERS_STARTED_SUCCESSFUL);
}, $this);
// initialize the flag to keep the application running
$keepRunning = true;
// wait till container will be shutdown
while ($keepRunning) {
// query whether we've a profile logger, log resource usage
if ($profileLogger) {
$profileLogger->debug(sprintf('Container %s still waiting for shutdown', $this->getContainerNode()->getName()));
}
// wait a second to lower system load
$keepRunning = $this->synchronized(function ($self) {
$self->wait(1000000 * AbstractContainerThread::TIME_TO_LIVE);
return $self->containerState->equals(ContainerStateKeys::get(ContainerStateKeys::SERVERS_STARTED_SUCCESSFUL));
}, $this);
}
// we need to stop all servers before we can shutdown the container
/** @var \AppserverIo\Server\Interfaces\ServerInterface $server */
foreach ($this->servers as $server) {
$server->stop();
}
// mark the container as successfully shutdown
$this->synchronized(function ($self) {
$self->containerState = ContainerStateKeys::get(ContainerStateKeys::SHUTDOWN);
}, $this);
// send log message that the container has been shutdown
$this->getInitialContext()->getSystemLogger()->info(
sprintf('Successfully shutdown container %s', $this->getContainerNode()->getName())
);
} | [
"public",
"function",
"main",
"(",
")",
"{",
"// register the default autoloader",
"require",
"SERVER_AUTOLOADER",
";",
"// initialize the container state",
"$",
"this",
"->",
"containerState",
"=",
"ContainerStateKeys",
"::",
"get",
"(",
"ContainerStateKeys",
"::",
"WAIT... | Run the containers logic
@return void | [
"Run",
"the",
"containers",
"logic"
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractContainerThread.php#L132-L291 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractContainerThread.php | AbstractContainerThread.addApplicationToSystemConfiguration | public function addApplicationToSystemConfiguration(ApplicationInterface $application)
{
// try to load the API app service instance
$appNode = $this->getService()->loadByWebappPath($application->getWebappPath());
// check if the application has already been attached to the container
if ($appNode == null) {
$this->getService()->newFromApplication($application);
}
// connect the application to the container
$application->connect();
} | php | public function addApplicationToSystemConfiguration(ApplicationInterface $application)
{
// try to load the API app service instance
$appNode = $this->getService()->loadByWebappPath($application->getWebappPath());
// check if the application has already been attached to the container
if ($appNode == null) {
$this->getService()->newFromApplication($application);
}
// connect the application to the container
$application->connect();
} | [
"public",
"function",
"addApplicationToSystemConfiguration",
"(",
"ApplicationInterface",
"$",
"application",
")",
"{",
"// try to load the API app service instance",
"$",
"appNode",
"=",
"$",
"this",
"->",
"getService",
"(",
")",
"->",
"loadByWebappPath",
"(",
"$",
"ap... | Connects the passed application to the system configuration.
@param \AppserverIo\Psr\Application\ApplicationInterface $application The application to be prepared
@return void | [
"Connects",
"the",
"passed",
"application",
"to",
"the",
"system",
"configuration",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractContainerThread.php#L463-L476 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractContainerThread.php | AbstractContainerThread.addApplication | public function addApplication(ApplicationInterface $application)
{
// register the application in this instance
$this->applications[$application->getName()] = $application;
// adds the application to the system configuration
$this->addApplicationToSystemConfiguration($application);
} | php | public function addApplication(ApplicationInterface $application)
{
// register the application in this instance
$this->applications[$application->getName()] = $application;
// adds the application to the system configuration
$this->addApplicationToSystemConfiguration($application);
} | [
"public",
"function",
"addApplication",
"(",
"ApplicationInterface",
"$",
"application",
")",
"{",
"// register the application in this instance",
"$",
"this",
"->",
"applications",
"[",
"$",
"application",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"application",
";... | Append the deployed application to the deployment instance
and registers it in the system configuration.
@param \AppserverIo\Psr\Application\ApplicationInterface $application The application to append
@return void | [
"Append",
"the",
"deployed",
"application",
"to",
"the",
"deployment",
"instance",
"and",
"registers",
"it",
"in",
"the",
"system",
"configuration",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractContainerThread.php#L486-L494 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractContainerThread.php | AbstractContainerThread.stop | public function stop()
{
// start container shutdown
$this->synchronized(function ($self) {
$self->containerState = ContainerStateKeys::get(ContainerStateKeys::HALT);
}, $this);
do {
// wait for 0.5 seconds
usleep(500000);
// log a message that we'll wait till application has been shutdown
$this->getInitialContext()->getSystemLogger()->info(
sprintf('Wait for container %s to be shutdown', $this->getContainerNode()->getName())
);
// query whether application state key is SHUTDOWN or not
$waitForShutdown = $this->synchronized(function ($self) {
return $self->containerState->notEquals(ContainerStateKeys::get(ContainerStateKeys::SHUTDOWN));
}, $this);
} while ($waitForShutdown);
} | php | public function stop()
{
// start container shutdown
$this->synchronized(function ($self) {
$self->containerState = ContainerStateKeys::get(ContainerStateKeys::HALT);
}, $this);
do {
// wait for 0.5 seconds
usleep(500000);
// log a message that we'll wait till application has been shutdown
$this->getInitialContext()->getSystemLogger()->info(
sprintf('Wait for container %s to be shutdown', $this->getContainerNode()->getName())
);
// query whether application state key is SHUTDOWN or not
$waitForShutdown = $this->synchronized(function ($self) {
return $self->containerState->notEquals(ContainerStateKeys::get(ContainerStateKeys::SHUTDOWN));
}, $this);
} while ($waitForShutdown);
} | [
"public",
"function",
"stop",
"(",
")",
"{",
"// start container shutdown",
"$",
"this",
"->",
"synchronized",
"(",
"function",
"(",
"$",
"self",
")",
"{",
"$",
"self",
"->",
"containerState",
"=",
"ContainerStateKeys",
"::",
"get",
"(",
"ContainerStateKeys",
... | Stops the container instance.
@return void | [
"Stops",
"the",
"container",
"instance",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractContainerThread.php#L501-L524 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractContainerThread.php | AbstractContainerThread.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->getInitialContext()->getSystemLogger()->critical($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->getInitialContext()->getSystemLogger()->critical($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/Core/AbstractContainerThread.php#L552-L566 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractContainerThread.php | AbstractContainerThread.validateDirectories | protected function validateDirectories()
{
// query whether the container's application directory is available and readable
$appBase = $this->getAppBase();
if (!is_dir($appBase) || !is_readable($appBase)) {
$this->getInitialContext()->getSystemLogger()->critical(
sprintf(
'Base directory (appBase) %s of container %s is no directory or not readable, can\'t deploy applications',
$appBase,
$this->getName()
)
);
}
// query whether the container's temporary directory is available and readable
$tmpDir = $this->getTmpDir();
if (!is_dir($tmpDir) || !is_readable($tmpDir)) {
$this->getInitialContext()->getSystemLogger()->critical(
sprintf(
'Temporary directory (tmpDir) %s of container %s is no directory or not readable!',
$tmpDir,
$this->getName()
)
);
}
} | php | protected function validateDirectories()
{
// query whether the container's application directory is available and readable
$appBase = $this->getAppBase();
if (!is_dir($appBase) || !is_readable($appBase)) {
$this->getInitialContext()->getSystemLogger()->critical(
sprintf(
'Base directory (appBase) %s of container %s is no directory or not readable, can\'t deploy applications',
$appBase,
$this->getName()
)
);
}
// query whether the container's temporary directory is available and readable
$tmpDir = $this->getTmpDir();
if (!is_dir($tmpDir) || !is_readable($tmpDir)) {
$this->getInitialContext()->getSystemLogger()->critical(
sprintf(
'Temporary directory (tmpDir) %s of container %s is no directory or not readable!',
$tmpDir,
$this->getName()
)
);
}
} | [
"protected",
"function",
"validateDirectories",
"(",
")",
"{",
"// query whether the container's application directory is available and readable",
"$",
"appBase",
"=",
"$",
"this",
"->",
"getAppBase",
"(",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"appBase",
")",
... | Validates that the container's application and temporary directory is available.
@return void | [
"Validates",
"that",
"the",
"container",
"s",
"application",
"and",
"temporary",
"directory",
"is",
"available",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractContainerThread.php#L573-L599 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/AbstractContainerThread.php | AbstractContainerThread.registerClassLoaders | protected function registerClassLoaders(GenericStackable $classLoaders)
{
// intialize the additional container class loaders
foreach ($this->getContainerNode()->getClassLoaders() as $classLoaderNode) {
// initialize the storage for the include path
$includePath = array();
// load the application base directory
$appBase = $this->getAppBase();
// load the composer class loader for the configured directories
foreach ($classLoaderNode->getDirectories() as $directory) {
// we prepare the directories to include scripts AFTER registering (in application context)
$includePath[] = $appBase . $directory->getNodeValue();
}
// load the class loader type
$className = $classLoaderNode->getType();
// initialize and register the class loader instance
$classLoaders[$classLoaderNode->getName()] = new $className(new GenericStackable(), $includePath);
$classLoaders[$classLoaderNode->getName()]->register(true, true);
}
} | php | protected function registerClassLoaders(GenericStackable $classLoaders)
{
// intialize the additional container class loaders
foreach ($this->getContainerNode()->getClassLoaders() as $classLoaderNode) {
// initialize the storage for the include path
$includePath = array();
// load the application base directory
$appBase = $this->getAppBase();
// load the composer class loader for the configured directories
foreach ($classLoaderNode->getDirectories() as $directory) {
// we prepare the directories to include scripts AFTER registering (in application context)
$includePath[] = $appBase . $directory->getNodeValue();
}
// load the class loader type
$className = $classLoaderNode->getType();
// initialize and register the class loader instance
$classLoaders[$classLoaderNode->getName()] = new $className(new GenericStackable(), $includePath);
$classLoaders[$classLoaderNode->getName()]->register(true, true);
}
} | [
"protected",
"function",
"registerClassLoaders",
"(",
"GenericStackable",
"$",
"classLoaders",
")",
"{",
"// intialize the additional container class loaders",
"foreach",
"(",
"$",
"this",
"->",
"getContainerNode",
"(",
")",
"->",
"getClassLoaders",
"(",
")",
"as",
"$",... | Register's the class loaders configured for this container.
@param \AppserverIo\Storage\GenericStackable $classLoaders The container for the class loader instances
@return void | [
"Register",
"s",
"the",
"class",
"loaders",
"configured",
"for",
"this",
"container",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/AbstractContainerThread.php#L608-L632 |
appserver-io/appserver | src/AppserverIo/Appserver/Provisioning/Steps/CreateDatabaseStep.php | CreateDatabaseStep.execute | public function execute()
{
try {
// load the class definitions
$classes = $this->getEntityManager()->getMetadataFactory()->getAllMetadata();
// create a new database instance
$this->getSchemaTool()->createSchema($classes);
} catch (\Exception $e) {
$this->getApplication()->getInitialContext()->getSystemLogger()->error($e->__toString());
}
} | php | public function execute()
{
try {
// load the class definitions
$classes = $this->getEntityManager()->getMetadataFactory()->getAllMetadata();
// create a new database instance
$this->getSchemaTool()->createSchema($classes);
} catch (\Exception $e) {
$this->getApplication()->getInitialContext()->getSystemLogger()->error($e->__toString());
}
} | [
"public",
"function",
"execute",
"(",
")",
"{",
"try",
"{",
"// load the class definitions",
"$",
"classes",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"getMetadataFactory",
"(",
")",
"->",
"getAllMetadata",
"(",
")",
";",
"// create a new datab... | Executes the functionality for this step, in this case the execution of
the PHP script defined in the step configuration.
@return void
@throws \Exception Is thrown if the script can't be executed
@see \AppserverIo\Provisioning\Steps\StepInterface::execute() | [
"Executes",
"the",
"functionality",
"for",
"this",
"step",
"in",
"this",
"case",
"the",
"execution",
"of",
"the",
"PHP",
"script",
"defined",
"in",
"the",
"step",
"configuration",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Provisioning/Steps/CreateDatabaseStep.php#L43-L56 |
appserver-io/appserver | src/AppserverIo/Appserver/Application/StandardManagerSettings.php | StandardManagerSettings.mergeWithParams | public function mergeWithParams(array $params)
{
// merge the passed properties with the default settings for the stateful session beans
foreach (array_keys(get_object_vars($this)) as $propertyName) {
if (array_key_exists($propertyName, $params)) {
$this->$propertyName = $params[$propertyName];
}
}
} | php | public function mergeWithParams(array $params)
{
// merge the passed properties with the default settings for the stateful session beans
foreach (array_keys(get_object_vars($this)) as $propertyName) {
if (array_key_exists($propertyName, $params)) {
$this->$propertyName = $params[$propertyName];
}
}
} | [
"public",
"function",
"mergeWithParams",
"(",
"array",
"$",
"params",
")",
"{",
"// merge the passed properties with the default settings for the stateful session beans",
"foreach",
"(",
"array_keys",
"(",
"get_object_vars",
"(",
"$",
"this",
")",
")",
"as",
"$",
"propert... | Merge the passed params with the default settings.
@param array $params The associative array with the params to merge
@return void | [
"Merge",
"the",
"passed",
"params",
"with",
"the",
"default",
"settings",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Application/StandardManagerSettings.php#L76-L84 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/Node/ManagerNode.php | ManagerNode.merge | public function merge(ManagerNodeInterface $managerNode)
{
// make sure, we only merge nodes with the same name
if (strcasecmp($this->getName(), $managerNode->getName()) !== 0) {
return;
}
// override type and factory attributes
$this->type = $managerNode->getType();
$this->factory = $managerNode->getFactory();
$this->contextFactory = $managerNode->getContextFactory();
$this->objectDescription = $managerNode->getObjectDescription();
// load the authenticators of this manager node
$localAuthenticators = $this->getAuthenticators();
// iterate over the authenticator nodes of the passed manager node and merge them
foreach ($managerNode->getAuthenticators() as $authenticatorNode) {
$isMerged = false;
foreach ($localAuthenticators as $key => $localAuthenticator) {
if (strcasecmp($localAuthenticator->getName(), $authenticatorNode->getName()) === 0) {
$localAuthenticators[$key] = $authenticatorNode;
$isMerged = true;
}
}
if ($isMerged === false) {
$localAuthenticators[$authenticatorNode->getUuid()] = $authenticatorNode;
}
}
// override the authenticators with the merged mones
$this->authenticators = $localAuthenticators;
// override the params if available
if (sizeof($params = $managerNode->getParams()) > 0) {
$this->params = $params;
}
// override the security domains if available
if (sizeof($securityDomains = $managerNode->getSecurityDomains()) > 0) {
$this->securityDomains = $securityDomains;
}
} | php | public function merge(ManagerNodeInterface $managerNode)
{
// make sure, we only merge nodes with the same name
if (strcasecmp($this->getName(), $managerNode->getName()) !== 0) {
return;
}
// override type and factory attributes
$this->type = $managerNode->getType();
$this->factory = $managerNode->getFactory();
$this->contextFactory = $managerNode->getContextFactory();
$this->objectDescription = $managerNode->getObjectDescription();
// load the authenticators of this manager node
$localAuthenticators = $this->getAuthenticators();
// iterate over the authenticator nodes of the passed manager node and merge them
foreach ($managerNode->getAuthenticators() as $authenticatorNode) {
$isMerged = false;
foreach ($localAuthenticators as $key => $localAuthenticator) {
if (strcasecmp($localAuthenticator->getName(), $authenticatorNode->getName()) === 0) {
$localAuthenticators[$key] = $authenticatorNode;
$isMerged = true;
}
}
if ($isMerged === false) {
$localAuthenticators[$authenticatorNode->getUuid()] = $authenticatorNode;
}
}
// override the authenticators with the merged mones
$this->authenticators = $localAuthenticators;
// override the params if available
if (sizeof($params = $managerNode->getParams()) > 0) {
$this->params = $params;
}
// override the security domains if available
if (sizeof($securityDomains = $managerNode->getSecurityDomains()) > 0) {
$this->securityDomains = $securityDomains;
}
} | [
"public",
"function",
"merge",
"(",
"ManagerNodeInterface",
"$",
"managerNode",
")",
"{",
"// make sure, we only merge nodes with the same name",
"if",
"(",
"strcasecmp",
"(",
"$",
"this",
"->",
"getName",
"(",
")",
",",
"$",
"managerNode",
"->",
"getName",
"(",
"... | This method merges the configuration of the passed manager node
into this one.
@param \AppserverIo\Appserver\Core\Api\Node\ManagerNodeInterface $managerNode The node with the manager configuration we want to merge
@return void | [
"This",
"method",
"merges",
"the",
"configuration",
"of",
"the",
"passed",
"manager",
"node",
"into",
"this",
"one",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/ManagerNode.php#L183-L226 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/DeploymentService.php | DeploymentService.findAll | public function findAll()
{
$deploymentNodes = array();
foreach ($this->getSystemConfiguration()->getContainers() as $container) {
$deploymentNode = $container->getDeployment();
$deploymentNodes[$deploymentNode->getUuid()] = $deploymentNode;
}
return $deploymentNodes;
} | php | public function findAll()
{
$deploymentNodes = array();
foreach ($this->getSystemConfiguration()->getContainers() as $container) {
$deploymentNode = $container->getDeployment();
$deploymentNodes[$deploymentNode->getUuid()] = $deploymentNode;
}
return $deploymentNodes;
} | [
"public",
"function",
"findAll",
"(",
")",
"{",
"$",
"deploymentNodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getSystemConfiguration",
"(",
")",
"->",
"getContainers",
"(",
")",
"as",
"$",
"container",
")",
"{",
"$",
"deploymen... | Returns all deployment configurations.
@return array An array with all deployment configurations
@see \AppserverIo\Psr\ApplicationServer\ServiceInterface::findAll() | [
"Returns",
"all",
"deployment",
"configurations",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DeploymentService.php#L51-L59 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/DeploymentService.php | DeploymentService.load | public function load($uuid)
{
$deploymentNodes = $this->findAll();
if (array_key_exists($uuid, $deploymentNodes)) {
return $deploymentNodes[$uuid];
}
} | php | public function load($uuid)
{
$deploymentNodes = $this->findAll();
if (array_key_exists($uuid, $deploymentNodes)) {
return $deploymentNodes[$uuid];
}
} | [
"public",
"function",
"load",
"(",
"$",
"uuid",
")",
"{",
"$",
"deploymentNodes",
"=",
"$",
"this",
"->",
"findAll",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"uuid",
",",
"$",
"deploymentNodes",
")",
")",
"{",
"return",
"$",
"deploymentN... | Returns the deployment with the passed UUID.
@param integer $uuid UUID of the deployment to return
@return \AppserverIo\Appserver\Core\Api\Node\\DeploymentNode The deployment with the UUID passed as parameter
@see \AppserverIo\Psr\ApplicationServer\ServiceInterface::load() | [
"Returns",
"the",
"deployment",
"with",
"the",
"passed",
"UUID",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DeploymentService.php#L69-L75 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/DeploymentService.php | DeploymentService.loadContextInstance | public function loadContextInstance(ContainerConfigurationInterface $containerNode, $webappPath)
{
// prepare the context path
$contextPath = basename($webappPath);
// load the system properties
$properties = $this->getSystemProperties($containerNode);
// append the application specific properties
$properties->add(SystemPropertyKeys::WEBAPP, $webappPath);
$properties->add(SystemPropertyKeys::WEBAPP_NAME, $contextPath);
// validate the base context file
/** @var \AppserverIo\Appserver\Core\Api\ConfigurationService $configurationService */
$configurationService = $this->newService('AppserverIo\Appserver\Core\Api\ConfigurationService');
$configurationService->validateFile($baseContextPath = $this->getConfdDir('context.xml'), null);
//load it as default if validation succeeds
$context = new ContextNode();
$context->initFromFile($baseContextPath);
$context->replaceProperties($properties);
// set the context webapp path
$context->setWebappPath($webappPath);
// try to load a context configuration (from appserver.xml) for the context path
if ($contextToMerge = $containerNode->getHost()->getContext($contextPath)) {
$contextToMerge->replaceProperties($properties);
$context->merge($contextToMerge);
}
// iterate through all context configurations (context.xml), validate and merge them
foreach ($this->globDir(AppEnvironmentHelper::getEnvironmentAwareGlobPattern($webappPath, 'META-INF/context')) as $contextFile) {
try {
// validate the application specific context
$configurationService->validateFile($contextFile, null);
// create a new context node instance and replace the properties
$contextInstance = new ContextNode();
$contextInstance->initFromFile($contextFile);
$contextInstance->replaceProperties($properties);
// merge it into the default configuration
$context->merge($contextInstance);
} catch (ConfigurationException $ce) {
// load the logger and log the XML validation errors
$systemLogger = $this->getInitialContext()->getSystemLogger();
$systemLogger->error($ce->__toString());
// additionally log a message that DS will be missing
$systemLogger->critical(
sprintf('Will skip app specific context file %s, configuration might be faulty.', $contextFile)
);
}
}
// set the real context name
$context->setName($contextPath);
$context->setEnvironmentName(AppEnvironmentHelper::getEnvironmentModifier($webappPath));
// return the initialized context instance
return $context;
} | php | public function loadContextInstance(ContainerConfigurationInterface $containerNode, $webappPath)
{
// prepare the context path
$contextPath = basename($webappPath);
// load the system properties
$properties = $this->getSystemProperties($containerNode);
// append the application specific properties
$properties->add(SystemPropertyKeys::WEBAPP, $webappPath);
$properties->add(SystemPropertyKeys::WEBAPP_NAME, $contextPath);
// validate the base context file
/** @var \AppserverIo\Appserver\Core\Api\ConfigurationService $configurationService */
$configurationService = $this->newService('AppserverIo\Appserver\Core\Api\ConfigurationService');
$configurationService->validateFile($baseContextPath = $this->getConfdDir('context.xml'), null);
//load it as default if validation succeeds
$context = new ContextNode();
$context->initFromFile($baseContextPath);
$context->replaceProperties($properties);
// set the context webapp path
$context->setWebappPath($webappPath);
// try to load a context configuration (from appserver.xml) for the context path
if ($contextToMerge = $containerNode->getHost()->getContext($contextPath)) {
$contextToMerge->replaceProperties($properties);
$context->merge($contextToMerge);
}
// iterate through all context configurations (context.xml), validate and merge them
foreach ($this->globDir(AppEnvironmentHelper::getEnvironmentAwareGlobPattern($webappPath, 'META-INF/context')) as $contextFile) {
try {
// validate the application specific context
$configurationService->validateFile($contextFile, null);
// create a new context node instance and replace the properties
$contextInstance = new ContextNode();
$contextInstance->initFromFile($contextFile);
$contextInstance->replaceProperties($properties);
// merge it into the default configuration
$context->merge($contextInstance);
} catch (ConfigurationException $ce) {
// load the logger and log the XML validation errors
$systemLogger = $this->getInitialContext()->getSystemLogger();
$systemLogger->error($ce->__toString());
// additionally log a message that DS will be missing
$systemLogger->critical(
sprintf('Will skip app specific context file %s, configuration might be faulty.', $contextFile)
);
}
}
// set the real context name
$context->setName($contextPath);
$context->setEnvironmentName(AppEnvironmentHelper::getEnvironmentModifier($webappPath));
// return the initialized context instance
return $context;
} | [
"public",
"function",
"loadContextInstance",
"(",
"ContainerConfigurationInterface",
"$",
"containerNode",
",",
"$",
"webappPath",
")",
"{",
"// prepare the context path",
"$",
"contextPath",
"=",
"basename",
"(",
"$",
"webappPath",
")",
";",
"// load the system propertie... | Initializes the context instance for the passed webapp path.
@param \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode The container to load the context for
@param string $webappPath The path to the web application
@return \AppserverIo\Appserver\Core\Api\Node\ContextNode The initialized context instance | [
"Initializes",
"the",
"context",
"instance",
"for",
"the",
"passed",
"webapp",
"path",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DeploymentService.php#L85-L149 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/DeploymentService.php | DeploymentService.loadContextInstancesByContainer | public function loadContextInstancesByContainer(ContainerInterface $container)
{
// initialize the array for the context instances
$contextInstances = array();
// iterate over all applications and create the context configuration
foreach (glob($container->getAppBase() . '/*', GLOB_ONLYDIR) as $webappPath) {
$context = $this->loadContextInstance($container->getContainerNode(), $webappPath);
$contextInstances[$context->getName()] = $context;
}
// return the array with the context instances
return $contextInstances;
} | php | public function loadContextInstancesByContainer(ContainerInterface $container)
{
// initialize the array for the context instances
$contextInstances = array();
// iterate over all applications and create the context configuration
foreach (glob($container->getAppBase() . '/*', GLOB_ONLYDIR) as $webappPath) {
$context = $this->loadContextInstance($container->getContainerNode(), $webappPath);
$contextInstances[$context->getName()] = $context;
}
// return the array with the context instances
return $contextInstances;
} | [
"public",
"function",
"loadContextInstancesByContainer",
"(",
"ContainerInterface",
"$",
"container",
")",
"{",
"// initialize the array for the context instances",
"$",
"contextInstances",
"=",
"array",
"(",
")",
";",
"// iterate over all applications and create the context config... | Initializes the available application contexts and returns them.
@param \AppserverIo\Psr\ApplicationServer\ContainerInterface $container The container we want to add the applications to
@return ContextNode[] The array with the application contexts | [
"Initializes",
"the",
"available",
"application",
"contexts",
"and",
"returns",
"them",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DeploymentService.php#L158-L172 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/DeploymentService.php | DeploymentService.prepareSystemProperties | protected function prepareSystemProperties(PropertiesInterface $properties, $webappPath)
{
// append the application specific properties and replace the properties
$properties->add(SystemPropertyKeys::WEBAPP, $webappPath);
$properties->add(SystemPropertyKeys::WEBAPP_NAME, basename($webappPath));
} | php | protected function prepareSystemProperties(PropertiesInterface $properties, $webappPath)
{
// append the application specific properties and replace the properties
$properties->add(SystemPropertyKeys::WEBAPP, $webappPath);
$properties->add(SystemPropertyKeys::WEBAPP_NAME, basename($webappPath));
} | [
"protected",
"function",
"prepareSystemProperties",
"(",
"PropertiesInterface",
"$",
"properties",
",",
"$",
"webappPath",
")",
"{",
"// append the application specific properties and replace the properties",
"$",
"properties",
"->",
"add",
"(",
"SystemPropertyKeys",
"::",
"W... | Prepares the system properties for the actual mode.
@param \AppserverIo\Properties\PropertiesInterface $properties The properties to prepare
@param string $webappPath The path of the web application to prepare the properties with
@return void | [
"Prepares",
"the",
"system",
"properties",
"for",
"the",
"actual",
"mode",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DeploymentService.php#L182-L187 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/DeploymentService.php | DeploymentService.loadContainerInstance | public function loadContainerInstance(
ContainerConfigurationInterface $containerNode,
SystemConfigurationInterface $systemConfiguration,
$webappPath
) {
// load the service to validate the files
/** @var \AppserverIo\Appserver\Core\Api\ConfigurationService $configurationService */
$configurationService = $this->newService('AppserverIo\Appserver\Core\Api\ConfigurationService');
// iterate through all server configurations (servers.xml), validate and merge them
foreach ($this->globDir(AppEnvironmentHelper::getEnvironmentAwareGlobPattern($webappPath, 'META-INF/containers')) as $containersConfigurationFile) {
try {
// validate the application specific container configurations
$configurationService->validateFile($containersConfigurationFile, null);
// create a new containers node instance
$containersNodeInstance = new ContainersNode();
$containersNodeInstance->initFromFile($containersConfigurationFile);
// load the system properties
$properties = $this->getSystemProperties($containerNode);
// prepare the sytsem properties
$this->prepareSystemProperties($properties, $webappPath);
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNodeInstance */
foreach ($containersNodeInstance->getContainers() as $containerNodeInstance) {
// replace the properties for the found container node instance
$containerNodeInstance->replaceProperties($properties);
// query whether we've to merge or append the server node instance
if ($container = $systemConfiguration->getContainer($containerNodeInstance->getName())) {
$container->merge($containerNodeInstance);
} else {
$systemConfiguration->attachContainer($containerNodeInstance);
}
}
} catch (ConfigurationException $ce) {
// load the logger and log the XML validation errors
$systemLogger = $this->getInitialContext()->getSystemLogger();
$systemLogger->error($ce->__toString());
// additionally log a message that server configuration will be missing
$systemLogger->critical(
sprintf(
'Will skip app specific server configuration because of invalid file %s',
$containersConfigurationFile
)
);
}
}
} | php | public function loadContainerInstance(
ContainerConfigurationInterface $containerNode,
SystemConfigurationInterface $systemConfiguration,
$webappPath
) {
// load the service to validate the files
/** @var \AppserverIo\Appserver\Core\Api\ConfigurationService $configurationService */
$configurationService = $this->newService('AppserverIo\Appserver\Core\Api\ConfigurationService');
// iterate through all server configurations (servers.xml), validate and merge them
foreach ($this->globDir(AppEnvironmentHelper::getEnvironmentAwareGlobPattern($webappPath, 'META-INF/containers')) as $containersConfigurationFile) {
try {
// validate the application specific container configurations
$configurationService->validateFile($containersConfigurationFile, null);
// create a new containers node instance
$containersNodeInstance = new ContainersNode();
$containersNodeInstance->initFromFile($containersConfigurationFile);
// load the system properties
$properties = $this->getSystemProperties($containerNode);
// prepare the sytsem properties
$this->prepareSystemProperties($properties, $webappPath);
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNodeInstance */
foreach ($containersNodeInstance->getContainers() as $containerNodeInstance) {
// replace the properties for the found container node instance
$containerNodeInstance->replaceProperties($properties);
// query whether we've to merge or append the server node instance
if ($container = $systemConfiguration->getContainer($containerNodeInstance->getName())) {
$container->merge($containerNodeInstance);
} else {
$systemConfiguration->attachContainer($containerNodeInstance);
}
}
} catch (ConfigurationException $ce) {
// load the logger and log the XML validation errors
$systemLogger = $this->getInitialContext()->getSystemLogger();
$systemLogger->error($ce->__toString());
// additionally log a message that server configuration will be missing
$systemLogger->critical(
sprintf(
'Will skip app specific server configuration because of invalid file %s',
$containersConfigurationFile
)
);
}
}
} | [
"public",
"function",
"loadContainerInstance",
"(",
"ContainerConfigurationInterface",
"$",
"containerNode",
",",
"SystemConfigurationInterface",
"$",
"systemConfiguration",
",",
"$",
"webappPath",
")",
"{",
"// load the service to validate the files",
"/** @var \\AppserverIo\\Apps... | Loads the container instances from the META-INF/containers.xml configuration file of the
passed web application path and add/merge them to/with the system configuration.
@param \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode The container node used for property replacement
@param \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface $systemConfiguration The system configuration to add/merge the found containers to/with
@param string $webappPath The path to the web application to search for a META-INF/containers.xml file
@return void | [
"Loads",
"the",
"container",
"instances",
"from",
"the",
"META",
"-",
"INF",
"/",
"containers",
".",
"xml",
"configuration",
"file",
"of",
"the",
"passed",
"web",
"application",
"path",
"and",
"add",
"/",
"merge",
"them",
"to",
"/",
"with",
"the",
"system"... | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DeploymentService.php#L199-L251 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/DeploymentService.php | DeploymentService.loadContainerInstances | public function loadContainerInstances()
{
// load the system configuration
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface $systemConfiguration */
$systemConfiguration = $this->getSystemConfiguration();
// if applications are NOT allowed to override the system configuration
if ($systemConfiguration->getAllowApplicationConfiguration() === false) {
return $systemConfiguration;
}
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNodeInstance */
foreach ($systemConfiguration->getContainers() as $containerNode) {
// load the containers application base directory
$containerAppBase = $this->getBaseDirectory($containerNode->getHost()->getAppBase());
// iterate over all applications and create the server configuration
foreach (glob($containerAppBase . '/*', GLOB_ONLYDIR) as $webappPath) {
$this->loadContainerInstance($containerNode, $systemConfiguration, $webappPath);
}
}
// returns the merged system configuration
return $systemConfiguration;
} | php | public function loadContainerInstances()
{
// load the system configuration
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface $systemConfiguration */
$systemConfiguration = $this->getSystemConfiguration();
// if applications are NOT allowed to override the system configuration
if ($systemConfiguration->getAllowApplicationConfiguration() === false) {
return $systemConfiguration;
}
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNodeInstance */
foreach ($systemConfiguration->getContainers() as $containerNode) {
// load the containers application base directory
$containerAppBase = $this->getBaseDirectory($containerNode->getHost()->getAppBase());
// iterate over all applications and create the server configuration
foreach (glob($containerAppBase . '/*', GLOB_ONLYDIR) as $webappPath) {
$this->loadContainerInstance($containerNode, $systemConfiguration, $webappPath);
}
}
// returns the merged system configuration
return $systemConfiguration;
} | [
"public",
"function",
"loadContainerInstances",
"(",
")",
"{",
"// load the system configuration",
"/** @var \\AppserverIo\\Psr\\ApplicationServer\\Configuration\\SystemConfigurationInterface $systemConfiguration */",
"$",
"systemConfiguration",
"=",
"$",
"this",
"->",
"getSystemConfigur... | Loads the containers, defined by the applications, merges them into
the system configuration and returns the merged system configuration.
@return \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface The merged system configuration | [
"Loads",
"the",
"containers",
"defined",
"by",
"the",
"applications",
"merges",
"them",
"into",
"the",
"system",
"configuration",
"and",
"returns",
"the",
"merged",
"system",
"configuration",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/DeploymentService.php#L259-L284 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Listeners/StartContainersListener.php | StartContainersListener.handle | public function handle(EventInterface $event, $runlevel = ApplicationServerInterface::NETWORK)
{
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());
// initialize the service to load the container configurations
/** @var \AppserverIo\Appserver\Core\Api\DeploymentService $deploymentService */
$deploymentService = $this->getDeploymentService();
$applicationServer->setSystemConfiguration($systemConfiguration = $deploymentService->loadContainerInstances());
// we also have to re-attach the system configuration to the initial context, because it's not a \Stackable
/** @var \AppserverIo\Appserver\Application\Interfaces\ContextInterface */
$initialContext = $applicationServer->getInitialContext();
$initialContext->setSystemConfiguration($systemConfiguration);
$applicationServer->setInitialContext($initialContext);
// load the naming directory
/** @var \AppserverIo\Appserver\Naming\NamingDirectory $namingDirectory */
$namingDirectory = $applicationServer->getNamingDirectory();
// initialize the environment variables
$namingDirectory->bind('php:env/baseDirectory', $deploymentService->getBaseDirectory());
$namingDirectory->bind('php:env/tmpDirectory', $deploymentService->getSystemTmpDir());
$namingDirectory->bind('php:env/vendorDirectory', $deploymentService->getVendorDir());
$namingDirectory->bind('php:env/umask', $applicationServer->getSystemConfiguration()->getUmask());
$namingDirectory->bind('php:env/user', $applicationServer->getSystemConfiguration()->getUser());
$namingDirectory->bind('php:env/group', $applicationServer->getSystemConfiguration()->getGroup());
// and initialize a container thread for each container
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */
foreach ($applicationServer->getSystemConfiguration()->getContainers() as $containerNode) {
// load the factory class name
/** @var \AppserverIo\Appserver\Core\Interfaces\ContainerFactoryInterface $containerFactory */
$containerFactory = $containerNode->getFactory();
// use the factory to create a new container instance
/** @var \AppserverIo\Psr\ApplicationServer\ContainerInterface $container */
$container = $containerFactory::factory($applicationServer, $containerNode, $runlevel);
$container->start();
// wait until all servers has been bound to their ports and addresses
while ($container->hasServersStarted() === false) {
// sleep to avoid cpu load
usleep(10000);
}
// register the container as service
$applicationServer->bindService($runlevel, $container);
}
} catch (\Exception $e) {
$applicationServer->getSystemLogger()->error($e->__toString());
}
} | php | public function handle(EventInterface $event, $runlevel = ApplicationServerInterface::NETWORK)
{
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());
// initialize the service to load the container configurations
/** @var \AppserverIo\Appserver\Core\Api\DeploymentService $deploymentService */
$deploymentService = $this->getDeploymentService();
$applicationServer->setSystemConfiguration($systemConfiguration = $deploymentService->loadContainerInstances());
// we also have to re-attach the system configuration to the initial context, because it's not a \Stackable
/** @var \AppserverIo\Appserver\Application\Interfaces\ContextInterface */
$initialContext = $applicationServer->getInitialContext();
$initialContext->setSystemConfiguration($systemConfiguration);
$applicationServer->setInitialContext($initialContext);
// load the naming directory
/** @var \AppserverIo\Appserver\Naming\NamingDirectory $namingDirectory */
$namingDirectory = $applicationServer->getNamingDirectory();
// initialize the environment variables
$namingDirectory->bind('php:env/baseDirectory', $deploymentService->getBaseDirectory());
$namingDirectory->bind('php:env/tmpDirectory', $deploymentService->getSystemTmpDir());
$namingDirectory->bind('php:env/vendorDirectory', $deploymentService->getVendorDir());
$namingDirectory->bind('php:env/umask', $applicationServer->getSystemConfiguration()->getUmask());
$namingDirectory->bind('php:env/user', $applicationServer->getSystemConfiguration()->getUser());
$namingDirectory->bind('php:env/group', $applicationServer->getSystemConfiguration()->getGroup());
// and initialize a container thread for each container
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */
foreach ($applicationServer->getSystemConfiguration()->getContainers() as $containerNode) {
// load the factory class name
/** @var \AppserverIo\Appserver\Core\Interfaces\ContainerFactoryInterface $containerFactory */
$containerFactory = $containerNode->getFactory();
// use the factory to create a new container instance
/** @var \AppserverIo\Psr\ApplicationServer\ContainerInterface $container */
$container = $containerFactory::factory($applicationServer, $containerNode, $runlevel);
$container->start();
// wait until all servers has been bound to their ports and addresses
while ($container->hasServersStarted() === false) {
// sleep to avoid cpu load
usleep(10000);
}
// register the container as service
$applicationServer->bindService($runlevel, $container);
}
} catch (\Exception $e) {
$applicationServer->getSystemLogger()->error($e->__toString());
}
} | [
"public",
"function",
"handle",
"(",
"EventInterface",
"$",
"event",
",",
"$",
"runlevel",
"=",
"ApplicationServerInterface",
"::",
"NETWORK",
")",
"{",
"try",
"{",
"// load the application server instance",
"/** @var \\AppserverIo\\Psr\\ApplicationServer\\ApplicationServerInte... | Handle an event.
@param \League\Event\EventInterface $event The triggering event
@param integer $runlevel The actual runlevel
@return void
@see \League\Event\ListenerInterface::handle() | [
"Handle",
"an",
"event",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Listeners/StartContainersListener.php#L47-L105 |
appserver-io/appserver | src/AppserverIo/Appserver/Core/Api/Node/DatasourcesNode.php | DatasourcesNode.getDatasourcesAsArray | public function getDatasourcesAsArray()
{
// initialize the array
$datasources = array();
// prepare the array with the datasources
foreach ($this->getDatasources() as $datasource) {
$datasources[$datasource->getPrimaryKey()] = $datasource;
}
// return the array with the datasources
return $datasources;
} | php | public function getDatasourcesAsArray()
{
// initialize the array
$datasources = array();
// prepare the array with the datasources
foreach ($this->getDatasources() as $datasource) {
$datasources[$datasource->getPrimaryKey()] = $datasource;
}
// return the array with the datasources
return $datasources;
} | [
"public",
"function",
"getDatasourcesAsArray",
"(",
")",
"{",
"// initialize the array",
"$",
"datasources",
"=",
"array",
"(",
")",
";",
"// prepare the array with the datasources",
"foreach",
"(",
"$",
"this",
"->",
"getDatasources",
"(",
")",
"as",
"$",
"datasour... | Return's an array with the datasources.
@return array The array with datasources | [
"Return",
"s",
"an",
"array",
"with",
"the",
"datasources",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/Core/Api/Node/DatasourcesNode.php#L61-L74 |
appserver-io/appserver | src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php | PersistenceManager.addEntityManagerName | public function addEntityManagerName($entityManagerName)
{
$this->getEntityManagerNames()->set(sizeof($this->getEntityManagerNames()->getAllKeys()), $entityManagerName);
} | php | public function addEntityManagerName($entityManagerName)
{
$this->getEntityManagerNames()->set(sizeof($this->getEntityManagerNames()->getAllKeys()), $entityManagerName);
} | [
"public",
"function",
"addEntityManagerName",
"(",
"$",
"entityManagerName",
")",
"{",
"$",
"this",
"->",
"getEntityManagerNames",
"(",
")",
"->",
"set",
"(",
"sizeof",
"(",
"$",
"this",
"->",
"getEntityManagerNames",
"(",
")",
"->",
"getAllKeys",
"(",
")",
... | Add the passed entity manager name to the persistenc manager.
@param string $entityManagerName The entity manager name to add
@return void | [
"Add",
"the",
"passed",
"entity",
"manager",
"name",
"to",
"the",
"persistenc",
"manager",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php#L88-L91 |
appserver-io/appserver | src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php | PersistenceManager.registerEntityManagers | public function registerEntityManagers(ApplicationInterface $application)
{
// build up META-INF directory var
$metaInfDir = $this->getWebappPath() . DIRECTORY_SEPARATOR .'META-INF';
// check if we've found a valid directory
if (is_dir($metaInfDir) === false) {
return;
}
// check META-INF + subdirectories for XML files with MQ definitions
/** @var \AppserverIo\Appserver\Core\Api\DeploymentService $service */
$service = $application->newService('AppserverIo\Appserver\Core\Api\DeploymentService');
$xmlFiles = $service->globDir(AppEnvironmentHelper::getEnvironmentAwareGlobPattern($this->getWebappPath(), 'META-INF' . DIRECTORY_SEPARATOR . 'persistence'));
// load the configuration service instance
/** @var \AppserverIo\Appserver\Core\Api\ConfigurationService $configurationService */
$configurationService = $application->newService('AppserverIo\Appserver\Core\Api\ConfigurationService');
// load the container node to initialize the system properties
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */
$containerNode = $application->getContainer()->getContainerNode();
// gather all the deployed web applications
foreach ($xmlFiles as $file) {
try {
// validate the file here, but skip if the validation fails
$configurationService->validateFile($file, null, true);
// load the system properties
$properties = $service->getSystemProperties($containerNode);
// append the application specific properties
$properties->add(SystemPropertyKeys::WEBAPP, $webappPath = $application->getWebappPath());
$properties->add(SystemPropertyKeys::WEBAPP_NAME, basename($webappPath));
$properties->add(SystemPropertyKeys::WEBAPP_DATA, $application->getDataDir());
$properties->add(SystemPropertyKeys::WEBAPP_CACHE, $application->getCacheDir());
$properties->add(SystemPropertyKeys::WEBAPP_SESSION, $application->getSessionDir());
// create a new persistence manager node instance and replace the properties
$persistenceNode = new PersistenceNode();
$persistenceNode->initFromFile($file);
$persistenceNode->replaceProperties($properties);
// register the entity managers found in the configuration
foreach ($persistenceNode->getPersistenceUnits() as $persistenceUnitNode) {
$this->registerEntityManager($application, $persistenceUnitNode);
}
} catch (InvalidConfigurationException $e) {
// try to load the system logger instance
/** @var \Psr\Log\LoggerInterface $systemLogger */
if ($systemLogger = $this->getApplication()->getInitialContext()->getSystemLogger()) {
$systemLogger->error($e->getMessage());
$systemLogger->critical(sprintf('Persistence configuration file %s is invalid, needed entity managers might be missing.', $file));
}
} catch (\Exception $e) {
// try to load the system logger instance
/** @var \Psr\Log\LoggerInterface $systemLogger */
if ($systemLogger = $this->getApplication()->getInitialContext()->getSystemLogger()) {
$systemLogger->error($e->__toString());
}
}
}
} | php | public function registerEntityManagers(ApplicationInterface $application)
{
// build up META-INF directory var
$metaInfDir = $this->getWebappPath() . DIRECTORY_SEPARATOR .'META-INF';
// check if we've found a valid directory
if (is_dir($metaInfDir) === false) {
return;
}
// check META-INF + subdirectories for XML files with MQ definitions
/** @var \AppserverIo\Appserver\Core\Api\DeploymentService $service */
$service = $application->newService('AppserverIo\Appserver\Core\Api\DeploymentService');
$xmlFiles = $service->globDir(AppEnvironmentHelper::getEnvironmentAwareGlobPattern($this->getWebappPath(), 'META-INF' . DIRECTORY_SEPARATOR . 'persistence'));
// load the configuration service instance
/** @var \AppserverIo\Appserver\Core\Api\ConfigurationService $configurationService */
$configurationService = $application->newService('AppserverIo\Appserver\Core\Api\ConfigurationService');
// load the container node to initialize the system properties
/** @var \AppserverIo\Psr\ApplicationServer\Configuration\ContainerConfigurationInterface $containerNode */
$containerNode = $application->getContainer()->getContainerNode();
// gather all the deployed web applications
foreach ($xmlFiles as $file) {
try {
// validate the file here, but skip if the validation fails
$configurationService->validateFile($file, null, true);
// load the system properties
$properties = $service->getSystemProperties($containerNode);
// append the application specific properties
$properties->add(SystemPropertyKeys::WEBAPP, $webappPath = $application->getWebappPath());
$properties->add(SystemPropertyKeys::WEBAPP_NAME, basename($webappPath));
$properties->add(SystemPropertyKeys::WEBAPP_DATA, $application->getDataDir());
$properties->add(SystemPropertyKeys::WEBAPP_CACHE, $application->getCacheDir());
$properties->add(SystemPropertyKeys::WEBAPP_SESSION, $application->getSessionDir());
// create a new persistence manager node instance and replace the properties
$persistenceNode = new PersistenceNode();
$persistenceNode->initFromFile($file);
$persistenceNode->replaceProperties($properties);
// register the entity managers found in the configuration
foreach ($persistenceNode->getPersistenceUnits() as $persistenceUnitNode) {
$this->registerEntityManager($application, $persistenceUnitNode);
}
} catch (InvalidConfigurationException $e) {
// try to load the system logger instance
/** @var \Psr\Log\LoggerInterface $systemLogger */
if ($systemLogger = $this->getApplication()->getInitialContext()->getSystemLogger()) {
$systemLogger->error($e->getMessage());
$systemLogger->critical(sprintf('Persistence configuration file %s is invalid, needed entity managers might be missing.', $file));
}
} catch (\Exception $e) {
// try to load the system logger instance
/** @var \Psr\Log\LoggerInterface $systemLogger */
if ($systemLogger = $this->getApplication()->getInitialContext()->getSystemLogger()) {
$systemLogger->error($e->__toString());
}
}
}
} | [
"public",
"function",
"registerEntityManagers",
"(",
"ApplicationInterface",
"$",
"application",
")",
"{",
"// build up META-INF directory var",
"$",
"metaInfDir",
"=",
"$",
"this",
"->",
"getWebappPath",
"(",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"'META-INF'",
";",
"... | Registers the entity managers at startup.
@param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance
@return void | [
"Registers",
"the",
"entity",
"managers",
"at",
"startup",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php#L136-L202 |
appserver-io/appserver | src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php | PersistenceManager.registerEntityManager | public function registerEntityManager(ApplicationInterface $application, PersistenceUnitConfigurationInterface $persistenceUnitNode)
{
// bind the callback for the Entity Manager instance to the naming directory
$application->getNamingDirectory()
->bind(
sprintf('php:global/%s/%s', $application->getUniqueName(), $lookupName = $persistenceUnitNode->getName()),
array(&$this, 'lookup'),
array($lookupName)
);
// bind the Entity Manager's configuration to the naming directory
$application->getNamingDirectory()
->bind(
sprintf('php:global/%s/%sConfiguration', $application->getUniqueName(), $lookupName),
$persistenceUnitNode
);
// register the entity manager's configuration in the persistence manager
$this->addEntityManagerName($lookupName);
// load the object manager instance
$objectManager = $this->getApplication()->search(ObjectManagerInterface::IDENTIFIER);
// add the descriptors, necesseary to create the Entity Manaager instance, to the object manager
$objectManager->addObjectDescriptor(PersistenceUnitDescriptor::newDescriptorInstance()->fromConfiguration($persistenceUnitNode));
$objectManager->addObjectDescriptor(PersistenceUnitFactoryDescriptor::newDescriptorInstance()->fromConfiguration($persistenceUnitNode));
} | php | public function registerEntityManager(ApplicationInterface $application, PersistenceUnitConfigurationInterface $persistenceUnitNode)
{
// bind the callback for the Entity Manager instance to the naming directory
$application->getNamingDirectory()
->bind(
sprintf('php:global/%s/%s', $application->getUniqueName(), $lookupName = $persistenceUnitNode->getName()),
array(&$this, 'lookup'),
array($lookupName)
);
// bind the Entity Manager's configuration to the naming directory
$application->getNamingDirectory()
->bind(
sprintf('php:global/%s/%sConfiguration', $application->getUniqueName(), $lookupName),
$persistenceUnitNode
);
// register the entity manager's configuration in the persistence manager
$this->addEntityManagerName($lookupName);
// load the object manager instance
$objectManager = $this->getApplication()->search(ObjectManagerInterface::IDENTIFIER);
// add the descriptors, necesseary to create the Entity Manaager instance, to the object manager
$objectManager->addObjectDescriptor(PersistenceUnitDescriptor::newDescriptorInstance()->fromConfiguration($persistenceUnitNode));
$objectManager->addObjectDescriptor(PersistenceUnitFactoryDescriptor::newDescriptorInstance()->fromConfiguration($persistenceUnitNode));
} | [
"public",
"function",
"registerEntityManager",
"(",
"ApplicationInterface",
"$",
"application",
",",
"PersistenceUnitConfigurationInterface",
"$",
"persistenceUnitNode",
")",
"{",
"// bind the callback for the Entity Manager instance to the naming directory",
"$",
"application",
"->"... | Deploys the entity manager described by the passed XML node.
@param \AppserverIo\Psr\Application\ApplicationInterface $application The application instance
@param \AppserverIo\Description\Configuration\PersistenceUnitConfigurationInterface $persistenceUnitNode The XML node that describes the entity manager
@return void | [
"Deploys",
"the",
"entity",
"manager",
"described",
"by",
"the",
"passed",
"XML",
"node",
"."
] | train | https://github.com/appserver-io/appserver/blob/2a5be730158b1fe2e60586665d5656d46c82ba73/src/AppserverIo/Appserver/PersistenceContainer/PersistenceManager.php#L212-L239 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.