def Sum(context, nodeSet):
    """Function: <number> sum(<node-set>)"""
    if not isinstance(nodeSet, NodesetType):
        raise RuntimeException(RuntimeException.WRONG_ARGUMENTS, 'sum',
                               _("expected node-set argument"))
    nns = map(Conversions.NumberValue, nodeSet)
    return reduce(lambda x, y: x + y, nns, 0)
class NMToken(AttributeInfo):
    display = _('nmtoken')

    def prepare(self, element, value):
        if value is None:
            return self.default
        if not value:
            raise XsltException(Error.INVALID_NMTOKEN_ATTR, value)
        return value
    reprocess = prepare
class Number(AttributeInfo):
    display = _('number')

    def prepare(self, element, value):
        if value is None:
            return self.default
        try:
            return float(value or self.default)
        except:
            raise XsltException(Error.INVALID_NUMBER_ATTR, value)
    reprocess = prepare
class NCName(AttributeInfo):
    display = _('ncname')

    def prepare(self, element, value):
        if value is None:
            return self.default
        if not value:
            raise XsltException(Error.INVALID_NCNAME_ATTR, value)
        if ':' in value:
            raise XsltException(Error.INVALID_NCNAME_ATTR, value)
        return value
    reprocess = prepare
class Char(AttributeInfo):
    """
    A string value with a length of one
    """
    display = _('char')

    def prepare(self, element, value):
        if value is None:
            return self.default
        if len(value) > 1:
            raise XsltException(Error.INVALID_CHAR_ATTR, value)
        return value
    reprocess = prepare
class Prefix(AttributeInfo):
    display = _('prefix')

    def prepare(self, element, value):
        if value is None:
            return self.default
        if not value:
            raise XsltException(Error.INVALID_PREFIX_ATTR, value)
        if ':' in value:
            raise XsltException(Error.INVALID_PREFIX_ATTR, value)
        if value == '#default':
            value = None
        return value
    reprocess = prepare
class UriReference(AttributeInfo):
    display = _('uri-reference')

    def __init__(self, required=0, default=None, description='', isNsName=0):
        AttributeInfo.__init__(self, required, default, description)
        self._isNsName = isNsName

    def prepare(self, element, value):
        if value is None:
            return self.default
        if self._isNsName and \
            value == XML_NAMESPACE or value == XMLNS_NAMESPACE:
            raise XsltException(Error.INVALID_NS_URIREF_ATTR, value)
        return value
    reprocess = prepare
class Tokens(Token):
    """
    A whitespace separated list of tokens (see Token for description of a token)
    """
    display = _('tokens')

    def prepare(self, element, value):
        if value is None:
            return []
        tokens = []
        for token in value.split():
            prepared = Token.prepare(self, element, token)
            tokens.append(prepared)
        return tokens
    reprocess = prepare
class QNames(QName):
    """
    A whitespace separated list of qnames (see QName for description of a qname)
    """
    display = _('qnames')

    def prepare(self, element, value):
        if value is None:
            return []
        qnames = []
        for qname in value.split():
            prepared = QName.prepare(self, element, qname)
            qnames.append(prepared)
        return qnames
    reprocess = prepare
Beispiel #10
0
class Prefixes(Prefix):
    """
    A whitespace separated list of prefixes (see Prefix for more information)
    """
    display = _('prefixes')

    def prepare(self, element, value):
        if value is None:
            return []
        prefixes = []
        for prefix in value.split():
            prepared = Prefix.prepare(self, element, prefix)
            prefixes.append(prepared)
        return prefixes
    reprocess = prepare
Beispiel #11
0
class Expression(AttributeInfo):
    """
    An attribute whose value is used as an XPath expression
    """
    display = _('expression')

    def prepare(self, element, value):
        if value is None:
            if self.default is None:
                return None
            value = self.default
        try:
            expression = _xpath_parser.parse(value)
        except SyntaxError, error:
            raise XsltException(Error.INVALID_EXPRESSION, value,
                                element.baseUri, element.lineNumber,
                                element.columnNumber, str(error))
        return ExpressionWrapper(expression, element, value)
Beispiel #12
0
class Pattern(AttributeInfo):
    """
    An attribute whose value is used as an XPattern expression
    """
    display = _('pattern')

    def prepare(self, element, value):
        if value is None:
            if self.default:
                value = self.default
            else:
                return None
        try:
            return _xpattern_parser.parse(value)
        except SyntaxError, error:
            raise XsltException(Error.INVALID_PATTERN, value,
                                element.baseUri, element.lineNumber,
                                element.columnNumber, str(error))
