Beispiel #1
0
    def __init__(self,
                 message,
                 parsedLine=-1,
                 snippet=None,
                 parsedFile=None,
                 previous=None):
        """Constructor.

        @param: string    message    The error message
        @param integer   parsedLine The line where the error occurred
        @param integer   snippet    The snippet of code near the problem
        @param string    parsedFile The file name where the error occurred
        @param Exception previous   The previous exception

        """
        if previous:
            assert isinstance(previous, Exception)

        self.__parsedFile = None
        self.__parsedLine = None
        self.__snippet = None
        self.__rawMessage = None

        self.__parsedFile = parsedFile
        self.__parsedLine = parsedLine
        self.__snippet = snippet
        self.__rawMessage = message

        self.__updateRepr()

        RuntimeException.__init__(self, self._message, 0, previous)
Beispiel #2
0
    def __init__(self, statusCode, message=None, previous=None, code=0):

        self.__statusCode = None

        self.__statusCode = statusCode

        RuntimeException.__init__(self, message, code, previous)
Beispiel #3
0
    def __init__(self, sourceServiceId, sourceScope, destServiceId, destScope):

        RuntimeException.__init__(self,
            'Scope Widening Injection detected: The definition "{0}" references '
            'the service "{1}" which belongs to a narrower scope. Generally, it '
            'is safer to either move "{2}" to scope "{3}" or alternatively rely '
            'on the provider pattern by injecting the container itself, and '
            'requesting the service "{4}" each time it is needed. In rare, '
            'special cases however that might not be necessary, then you can '
            'set the reference to strict=False to get rid of this error.'
            ''.format(
           sourceServiceId,
           destServiceId,
           sourceServiceId,
           destScope,
           destServiceId
        ));

        self.__sourceServiceId = None;
        self.__sourceScope = None;
        self.__destServiceId = None;
        self.__destScope = None;

        self.__sourceServiceId = sourceServiceId;
        self.__sourceScope = sourceScope;
        self.__destServiceId = destServiceId;
        self.__destScope = destScope;
Beispiel #4
0
    def __init__(self, sourceServiceId, sourceScope, destServiceId, destScope):

        RuntimeException.__init__(self,
            'Scope Crossing Injection detected: The definition "{0}" references '
            'the service "{1}" which belongs to another scope hierarchy. '
            'This service might not be available consistently. Generally, it '
            'is safer to either move the definition "{2}" to scope "{3}", or '
            'declare "{4}" as a child scope of "{5}". If you can be sure that '
            'the other scope is always active, you can set the reference to '
            'strict=False to get rid of this error.'.format(
           sourceServiceId,
           destServiceId,
           sourceServiceId,
           destScope,
           sourceScope,
           destScope
        ));

        self.__sourceServiceId = None;
        self.__sourceScope = None;
        self.__destServiceId = None;
        self.__destScope = None;
    
        self.__sourceServiceId = sourceServiceId;
        self.__sourceScope = sourceScope;
        self.__destServiceId = destServiceId;
        self.__destScope = destScope;
Beispiel #5
0
    def __init__(self, statusCode, message = None, previous = None, code = 0):

        self.__statusCode = None;

        self.__statusCode = statusCode;

        RuntimeException.__init__(self, message, code, previous);
Beispiel #6
0
    def _getNodeClass(self, nodeType):
        """Returns the class name of the node definition.

        @param nodeType: string The node type

        @return: string The node definition class name

        @raise RuntimeException: When the node type is not registered
        @raise RuntimeException: When the node class is not found
        """
        nodeType = str(nodeType).lower();

        if nodeType not in self._nodeMapping:
            raise RuntimeException(
                'The node type "{0}" is not registered.'
                ''.format(nodeType)
            );

        nodeClass = self._nodeMapping[nodeType];

        if not ReflectionClass(nodeClass).exists():
            raise RuntimeException(
                'The node class "{0}" does not exist.'.format(nodeClass)
            );

        return nodeClass;
