Ejemplo n.º 1
0
 /**
  * This method finally handles all PHP and user errors as well as the exceptions that
  * have been thrown through the servlet processing.
  *
  * @param \AppserverIo\Appserver\ServletEngine\RequestHandler        $requestHandler  The request handler instance
  * @param \AppserverIo\Psr\Servlet\Http\HttpServletRequestInterface  $servletRequest  The actual request instance
  * @param \AppserverIo\Psr\Servlet\Http\HttpServletResponseInterface $servletResponse The actual request instance
  *
  * @return void
  */
 public function handleErrors(RequestHandler $requestHandler, HttpServletRequestInterface $servletRequest, HttpServletResponseInterface $servletResponse)
 {
     // return immediately if we don't have any errors
     if (sizeof($errors = $requestHandler->getErrors()) === 0) {
         return;
     }
     // iterate over the errors to process each of them
     foreach ($errors as $error) {
         // prepare the error message
         $message = $this->prepareMessage($error);
         // query whether or not we have to log the error
         if (Boolean::valueOf(new String(ini_get('log_errors')))->booleanValue()) {
             // create a local copy of the application
             if ($application = $servletRequest->getContext()) {
                 // try to load the system logger from the application
                 if ($systemLogger = $application->getLogger(LoggerUtils::SYSTEM)) {
                     $systemLogger->log($this->mapLogLevel($error), $message);
                 }
             }
         }
         // query whether or not, the error has an status code
         if ($statusCode = $error->getStatusCode()) {
             $servletResponse->setStatusCode($statusCode);
         }
     }
     // we add the error to the servlet request
     $servletRequest->setAttribute(RequestHandlerKeys::ERROR_MESSAGES, $errors);
     // we append the the errors to the body stream if display_errors is on
     if (Boolean::valueOf(new String(ini_get('display_errors')))->booleanValue()) {
         $servletResponse->appendBodyStream(implode('<br/>', $errors));
     }
     // query whether or not we've a client or an server error
     if ($servletResponse->getStatusCode() > 399) {
         try {
             // create a local copy of the application
             $application = $servletRequest->getContext();
             // inject the application and servlet response
             $servletRequest->injectResponse($servletResponse);
             $servletRequest->injectContext($application);
             // load the servlet context instance
             $servletManager = $application->search(ServletContextInterface::IDENTIFIER);
             // initialize the request URI for the error page to be rendered
             $requestUri = null;
             // iterate over the configured error pages to find a matching one
             foreach ($servletManager->getErrorPages() as $errorCodePattern => $errorPage) {
                 // query whether or not we found an error page configured for the actual status code
                 if (fnmatch($errorCodePattern, $servletResponse->getStatusCode())) {
                     $requestUri = $errorPage;
                     break;
                 }
             }
             // query whether or not we've an found a configured error page
             if ($requestUri == null) {
                 throw new ServletException(sprintf('Please configure an error page for status code %s', $servletResponse->getStatusCode()));
             }
             // initialize the request URI
             $servletRequest->setRequestUri($requestUri);
             // prepare the request with the new data
             $servletRequest->prepare();
             // reset the body stream to remove content, that has already been appended
             $servletResponse->resetBodyStream();
             // load the servlet path and session-ID
             $servletPath = $servletRequest->getServletPath();
             $sessionId = $servletRequest->getProposedSessionId();
             // load and process the servlet
             $servlet = $servletManager->lookup($servletPath, $sessionId);
             $servlet->service($servletRequest, $servletResponse);
         } catch (\Exception $e) {
             // finally log the exception
             $application->getInitialContext()->getSystemLogger()->critical($e->__toString());
             // append the exception message to the body stream
             $servletResponse->appendBodyStream($e->__toString());
         }
     }
 }
Ejemplo n.º 2
0
 /**
  * Casts the params value to the defined type and returns it.
  *
  * @return mixed The casted value
  */
 public function castToType()
 {
     // load the params value
     $value = $this->getNodeValue()->__toString();
     // query whether or not we've an environment variable and/or a constant
     $this->isEnv() ? $value = getenv($value) : $value;
     $this->isConstant() ? $value = constant($value) : $value;
     // query the parameters type
     switch ($type = $this->getType()) {
         case 'bool':
         case 'boolean':
             // bool + boolean needs custom handling
             $value = Boolean::valueOf(new String($value))->booleanValue();
             break;
         default:
             // all other can go the same way
             settype($value, $type);
     }
     // return the value
     return $value;
 }