Beispiel #13
0
def NamespaceUri(context, nodeSet=None):
    """Function: <string> namespace-uri(<node-set>?)"""
    if nodeSet is None:
        node = context.node
    elif not isinstance(nodeSet, NodesetType):
        raise RuntimeException(RuntimeException.WRONG_ARGUMENTS,
                               'namespace-uri', _("expected node-set"))
    elif not nodeSet:
        return u''
    else:
        nodeSet.sort()
        node = nodeSet[0]

    # only elements and attributes have a namespace-uri
    node_type = getattr(node, 'nodeType', None)
    if node_type in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
        return node.namespaceURI or u''
    return u''
Beispiel #14
0
class QName(AttributeInfo):
    display = _('qname')

    def prepare(self, element, value):
        if value is None:
            if self.default is None:
                return None
            value = self.default
        elif not IsQName(value):
            raise XsltException(Error.INVALID_QNAME_ATTR, value)

        prefix, local = SplitQName(value)
        if prefix:
            try:
                namespace = element.namespaces[prefix]
            except KeyError:
                raise XsltRuntimeException(Error.UNDEFINED_PREFIX,
                                           element, prefix)
        else:
            namespace = EMPTY_NAMESPACE
        return (namespace, local)
    reprocess = prepare
Beispiel #15
0
def Name(context, nodeSet=None):
    """Function: <string> name(<node-set>?)"""
    if nodeSet is None:
        node = context.node
    elif not isinstance(nodeSet, NodesetType):
        raise RuntimeException(RuntimeException.WRONG_ARGUMENTS, 'name',
                               _("expected node-set"))
    elif not nodeSet:
        return u''
    else:
        nodeSet.sort()
        node = nodeSet[0]

    node_type = getattr(node, 'nodeType', None)
    if node_type in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
        return node.nodeName
    elif node_type == NAMESPACE_NODE:
        # localName could be null
        return node.localName or u''
    elif node_type == Node.PROCESSING_INSTRUCTION_NODE:
        # target cannot be null
        return node.target
    return u''
Beispiel #16
0
class QNameButNotNCName(AttributeInfo):
    display = _('qname-but-not-ncname')

    def prepare(self, element, value):
        if value is None:
            if self.default is None:
                return None
            value = self.default
        elif not value:
            raise XsltException(Error.QNAME_BUT_NOT_NCNAME, value)

        try:
            index = value.index(':')
        except ValueError:
            raise XsltException(Error.QNAME_BUT_NOT_NCNAME, value)
        prefix, local = value[:index], value[index+1:]
        try:
            namespace = element.namespaces[prefix]
        except KeyError:
            raise XsltRuntimeException(Error.UNDEFINED_PREFIX,
                                       element, prefix)
        return (namespace, local)
    reprocess = prepare
Beispiel #17
0
class Token(AttributeInfo):
    """
    An attribute whose value is used as an XPath NameTest
    """
    display = _('token')

    def prepare(self, element, value):
        # a 'token' is really an XPath NameTest; '*' | NCName ':' '*' | QName
        # From XPath 1.0 section 2.3:
        #  if the QName does not have a prefix, then the namespace URI is null
        index = value.rfind(':')
        if index == -1:
            namespace = None
            local = value
        else:
            prefix = value[:index]
            local = value[index+1:]
            try:
                namespace = element.namespaces[prefix]
            except KeyError:
                raise XsltRuntimeException(Error.UNDEFINED_PREFIX,
                                           element, prefix)
        return (namespace, local)
    reprocess = prepare
Beispiel #18
0
Copyright 2004 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

from Ft import TranslateMessage as _
from Ft.Lib import UriException