Beispiel #7
0
    def __init__(self, message, parsedLine = -1, snippet = None, parsedFile = None, previous = None):
        """Constructor.

        @param: string    message    The error message
        @param integer   parsedLine The line where the error occurred
        @param integer   snippet    The snippet of code near the problem
        @param string    parsedFile The file name where the error occurred
        @param Exception previous   The previous exception

        """
        if previous:
            assert isinstance(previous, Exception);

        self.__parsedFile = None;
        self.__parsedLine = None;
        self.__snippet = None;
        self.__rawMessage = None;


        self.__parsedFile = parsedFile;
        self.__parsedLine = parsedLine;
        self.__snippet = snippet;
        self.__rawMessage = message;

        self.__updateRepr();

        RuntimeException.__init__(self, self._message, 0, previous);
Beispiel #8
0
    def __init__(self, parameters):
        RuntimeException.__init__(
            self,
            'Circular reference detected for parameter "{0}" ("{1}" > "{2}").'.
            format(parameters[0], '" > "'.join(parameters), parameters[0]))

        self.__parameters = parameters
Beispiel #9
0
    def end(self):
        """Returns the related node

        @return: NodeDefinition

        @raise RuntimeException:
        """
        if self.ifPart is None:
            raise RuntimeException('You must specify an if part.');
        if self.thenPart is None:
            raise RuntimeException('You must specify a then part.');
        return self._node;
Beispiel #10
0
    def __init__(self, serviceId, path):
        assert isinstance(path, list)

        RuntimeException.__init__(
            self, 'Circular reference detected for service "{0}", path: "{1}".'
            ''.format(serviceId, ' -> '.join(path)))

        self.__serviceId = None
        self.__path = None

        self.__serviceId = serviceId
        self.__path = path
Beispiel #11
0
    def __init__(self, serviceId, path):
        assert isinstance(path, list);

        RuntimeException.__init__(self,
            'Circular reference detected for service "{0}", path: "{1}".'
            ''.format(serviceId, ' -> '.join(path)
        ));

        self.__serviceId = None;
        self.__path = None;


        self.__serviceId = serviceId;
        self.__path = path;
Beispiel #12
0
    def _buildContainer(self):
        resouces = {
            'cache': self.getCacheDir(),
            'logs': self.getLogDir(),
        }
        for name, path in resouces.items():
            if not os.path.isdir(path):
                try:
                    os.makedirs(path, 0o777)
                except Exception:
                    raise RuntimeException(
                        "Unable to create the {0} directory ({1})\n"
                        "".format(name, path))
            elif not os.access(path, os.W_OK):
                raise RuntimeException(
                    "Unable to write in the {0} directory ({1})\n"
                    "".format(name, path))

        container = self._getContainerBuilder()
        extensions = list()

        container.addObjectResource(self)

        for bundle in self._bundles.values():
            extension = bundle.getContainerExtension()
            if extension:
                container.registerExtension(extension)
                extensions.append(extension.getAlias())

            if self._debug:
                container.addObjectResource(bundle)

        for bundle in self._bundles.values():
            bundle.build(container)

        container.addObjectResource(self)

        # ensure these extensions are implicitly loaded
        container.getCompilerPassConfig().setMergePass(
            MergeExtensionConfigurationPass(extensions))

        cont = self.registerContainerConfiguration(
            self._getContainerLoader(container))
        if not cont is None:
            container.merge(cont)

        container.compile()

        return container
Beispiel #13
0
    def _writeCacheFile(self, filename, content):

        try:
            suffix = 0
            while os.path.exists(filename + str(suffix)):
                suffix += 1
            tmpFile = filename + str(suffix)
            f = open(tmpFile, 'w')
            f.write(content)
            f.close()
            if os.path.exists(filename):
                os.remove(filename)
            os.rename(tmpFile, filename)
            if hasattr(os, 'chmod'):
                umask = os.umask(0o220)
                os.umask(umask)
                os.chmod(filename, 0o666 & ~umask)
        except Exception:
            raise RuntimeException(
                'Failed to write cache file "{0}".'.format(filename))
        else:
            try:
                if hasattr(os, 'chmod'):
                    umask = os.umask(0o220)
                    os.umask(umask)
                    os.chmod(filename, 0o666 & ~umask)
            except Exception:
                pass
        finally:
            try:
                f.close()
            except Exception:
                pass
            if os.path.exists(tmpFile):
                os.remove(tmpFile)