Ejemplo n.º 3
0
 /**
  * Returns the value for a given reflection property and configuration
  *
  * @param \ReflectionProperty                                          $reflectionProperty The reflection property
  * @param \AppserverIo\Configuration\Interfaces\ConfigurationInterface $configuration      The configuration instance
  *
  * @return array|null An array with all values from given reflection property
  * @throws \Exception
  */
 public function getValueForReflectionProperty(\ReflectionProperty $reflectionProperty, ConfigurationInterface $configuration)
 {
     // load the mapping from the annotation
     $mapping = $this->getPropertyTypeFromDocComment($reflectionProperty);
     // if we don't have a mapping do nothing
     if ($mapping == null) {
         return;
     }
     // load node type and configuration node name
     $nodeType = $mapping->getNodeType();
     $configurationNodeName = $this->getConfigurationNodeName($configuration, $mapping);
     // get our valid simple node types
     $simpleTypes = array_flip(array('string', 'integer', 'float', 'boolean', 'double', 'array'));
     // initialize a new value configuration node
     if (!isset($simpleTypes[$nodeType]) && class_exists($nodeType) && $this->isValueClass($nodeType)) {
         // initialize the new node type
         /** @var \AppserverIo\Appserver\Core\Api\Node\AbstractNode $newNode */
         $newNode = new $nodeType();
         $newNode->initFromConfiguration($configuration);
         // set the instance
         return $this->{$reflectionProperty->getName()} = $newNode;
         // initialize a new configuration node from the found child data
     } elseif (!isset($simpleTypes[$nodeType]) && class_exists($nodeType)) {
         // first we've to check if the child has data
         if ($child = $configuration->getChild($configurationNodeName)) {
             // initialize the new node type
             /** @var \AppserverIo\Appserver\Core\Api\Node\AbstractNode $newNode */
             $newNode = new $nodeType();
             $newNode->initFromConfiguration($child);
             $newNode->setParentUuid($this->getUuid());
             // set the instance
             $this->{$reflectionProperty->getName()} = $newNode;
         }
         // return anyway
         return;
     }
     // array => create the configured nodes and add them
     if ($nodeType === 'array') {
         // iterate over all elements and create the node
         foreach ($configuration->getChilds($configurationNodeName) as $child) {
             // initialize the node and load the data from the configuration
             $elementType = $mapping->getElementType();
             /** @var \AppserverIo\Appserver\Core\Api\Node\AbstractNode $newNode */
             $newNode = new $elementType();
             $newNode->initFromConfiguration($child);
             $newNode->setParentUuid($this->getUuid());
             // add the value to the node
             if ($pk = $newNode->getPrimaryKey()) {
                 $this->{$reflectionProperty->getName()}[$pk] = $newNode;
             } else {
                 $this->{$reflectionProperty->getName()}[] = $newNode;
             }
         }
         return;
     }
     // check the node type specified in the annotation
     switch ($nodeType) {
         case 'string':
             // simple string, we don't have to do anything
             if ($configuration->getData($reflectionProperty->getName()) == null) {
                 return;
             }
             return $this->{$reflectionProperty->getName()} = $configuration->getData($reflectionProperty->getName());
         case 'integer':
             // integer => validate and transform the value
             if ($configuration->getData($reflectionProperty->getName()) == null) {
                 return;
             }
             $integer = Integer::valueOf(new String($configuration->getData($reflectionProperty->getName())));
             return $this->{$reflectionProperty->getName()} = $integer->intValue();
         case 'float':
             // float => validate and transform the value
             if ($configuration->getData($reflectionProperty->getName()) == null) {
                 return;
             }
             $float = Float::valueOf(new String($configuration->getData($reflectionProperty->getName())));
             return $this->{$reflectionProperty->getName()} = $float->floatValue();
         case 'double':
             // double => validate and transform the value
             if ($configuration->getData($reflectionProperty->getName()) == null) {
                 return;
             }
             $float = Float::valueOf(new String($configuration->getData($reflectionProperty->getName())));
             return $this->{$reflectionProperty->getName()} = $float->doubleValue();
         case 'boolean':
             // boolean => validate and transform the value
             if ($configuration->getData($reflectionProperty->getName()) == null) {
                 return;
             }
             $boolean = Boolean::valueOf(new String($configuration->getData($reflectionProperty->getName())));
             return $this->{$reflectionProperty->getName()} = $boolean->booleanValue();
         default:
             // we don't support other node types
             throw new \Exception(sprintf("Found invalid property type %s in node %s", $nodeType, get_class($this)));
     }
 }