# %r preferred for reporting URIs because the URI refs can be empty
# strings or, if invalid, could contain characters unsafe for the error
# message stream.
#
URI = {
    UriException.INVALID_BASE_URI:
    _("Invalid base URI: %(base)r cannot be used to resolve reference %(ref)r"
      ),
    UriException.RELATIVE_BASE_URI:
    _("Invalid base URI: %(base)r cannot be used to resolve reference %(ref)r;"
      " the base URI must be absolute, not relative."),
    UriException.NON_FILE_URI:
    _("Only a 'file' URI can be converted to an OS-specific path; URI given was %r"
      ),
    UriException.UNIX_REMOTE_HOST_FILE_URI:
    _("A URI containing a remote host name cannot be converted to a path on posix;"
      " URI given was %r"),
    UriException.RESOURCE_ERROR:
    _("Error retrieving resource %(loc)r: %(msg)s"),
    UriException.UNSUPPORTED_PLATFORM:
    _("Platform %r not supported by URI function %s"),
    UriException.SCHEME_REQUIRED:
    _("Scheme-based resolution requires a URI with a scheme; "
Beispiel #19
0
    SYNTAX_ERROR = 1
    UNRECOGNIZED_INSTRUCTION = 2
    NO_VERSION = 10
    NO_SELECT = 11
    NO_TEST = 12
    INVALID_SELECT = 13
    UNSUPPORTED_VERSION = 14
    INVALID_DOM_NODE = 100
    UNKNOWN_NODE_TYPE = 101

    def __init__(self, errorCode, *args, **kwargs):
        FtException.__init__(self, errorCode, g_errorMessages, args, **kwargs)


g_errorMessages = {
    XUpdateException.SYNTAX_ERROR: _('Syntax error in expression %(expr)r: %(err)s'),
    XUpdateException.UNRECOGNIZED_INSTRUCTION: _('Unrecognized instruction in XUpdate namespace: %(name)r'),
    XUpdateException.NO_VERSION: _('Missing required version attribute'),
    XUpdateException.NO_SELECT: _('Missing required select attribute'),
    XUpdateException.NO_TEST: _('Missing required "test" attribute'),
    XUpdateException.INVALID_SELECT: _('select expression "%(expr)s" must evaluate to a non-empty node-set'),
    XUpdateException.UNSUPPORTED_VERSION: _('XUpdate version %(version)s unsupported by this implementation'),
    XUpdateException.INVALID_DOM_NODE: _('Invalid DOM node %(node)r'),
    XUpdateException.UNKNOWN_NODE_TYPE: _('Unknown node type %(nodetype)r'),
    }

SUPPORTED_VERSIONS = ('1.0',)

class StringWriter(NullWriter.NullWriter):
    def __init__(self):
        self._result = []
Beispiel #20
0
########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Xml/Xslt/MessageSource.py,v 1.37 2005/04/03 06:47:13 jkloth Exp $
"""
XSLT error codes and messages

Copyright 2003 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

from Ft import TranslateMessage as _

POSITION_INFO = _('In stylesheet %s, line %s, column %s:\n%s')

EXPRESSION_POSITION_INFO = _('In stylesheet %s, line %s, column %s in "%s":\n'
                             '%s')

XSLT_EXPRESSION_POSITION_INFO = _('%s\n'
                                  'The error occurred in the expression "%s".')

BUILTIN_TEMPLATE_WITH_PARAMS = _('Built-in template invoked with params that '
                                 'will be ignored. This message will only '
                                 'appear once per transform.')

TEMPLATE_CONFLICT_LOCATION = _('In stylesheet %s, line %s, column %s, pattern %s')

# for xsl:message output
DEFAULT_MESSAGE_PREFIX = _('STYLESHEET MESSAGE:\n')
DEFAULT_MESSAGE_SUFFIX = _('\nEND STYLESHEET MESSAGE\n')

class Error:
Beispiel #21
0
Copyright 2004 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

from Ft import TranslateMessage as _
from Ft.Lib import UriException

# %r preferred for reporting URIs because the URI refs can be empty
# strings or, if invalid, could contain characters unsafe for the error
# message stream.
#
URI = {
    UriException.INVALID_BASE_URI:
        _("Invalid base URI: %(base)r cannot be used to resolve reference %(ref)r"),
    UriException.RELATIVE_BASE_URI:
        _("Invalid base URI: %(base)r cannot be used to resolve reference %(ref)r;"
          " the base URI must be absolute, not relative."),
    UriException.NON_FILE_URI:
        _("Only a 'file' URI can be converted to an OS-specific path; URI given was %r"),
    UriException.UNIX_REMOTE_HOST_FILE_URI:
        _("A URI containing a remote host name cannot be converted to a path on posix;"
          " URI given was %r"),
    UriException.RESOURCE_ERROR:
        _("Error retrieving resource %(loc)r: %(msg)s"),
    UriException.UNSUPPORTED_PLATFORM:
        _("Platform %r not supported by URI function %s"),
    UriException.SCHEME_REQUIRED:
        _("Scheme-based resolution requires a URI with a scheme; "
          "neither the base URI %(base)r nor the reference %(ref)r have one."),
Beispiel #22
0
Copyright 2003 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

from Ft import TranslateMessage as _

from Ft.Xml.XPath import CompiletimeException, RuntimeException

# messages for expression compile-time errors
ERROR_COMPILETIME = {
    # internal/unexpected errors
    CompiletimeException.INTERNAL: _('There is an internal bug in 4XPath. '
        'Please make a post to the 4Suite mailing list to report this error '
        'message to the developers. Include platform details and info about '
        'how to reproduce the error. Info about the mailing list is at '
        'http://lists.fourthought.com/mailman/listinfo/4suite. '
        'The error code to report is: %s'),
    # other compile-time errors
    CompiletimeException.SYNTAX: _('XPath expression syntax error at line %d, column %d: %s'),
}


# messages for expression evaluation (run-time) errors
ERROR_RUNTIME = {
    # internal/unexpected errors
    RuntimeException.INTERNAL: _('There is an internal bug in 4XPath. '
        'Please make a post to the 4Suite mailing list to report this error '
        'message to the developers. Include platform details and info about '
        'how to reproduce the error. Info about the mailing list is at '
        'http://lists.fourthought.com/mailman/listinfo/4suite. '
Beispiel #23
0
########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Xml/Xslt/MessageSource.py,v 1.37 2005/04/03 06:47:13 jkloth Exp $
"""
XSLT error codes and messages

Copyright 2003 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

from Ft import TranslateMessage as _

POSITION_INFO = _('In stylesheet %s, line %s, column %s:\n%s')

EXPRESSION_POSITION_INFO = _('In stylesheet %s, line %s, column %s in "%s":\n'
                             '%s')

XSLT_EXPRESSION_POSITION_INFO = _('%s\n'
                                  'The error occurred in the expression "%s".')

BUILTIN_TEMPLATE_WITH_PARAMS = _('Built-in template invoked with params that '
                                 'will be ignored. This message will only '
                                 'appear once per transform.')

TEMPLATE_CONFLICT_LOCATION = _(
    'In stylesheet %s, line %s, column %s, pattern %s')

# for xsl:message output
DEFAULT_MESSAGE_PREFIX = _('STYLESHEET MESSAGE:\n')
DEFAULT_MESSAGE_SUFFIX = _('\nEND STYLESHEET MESSAGE\n')
Beispiel #24
0
class Error:

    UNSUPPORTED_DOCUMENT_URI_SCHEME = 3000
    ABORTED_EXSLDOCUMENT_OVERWRITE = 3010
    NO_EXSLTDOCUMENT_BASE_URI = 3020

    ILLEGAL_DURATION_FORMAT = 3100

    RESULT_NOT_IN_FUNCTION = 3200
    ILLEGAL_RESULT_SIBLINGS = 3201


g_exsltErrorMessages = {
    Error.UNSUPPORTED_DOCUMENT_URI_SCHEME:
    _('4Suite\'s implementation of exsl:document only supports an href value having the "file" URI scheme, which may be implicit. Scheme "%s" was found.'
      ),
    Error.ABORTED_EXSLDOCUMENT_OVERWRITE:
    _('An attempt was made to write to %s, which already exists.  The attempt to save the contents of this file to %s also failed, and so the instruction has been aborted.  If you are sure it is OK to overwrite this file, please indicate this by adding the f:overwrite-okay attribute to the exsl:document instruction.'
      ),
    Error.NO_EXSLTDOCUMENT_BASE_URI:
    _('An `exsl:document` element referred to a relative reference "%s", but there is no explicit output document to provide a base URI in order to resolve this relative reference.'
      ),
    Error.ILLEGAL_DURATION_FORMAT:
    _('Duration string "%s" not in xs:duration format.'),
    Error.RESULT_NOT_IN_FUNCTION:
    _('An EXSLT func:result element must occur within a func:function element.'
      ),
    Error.ILLEGAL_RESULT_SIBLINGS:
    _('An EXSLT func:result element must not have following sibling elements besides xsl:fallback.'
      ),
}
Beispiel #25
0
 def __str__(self):
     systemId = self.systemId
     if isinstance(systemId, unicode):
         systemId = systemId.encode('unicode_escape')
     return _("In %s, line %s, column %s: %s") % (
         systemId, self.lineNumber, self.columnNumber, self.message)
Beispiel #26
0
class BooleanExpression(Expression):
    display = _('boolean-expression')
Beispiel #27
0
class AnyAvt(Avt, AttributeInfo):
    display = _('any avt')
Beispiel #28
0
class NumberExpression(Expression):
    display = _('number-expression')
Beispiel #29
0
class StringExpression(Expression):
    display = _('string-expression')
Beispiel #30
0
class NodeSetExpression(Expression):
    display = _('node-set-expression')
Beispiel #31
0
class String(AttributeInfo):
    display = _('string')
Beispiel #32
0
########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Xml/XPointer/MessageSource.py,v 1.3 2004/01/26 07:40:21 jkloth Exp $
"""
XPointer error codes and messages

Copyright 2003 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

from Ft import TranslateMessage as _
from Ft.Xml.XPointer import XPtrException

g_errorMessages = {
    XPtrException.INTERNAL_ERROR : _('There is an internal bug in 4Suite. '
        'Please make a post to the 4Suite mailing list to report this error '
        'message to the developers. Include platform details and info about '
        'how to reproduce the error. Info about the mailing list is at '
        'http://lists.fourthought.com/mailman/listinfo/4suite. '
        'The error code to report is: %s'),
    XPtrException.SYNTAX_ERROR : _("Syntax error in XPointer expression: %s"),
    XPtrException.RESOURCE_ERROR : _("Invalid resource, or not well-formed XML: %s"),
    XPtrException.SUB_RESOURCE_ERROR : _("Expression does not locate a resource"),
    }
Beispiel #33
0
########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Xml/MessageSource.py,v 1.13 2006/02/04 00:06:36 jkloth Exp $
"""
Localizable message strings

Copyright 2005 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

from Ft import TranslateMessage as _
from Ft.Xml import ReaderException, XIncludeException

XINCLUDE = {
    XIncludeException.MISSING_HREF : _('Missing or empty href attribute'),
    XIncludeException.INVALID_PARSE_ATTR : _(
    'Invalid value %r for parse attribute'),
    XIncludeException.TEXT_XPOINTER : _(
    'xpointer attribute forbidden for parse="text"'),
    XIncludeException.FRAGMENT_IDENTIFIER : _(
    'Fragment identifier not allowed in URI %r; use the xpointer attribute'),
    XIncludeException.UNSUPPORTED_XPOINTER : _(
    'Unsupported XPointer %r'),
    XIncludeException.INCLUDE_IN_INCLUDE :_(
    'xi:include has an xi:include child'),
    XIncludeException.FALLBACK_NOT_IN_INCLUDE : _(
    'xi:fallback is not the child of an xi:include'),
    XIncludeException.MULTIPLE_FALLBACKS : _(
    'xi:include with multiple xi:fallback children'),
    }
Beispiel #34
0
from Ft import TranslateMessage as _

# this works around a circular import
from Ft.Xml.Xslt.MessageSource import g_errorMessages

class Error:

    UNSUPPORTED_DOCUMENT_URI_SCHEME = 3000
    ABORTED_EXSLDOCUMENT_OVERWRITE = 3010
    NO_EXSLTDOCUMENT_BASE_URI = 3020

    ILLEGAL_DURATION_FORMAT = 3100

    RESULT_NOT_IN_FUNCTION = 3200
    ILLEGAL_RESULT_SIBLINGS = 3201


g_exsltErrorMessages = {
    Error.UNSUPPORTED_DOCUMENT_URI_SCHEME: _('4Suite\'s implementation of exsl:document only supports an href value having the "file" URI scheme, which may be implicit. Scheme "%s" was found.'),
    Error.ABORTED_EXSLDOCUMENT_OVERWRITE: _('An attempt was made to write to %s, which already exists.  The attempt to save the contents of this file to %s also failed, and so the instruction has been aborted.  If you are sure it is OK to overwrite this file, please indicate this by adding the f:overwrite-okay attribute to the exsl:document instruction.'),
    Error.NO_EXSLTDOCUMENT_BASE_URI: _('An `exsl:document` element referred to a relative reference "%s", but there is no explicit output document to provide a base URI in order to resolve this relative reference.'),
    Error.ILLEGAL_DURATION_FORMAT: _('Duration string "%s" not in xs:duration format.'),
    Error.RESULT_NOT_IN_FUNCTION: _('An EXSLT func:result element must occur within a func:function element.'),
    Error.ILLEGAL_RESULT_SIBLINGS: _('An EXSLT func:result element must not have following sibling elements besides xsl:fallback.'),
}

g_errorMessages.update(g_exsltErrorMessages)