Beispiel #14
0
    def clearAction(self, _o_no_warmup, _o_no_optional_warmers, response):
        assert isinstance(response, Response)

        realCacheDir = self._container.getParameter('kernel.cache_dir')
        oldCacheDir = realCacheDir + '_old'

        if not os.access(realCacheDir, os.W_OK):
            raise RuntimeException(
                'Unable to write in the "{0}" directory'.format(realCacheDir))

        shutil.rmtree(oldCacheDir, True)

        kernel = self._container.get('kernel')
        response.writeln(
            'Clearing the cache for the <info>{0}</info> environment with debug <info>{1}</info>'
            .format(kernel.getEnvironment(), kernel.isDebug()))
        self._container.get('cache_clearer').clear(realCacheDir)

        if os.path.isdir(realCacheDir):
            shutil.copytree(realCacheDir, oldCacheDir, symlinks=True)
            shutil.rmtree(realCacheDir)

        if not _o_no_warmup:
            self._warmup(realCacheDir, not _o_no_optional_warmers)

        shutil.rmtree(oldCacheDir, True)

        return response
Beispiel #15
0
    def _doWrite(self, message, newline):
        """Writes a message to the output.

        @param string  message A message to write to the output
        @param Boolean newline Whether to add a newline or not

        @raise RuntimeException When unable to write output (should never happen)

        """

        if newline:
            text = message + os.linesep;
        else:
            text = message;

        try:
            self.__stream.write(text);
        except TypeError:
            self.__stream.write(text.encode());
        except IOError:
            # @codeCoverageIgnoreStart
            # should never happen
            raise RuntimeException('Unable to write output.');
            # @codeCoverageIgnoreEnd


        self.__stream.flush();
    def getScopedFooService(self):

        if 'foo' not in self._scopedServices:
            raise RuntimeException('Invalid call')

        self._services['scoped_foo'] = self._scopedServices['foo'][
            'scoped_foo'] = Object()
        return self._services['scoped_foo']
Beispiel #17
0
    def buildTree(self):
        """Builds the tree.

        @return: NodeInterface

        @raise RuntimeException: When the configuration tree has no root node.
        """
        if self._root is None:
            raise RuntimeException('The configuration tree has no root node.');
        if not self._tree is None:
            return self._tree;

        self._tree = self._root.getNode(True);
        return self._tree;
Beispiel #18
0
    def _instantiateNode(self):
        """Instantiate a Node

        @return EnumNode The node

        @raise RuntimeException

        """

        if (None is self.__values) :
            raise RuntimeException('You must call .values() on enum nodes.');


        return EnumNode(self._name, self._parent, self.__values);
Beispiel #19
0
    def __init__(self, sourceServiceId, sourceScope, destServiceId, destScope):

        RuntimeException.__init__(
            self,
            'Scope Crossing Injection detected: The definition "{0}" references '
            'the service "{1}" which belongs to another scope hierarchy. '
            'This service might not be available consistently. Generally, it '
            'is safer to either move the definition "{2}" to scope "{3}", or '
            'declare "{4}" as a child scope of "{5}". If you can be sure that '
            'the other scope is always active, you can set the reference to '
            'strict=False to get rid of this error.'.format(
                sourceServiceId, destServiceId, sourceServiceId, destScope,
                sourceScope, destScope))

        self.__sourceServiceId = None
        self.__sourceScope = None
        self.__destServiceId = None
        self.__destScope = None

        self.__sourceServiceId = sourceServiceId
        self.__sourceScope = sourceScope
        self.__destServiceId = destServiceId
        self.__destScope = destScope
Beispiel #20
0
    def __init__(self, sourceServiceId, sourceScope, destServiceId, destScope):

        RuntimeException.__init__(
            self,
            'Scope Widening Injection detected: The definition "{0}" references '
            'the service "{1}" which belongs to a narrower scope. Generally, it '
            'is safer to either move "{2}" to scope "{3}" or alternatively rely '
            'on the provider pattern by injecting the container itself, and '
            'requesting the service "{4}" each time it is needed. In rare, '
            'special cases however that might not be necessary, then you can '
            'set the reference to strict=False to get rid of this error.'
            ''.format(sourceServiceId, destServiceId, sourceServiceId,
                      destScope, destServiceId))

        self.__sourceServiceId = None
        self.__sourceScope = None
        self.__destServiceId = None
        self.__destScope = None

        self.__sourceServiceId = sourceServiceId
        self.__sourceScope = sourceScope
        self.__destServiceId = destServiceId
        self.__destScope = destScope