Ejemplo n.º 4
0
 /**
  * Creates a new entity manager instance based on the passed configuration.
  *
  * @param \AppserverIo\Psr\Application\ApplicationInterface                 $application         The application instance to create the entity manager for
  * @param \AppserverIo\Appserver\Core\Api\Node\PersistenceUnitNodeInterface $persistenceUnitNode The datasource configuration
  *
  * @return object The entity manager instance
  */
 public static function factory(ApplicationInterface $application, PersistenceUnitNodeInterface $persistenceUnitNode)
 {
     // register additional annotation libraries
     foreach ($persistenceUnitNode->getAnnotationRegistries() as $annotationRegistry) {
         AnnotationRegistry::registerAutoloadNamespace($annotationRegistry->getNamespace(), $annotationRegistry->getDirectoriesAsArray($application->getWebappPath()));
     }
     // load the metadata configuration
     $metadataConfiguration = $persistenceUnitNode->getMetadataConfiguration();
     // prepare the setup properties
     $absolutePaths = $metadataConfiguration->getDirectoriesAsArray($application->getWebappPath());
     $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_PROXY_DIR);
     $isDevMode = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_IS_DEV_MODE);
     $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_USE_SIMPLE_ANNOTATION_READER);
     // load the factory method from the available mappings
     $factoryMethod = EntityManagerFactory::$metadataMapping[$metadataConfiguration->getType()];
     // create the database configuration and initialize the entity manager
     $configuration = Setup::$factoryMethod($absolutePaths, $isDevMode, $proxyDir, null, $useSimpleAnnotationReader);
     // load the datasource node
     $datasourceNode = null;
     foreach ($application->getInitialContext()->getSystemConfiguration()->getDatasources() as $datasourceNode) {
         if ($datasourceNode->getName() === $persistenceUnitNode->getDatasource()->getName()) {
             break;
         }
     }
     // throw a exception if the configured datasource is NOT available
     if ($datasourceNode == null) {
         throw new \Exception(sprintf('Can\'t find a datasource node for persistence unit %s', $persistenceUnitNode->getName()));
     }
     // load the database node
     $databaseNode = $datasourceNode->getDatabase();
     // throw an exception if the configured database is NOT available
     if ($databaseNode == null) {
         throw new \Exception(sprintf('Can\'t find database node for persistence unit %s', $persistenceUnitNode->getName()));
     }
     // load the driver node
     $driverNode = $databaseNode->getDriver();
     // throw an exception if the configured driver is NOT available
     if ($driverNode == null) {
         throw new \Exception(sprintf('Can\'t find driver node for persistence unit %s', $persistenceUnitNode->getName()));
     }
     // initialize the connection parameters with the mandatory driver
     $connectionParameters = array('driver' => $databaseNode->getDriver()->getNodeValue()->__toString());
     // initialize the path/memory to the database when we use sqlite for example
     if ($pathNode = $databaseNode->getPath()) {
         $connectionParameters['path'] = $application->getWebappPath() . DIRECTORY_SEPARATOR . $pathNode->getNodeValue()->__toString();
     } elseif ($memoryNode = $databaseNode->getMemory()) {
         $connectionParameters['memory'] = Boolean::valueOf(new String($memoryNode->getNodeValue()->__toString()))->booleanValue();
     } else {
         // do nothing here, because there is NO option
     }
     // add username, if specified
     if ($userNode = $databaseNode->getUser()) {
         $connectionParameters['user'] = $userNode->getNodeValue()->__toString();
     }
     // add password, if specified
     if ($passwordNode = $databaseNode->getPassword()) {
         $connectionParameters['password'] = $passwordNode->getNodeValue()->__toString();
     }
     // add database name if using another PDO driver than sqlite
     if ($databaseNameNode = $databaseNode->getDatabaseName()) {
         $connectionParameters['dbname'] = $databaseNameNode->getNodeValue()->__toString();
     }
     // add database host if using another PDO driver than sqlite
     if ($databaseHostNode = $databaseNode->getDatabaseHost()) {
         $connectionParameters['host'] = $databaseHostNode->getNodeValue()->__toString();
     }
     // add charset, if specified
     if ($charsetNode = $databaseNode->getCharset()) {
         $connectionParameters['charset'] = $charsetNode->getNodeValue()->__toString();
     }
     // add driver options, if specified
     if ($driverOptionsNode = $databaseNode->getDriverOptions()) {
         // explode the raw options separated with a semicolon
         $rawOptions = explode(';', $driverOptionsNode->getNodeValue()->__toString());
         // prepare the array with the driver options key/value pair (separated with a =)
         $options = array();
         foreach ($rawOptions as $rawOption) {
             list($key, $value) = explode('=', $rawOption);
             $options[$key] = $value;
         }
         // set the driver options
         $connectionParameters['driverOptions'] = $options;
     }
     // add driver options, if specified
     if ($unixSocketNode = $databaseNode->getUnixSocket()) {
         $connectionParameters['unix_socket'] = $unixSocketNode->getNodeValue()->__toString();
     }
     // initialize and return a entity manager decorator instance
     return new DoctrineEntityManagerDecorator(EntityManager::create($connectionParameters, $configuration));
 }