Beispiel #21
0
    def _mergeValues(self, leftSide, rightSide):
        """Merges values together.

        @param leftSide:  mixed The left side to merge.
        @param rightSide: mixed The right side to merge.

        @return: mixed The merged values

        @rasie InvalidConfigurationException:
        @rasie RuntimeException:

        """
        if rightSide is False:
            # if this is still false after the last config has been merged the
            # finalization pass will take care of removing this key entirely
            return False

        if not leftSide or not self._performDeepMerging:
            return rightSide

        if isinstance(rightSide, list):
            rightSide = Array.toDict(rightSide)

        for k, v in rightSide.items():
            # no conflict
            if k not in leftSide:
                if not self._allowNewKeys:
                    ex = InvalidConfigurationException(
                        'You are not allowed to define new elements for path '
                        '"{0}". Please define all elements for this path in '
                        'one config file. If you are trying to overwrite an '
                        'element, make sure you redefine it with the same '
                        'name.'.format(self.getPath()))
                    ex.setPath(self.getPath())
                    raise ex

                leftSide[k] = v
                continue

            if k not in self._children:
                raise RuntimeException(
                    'merge() expects a normalized config array.')

            leftSide[k] = self._children[k].merge(leftSide[k], v)

        return leftSide
Beispiel #22
0
    def getDefaultValue(self):
        """Retrieves the default value.

        @return: dict The default value

        @raise RuntimeException: if the node has no default value
        """
        if not self.hasDefaultValue():
            raise RuntimeException(
                'The node at path "{0}" has no default value.'
                ''.format(self.getPath()))

        default = dict()
        for name, child in self._children.items():
            if child.hasDefaultValue():
                default[name] = child.getDefaultValue()

        return default
Beispiel #23
0
    def _doGetArguments(self, request, controller, parameters, response):
        assert isinstance(request, Request)
        assert isinstance(parameters, list)
        assert isinstance(response, Response)

        attributes = request.attributes.all()
        arguments = list()

        for param in parameters:
            assert isinstance(param, ReflectionParameter)
            name = param.getName()
            attr = name
            # strip option prefix
            if name.startswith(self.PREFIX_OPTION):
                attr = attr[len(self.PREFIX_OPTION):]

                attr = attr.replace('_', '-')

                if attr.startswith('-'):
                    attr = '_' + attr[1:]

            arg = [name, attr]

            if arg[0] == 'request':
                arguments.append(request)
            elif arg[0] == 'response':
                arguments.append(response)
            elif arg[1] in attributes:
                arguments.append(attributes[arg[1]])
            elif request.hasOption(arg[1]):
                arguments.append(request.getOption(arg[1]))
            elif param.isDefaultValueAvailable():
                arguments.append(param.getDefaultValue())
            else:
                raise RuntimeException(
                    'Controller "{0}" requires that you provide a value for '
                    'the "{1}" argument (because there is no default value or '
                    'because there is a non optional argument after this one).'
                    ''.format(repr(controller), name))

        return arguments
Beispiel #24
0
    def locateResource(self, name, directory=None, first=True):
        """Returns the file path for a given resource.

        A Resource can be a file or a directory.
        The resource name must follow the following pattern:
            @BundleName/path/to/a/file.something
        where package is the name of the package
        and the remaining part is the relative path in the package.

        If directory is passed, and the first segment of the path is Resources,
        this method will look for a file named:
            directory/BundleName/path/without/Resources

        If BundleName is empty the application root directory is use.
            %kernel.root_dir%/path/to/a/file.something

        @param name: string A resource name to locate
        @param path: string A directory where to look for the resource first
        @param first: Boolean Whether to return the first path
            or paths for all matching bundles

        @return: string|array The absolute path of the resource
            or an array if $first is false

        @raise InvalidArgumentException: if the file cannot be found or
            the name is not valid
        @raise RuntimeException: if the name contains invalid/unsafe characters
        """
        name = str(name)
        isResource = False

        if not name.startswith("@"):
            raise InvalidArgumentException(
                'A resource name must start with @ ("{0}" given).'
                "".format(name))

        if ".." in name:
            raise RuntimeException(
                'File name "{0}" contains invalid characters (..).'
                "".format(name))

        bundleName = name[1:]
        if "/" in bundleName:
            bundleName, path = bundleName.split("/", 1)

        if path.startswith("Resources") and directory:
            isResource = True
        overridePath = path[10:]
        resourceBundle = None
        files = []

        if bundleName:
            bundles = self.getBundle(bundleName, False)
            for bundle in bundles:
                if isResource:
                    filename = os.path.join(directory, bundle.getName(),
                                            overridePath)
                    if os.path.exists(filename):
                        if resourceBundle:
                            raise RuntimeException(
                                '"{0}" resource is hidden by a resource from '
                                'the "{1}" derived bundle. Create a "{2}" '
                                'file to override the bundle resource.'
                                ''.format(
                                    filename, resourceBundle, directory + '/' +
                                    bundles[0].getName() + '/' + overridePath))
                        if first:
                            return filename
                        files.append(filename)

                filename = os.path.join(bundle.getPath(), path)
                if os.path.exists(filename):
                    if first and not isResource:
                        return filename
                    files.append(filename)
                    resourceBundle = bundle.getName()

        else:
            # check in root_dir when bundle name is empty
            if isResource:
                filename = os.path.join(directory, overridePath)
            else:
                filename = os.path.join(self._rootDir, path)
            if os.path.exists(filename):
                if first and not isResource:
                    return filename
                files.append(filename)

        if files:
            if first and isResource:
                return files[0]
            else:
                return files

        raise InvalidArgumentException(
            'Unable to find file "{0}".'.format(name))
Beispiel #25
0
    def write(self, content, metadata=None):
        """Writes cache.

        @param string              content  The content to write in the cache
        @param ResourceInterface[] metadata An array of ResourceInterface instances

        @raise RuntimeException When cache file can't be wrote

        """
        assert isinstance(metadata, list) or metadata is None

        dirname = os.path.dirname(self.__file)
        if not os.path.isdir(dirname):
            try:
                os.makedirs(dirname, 0o777)
            except os.error:
                raise RuntimeException(
                    'Unable to create the {0} directory'.format(dirname))

        elif not os.access(dirname, os.W_OK):
            raise RuntimeException(
                'Unable to write in the {0} directory'.format(dirname))

        try:
            suffix = 0
            while os.path.exists(self.__file + str(suffix)):
                suffix += 1
            tmpFile = self.__file + str(suffix)
            f = open(tmpFile, 'w')
            f.write(content)
            f.close()
            if os.path.exists(self.__file):
                os.remove(self.__file)
            os.rename(tmpFile, self.__file)
            if hasattr(os, 'chmod'):
                umask = os.umask(0o220)
                os.umask(umask)
                os.chmod(self.__file, 0o666 & ~umask)
        except Exception:
            raise RuntimeException('Failed to write cache file "{0}".'.format(
                self.__file))
        else:
            try:
                if hasattr(os, 'chmod'):
                    umask = os.umask(0o220)
                    os.umask(umask)
                    os.chmod(self.__file, 0o666 & ~umask)
            except Exception:
                pass
        finally:
            try:
                f.close()
            except Exception:
                pass
            if os.path.exists(tmpFile):
                os.remove(tmpFile)

        if None is not metadata and True is self.__debug:
            filename = self.__file + '.meta'
            content = serialize(metadata)

            try:
                suffix = 0
                while os.path.exists(filename + str(suffix)):
                    suffix += 1
                tmpFile = filename + str(suffix)
                f = open(tmpFile, 'w')
                f.write(content)
                f.close()
                if os.path.exists(filename):
                    os.remove(filename)
                os.rename(tmpFile, filename)
            except Exception:
                pass
            else:
                try:
                    if hasattr(os, 'chmod'):
                        umask = os.umask(0o220)
                        os.umask(umask)
                        os.chmod(filename, 0o666 & ~umask)
                except Exception:
                    pass
            finally:
                try:
                    f.close()
                except Exception:
                    pass
                if os.path.exists(tmpFile):
                    os.remove(tmpFile)
Beispiel #26
0
    def __init__(self, parameters):
        RuntimeException.__init__(self, 'Circular reference detected for parameter "{0}" ("{1}" > "{2}").'.format(parameters[0], '" > "'.join(parameters), parameters[0]));

        self.__parameters = parameters;