Ejemplo n.º 5
0
 /**
  * Casts the params value to the defined type and returns it.
  *
  * @return mixed The casted value
  */
 public function castToType()
 {
     // load the params value
     $value = $this->getNodeValue()->__toString();
     // query the parameters type
     switch ($type = $this->getType()) {
         case 'bool':
         case 'boolean':
             // bool + boolean needs custom handling
             $value = Boolean::valueOf(new String($value))->booleanValue();
             break;
         default:
             // all other can go the same way
             settype($value, $type);
     }
     // return the value
     return $value;
 }
 /**
  * Initializes a bean descriptor instance from the passed configuration node.
  *
  * @param \AppserverIo\Description\Configuration\ConfigurationInterface $configuration The configuration node with the bean configuration
  *
  * @return \AppserverIo\Psr\EnterpriseBeans\Description\SingletonSessionBeanDescriptorInterface|null The initialized descriptor instance
  */
 public function fromConfiguration(ConfigurationInterface $configuration)
 {
     // query whether or not we've a session bean configuration
     if (!$configuration instanceof SessionConfigurationInterface) {
         return;
     }
     // query wheter or not the session type matches
     if ((string) $configuration->getSessionType() !== SingletonSessionBeanDescriptor::SESSION_TYPE) {
         return;
     }
     // initialize the descriptor instance
     parent::fromConfiguration($configuration);
     // initialize the post detach callback methods
     if ($postDetach = $configuration->getPostDetach()) {
         foreach ($postDetach->getLifecycleCallbackMethods() as $postDetachCallback) {
             $this->addPostDetachCallback(DescriptorUtil::trim((string) $postDetachCallback));
         }
     }
     // initialize the pre attach callback methods
     if ($preAttach = $configuration->getPreAttach()) {
         foreach ($preAttach->getLifecycleCallbackMethods() as $preAttachCallback) {
             $this->addPreAttachCallback(DescriptorUtil::trim((string) $preAttachCallback));
         }
     }
     // query for the startup flag
     if ($initOnStartup = (string) $configuration->getInitOnStartup()) {
         $this->setInitOnStartup(Boolean::valueOf(new String($initOnStartup))->booleanValue());
     }
     // return the instance
     return $this;
 }
 /**
  * Query whether or not this is the default authenticator.
  *
  * @return boolean TRUE if this is the default authenticator, else FALSE
  */
 public function isDefaultAuthenticator()
 {
     return $this->defaultAuthenticator->booleanValue();
 }
Ejemplo n.º 8
0
 /**
  * Creates an array with the connection parameters for a Doctrine DBAL connection from
  * the passed database node.
  *
  * @param AppserverIo\Appserver\Core\Api\Node\DatabaseNodeInterface $databaseNode The database node to create the connection parameters from
  *
  * @return array The DBAL connection parameters
  */
 public function fromDatabaseNode(DatabaseNodeInterface $databaseNode)
 {
     // initialize the connection parameters with the mandatory driver
     $connectionParameters = array('driver' => $databaseNode->getDriver()->getNodeValue()->__toString());
     // initialize the path/memory to the database when we use sqlite for example
     if ($pathNode = $databaseNode->getPath()) {
         $connectionParameters['path'] = $this->getApplication()->getWebappPath() . DIRECTORY_SEPARATOR . $pathNode->getNodeValue()->__toString();
     } elseif ($memoryNode = $databaseNode->getMemory()) {
         $connectionParameters['memory'] = Boolean::valueOf(new String($memoryNode->getNodeValue()->__toString()))->booleanValue();
     } else {
         // do nothing here, because there is NO option
     }
     // add username, if specified
     if ($userNode = $databaseNode->getUser()) {
         $connectionParameters['user'] = $userNode->getNodeValue()->__toString();
     }
     // add password, if specified
     if ($passwordNode = $databaseNode->getPassword()) {
         $connectionParameters['password'] = $passwordNode->getNodeValue()->__toString();
     }
     // add database name if using another PDO driver than sqlite
     if ($databaseNameNode = $databaseNode->getDatabaseName()) {
         $connectionParameters['dbname'] = $databaseNameNode->getNodeValue()->__toString();
     }
     // add database host if using another PDO driver than sqlite
     if ($databaseHostNode = $databaseNode->getDatabaseHost()) {
         $connectionParameters['host'] = $databaseHostNode->getNodeValue()->__toString();
     }
     // add database port if using another PDO driver than sqlite
     if ($databasePortNode = $databaseNode->getDatabasePort()) {
         $connectionParameters['port'] = $databasePortNode->getNodeValue()->__toString();
     }
     // add charset, if specified
     if ($charsetNode = $databaseNode->getCharset()) {
         $connectionParameters['charset'] = $charsetNode->getNodeValue()->__toString();
     }
     // add driver options, if specified
     if ($unixSocketNode = $databaseNode->getUnixSocket()) {
         $connectionParameters['unix_socket'] = $unixSocketNode->getNodeValue()->__toString();
     }
     // add server version, if specified
     if ($serverVersionNode = $databaseNode->getServerVersion()) {
         $connectionParameters['server_version'] = $serverVersionNode->getNodeValue()->__toString();
     }
     // set platform, if specified
     if ($platformNode = $databaseNode->getPlatform()) {
         $platform = $platformNode->getNodeValue()->__toString();
         $connectionParameters['platform'] = new $platform();
     }
     // add driver options, if specified
     if ($driverOptionsNode = $databaseNode->getDriverOptions()) {
         // explode the raw options separated with a semicolon
         $rawOptions = explode(';', $driverOptionsNode->getNodeValue()->__toString());
         // prepare the array with the driver options key/value pair (separated with a =)
         $options = array();
         foreach ($rawOptions as $rawOption) {
             list($key, $value) = explode('=', $rawOption);
             $options[$key] = $value;
         }
         // set the driver options
         $connectionParameters['driverOptions'] = $options;
     }
     // returns the connection parameters
     return $connectionParameters;
 }
 /**
  * Initialize the login module. This stores the subject, callbackHandler and sharedState and options
  * for the login session. Subclasses should override if they need to process their own options. A call
  * to parent::initialize() must be made in the case of an override.
  *
  * The following parameters can by default be passed from the configuration.
  *
  * lookupName:      The datasource name used to lookup in the naming directory
  * rolesQuery:      The database query used to load the user's roles
  * principalsQuery: The database query used to load the user
  *
  * @param \AppserverIo\Psr\Security\Auth\Subject                           $subject         The Subject to update after a successful login
  * @param \AppserverIo\Psr\Security\Auth\Callback\CallbackHandlerInterface $callbackHandler The callback handler that will be used to obtain the user identity and credentials
  * @param \AppserverIo\Collections\MapInterface                            $sharedState     A map shared between all configured login module instances
  * @param \AppserverIo\Collections\MapInterface                            $params          The parameters passed to the login module
  *
  * @return void
  */
 public function initialize(Subject $subject, CallbackHandlerInterface $callbackHandler, MapInterface $sharedState, MapInterface $params)
 {
     // call the parent method
     parent::initialize($subject, $callbackHandler, $sharedState, $params);
     // check to see if password hashing has been enabled, if an algorithm is set, check for a format and charset
     $this->hashAlgorithm = new String($params->get(ParamKeys::HASH_ALGORITHM));
     // query whether or not a hash algorithm has been specified
     if ($this->hashAlgorithm != null) {
         // initialize the hash encoding to use
         if ($params->exists(ParamKeys::HASH_ENCODING)) {
             $this->hashEncoding = new String($params->get(ParamKeys::HASH_ENCODING));
         } else {
             $this->hashEncoding = new String(Util::BASE64_ENCODING);
         }
         // initialize the hash charset if specified
         if ($params->exists(ParamKeys::HASH_CHARSET)) {
             $this->hashCharset = new String($params->get(ParamKeys::HASH_CHARSET));
         }
     }
     // query whether or not we should ignor case when comparing passwords
     if ($params->exists(ParamKeys::IGNORE_PASSWORD_CASE)) {
         $flag = new String($params->get(ParamKeys::IGNORE_PASSWORD_CASE));
         $this->ignorePasswordCase = Boolean::valueOf($flag)->booleanValue();
     } else {
         $this->ignorePasswordCase = false;
     }
 }