Пример #1
0
    def startElementNS(self, ns_and_name, qname, attrs):

        ns, name = ns_and_name
        if ns == nevow.namespace:
            if name == 'invisible':
                name = ''
            elif name == 'slot':
                el = slot(attrs[(None, 'name')])
                self.stack.append(el)
                self.current.append(el)
                self.current = el.children
                return

        attrs = dict(attrs)
        specials = {}
        attributes = self.attributeList
        directives = self.directiveMapping
        for k, v in attrs.items():
            att_ns, nons = k
            if att_ns != nevow.namespace:
                continue
            if nons in directives:
                ## clean this up by making the names more consistent
                specials[directives[nons]] = directive(v)
                del attrs[k]
            if nons in attributes:
                specials[nons] = v
                del attrs[k]

        no_ns_attrs = {}
        for (attrNs, attrName), v in attrs.items():
            nsPrefix = self.prefixMap.get(attrNs)
            if nsPrefix is None:
                no_ns_attrs[attrName] = v
            else:
                no_ns_attrs['%s:%s' % (nsPrefix, attrName)] = v

        if ns == nevow.namespace and name == 'attr':
            if not self.stack:
                # TODO: define a better exception for this?
                raise AssertionError('<nevow:attr> as top-level element')
            if 'name' not in no_ns_attrs:
                # TODO: same here
                raise AssertionError('<nevow:attr> requires a name attribute')
            el = Tag('', specials=specials)
            self.stack[-1].attributes[no_ns_attrs['name']] = el
            self.stack.append(el)
            self.current = el.children
            return

        # Apply any xmlns attributes
        if self.xmlnsAttrs:
            no_ns_attrs.update(dict(self.xmlnsAttrs))
            self.xmlnsAttrs = []

        el = Tag(name, attributes=dict(no_ns_attrs), specials=specials)
        self.stack.append(el)
        self.current.append(el)
        self.current = el.children
Пример #2
0
def term(t):
    """stan xml node for the given rdflib term"""
    if isinstance(t, URIRef):
        return Tag("uri")[t]
    elif isinstance(t, Literal):
        ret = Tag("literal")[t]
        if t.datatype is not None:
            ret.attributes['datatype'] = t.datatype
        return ret
    elif isinstance(t, BNode):
        return Tag("bnode")[t]
    else:
        raise TypeError("unknown term type %r" % t)
Пример #3
0
def term(t):
    """stan xml node for the given rdflib term"""
    if isinstance(t, URIRef):
        return Tag("uri")[t]
    elif isinstance(t, Literal):
        ret = Tag("literal")[t]
        if t.datatype is not None:
            ret.attributes['datatype'] = t.datatype
        return ret
    elif isinstance(t, BNode):
        return Tag("bnode")[t]
    else:
        raise TypeError("unknown term type %r" % t)
Пример #4
0
def canvas(width, height, delegate, useCGI=False):
    C = cookie()
    if useCGI:
        global _canvasCGIService
        if _canvasCGIService is None:
            from nevow import appserver
            from twisted.internet import reactor
            _canvasCGIService = reactor.listenTCP(
                0, appserver.NevowSite(Canvas(docFactory=canvasServerMessage)))
            _canvasCGIService.dispatchMap = {}
        port = _canvasCGIService.getHost().port
        prefix = '/'
        movie_url = url.here.click('/').secure(False, port)
    else:
        movie_url = url.here
        port = lambda c, d: inevow.IRequest(c).transport.server.port

        def prefix(c, d):
            pre = inevow.IRequest(c).path
            if pre.endswith('/'):
                return pre
            return pre + '/'

    _hookup[C] = delegate
    handlerInfo = []
    for handlerName in [
            'onMouseMove', 'onMouseDown', 'onMouseUp', 'onKeyDown', 'onKeyUp'
    ]:
        if getattr(delegate, handlerName, None) is not None:
            handlerInfo.append((handlerName, 1))

    movie_url = movie_url.child('nevow_canvas_movie.swf').add('cookie', C).add(
        'port', port).add('prefix', prefix)
    for (k, v) in handlerInfo:
        movie_url = movie_url.add(k, v)

    return tags._object(
        classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000",
        codebase=
        "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0",
        width=width,
        height=height,
        id=("Canvas-", C),
        align="middle"
    )[tags.param(name="allowScriptAccess", value="sameDomain"),
      tags.param(name="movie", value=movie_url),
      tags.param(name="quality", value="high"),
      tags.param(name="scale", value="noscale"),
      tags.param(name="bgcolor", value="#ffffff"),
      Tag('embed')(src=movie_url,
                   quality="high",
                   scale="noscale",
                   bgcolor="#ffffff",
                   width=width,
                   height=height,
                   name=("Canvas-", C),
                   align="middle",
                   allowScriptAccess="sameDomain",
                   type="application/x-shockwave-flash",
                   pluginspage="http://www.macromedia.com/go/getflashplayer")]
Пример #5
0
def MicroDomElementSerializer(element, context):
    directiveMapping = {
        'render': 'render',
        'data': 'data',
        'macro': 'macro',
    }
    attributeList = [
        'pattern',
        'key',
    ]

    name = element.tagName
    if name.startswith('nevow:'):
        _, name = name.split(':')
        if name == 'invisible':
            name = ''
        elif name == 'slot':
            return slot(element.attributes['name'])[precompile(
                serialize(element.childNodes, context), context)]

    attrs = dict(element.attributes)  # get rid of CaseInsensitiveDict
    specials = {}
    attributes = attributeList
    directives = directiveMapping
    for k, v in list(attrs.items()):
        # I know, this is totally not the way to do xml namespaces but who cares right now
        ## I'll fix it later -dp
        ### no you won't *I'll* fix it later -glyph
        if isinstance(k, tuple):
            if k[0] != 'http://nevow.com/ns/nevow/0.1':
                continue
            else:
                nons = k[1]
        elif not k.startswith('nevow:'):
            continue
        else:
            _, nons = k.split(':')
        if nons in directives:
            ## clean this up by making the names more consistent
            specials[directives[nons]] = directive(v)
            del attrs[k]
        if nons in attributes:
            specials[nons] = v
            del attrs[k]

    # TODO: there must be a better way than this ...
    # Handle any nevow:attr elements. If we don't do it now then this tag will
    # be serialised and it will too late.
    childNodes = []
    for child in element.childNodes:
        if getattr(child, 'tagName', None) == 'nevow:attr':
            attrs[child.attributes['name']] = child.childNodes
        else:
            childNodes.append(child)

    tag = Tag(name, attributes=attrs, children=childNodes, specials=specials)

    return serialize(tag, context)
Пример #6
0
def xmlResults(resultRows):
    """xml text for a list of sparql results. These rows are a list of
    dicts with variable names as keys, rdflib objects as values.

    Values of None, as rdflib returns if your selection variable
    doesn't appear in your query, are omitted. For example, running this:

       SELECT ?x ?unused { ?x :y :z}

    will return bindings for ?x only, just as if you never included
    ?unused. The sparql engine should probably error on that case, in
    which case this handler will stop getting used.

    But note that if there was an OPTIONAL { ?unused ... } in the
    query, then there's no error but some rows won't get a
    <binding>. See _addOptionalVars in remotegraph.py.

    This is the inverse of parseSparqlResults.
    """
    # this is redundant with a version in rdflib already, although
    # mine uses a default xml namespace that saves quite a few bytes

    # in one test, getQuery spends 27% in queryd and 71% in this function!

    return '<?xml version="1.0"?>\n' + flat.flatten(
        Tag("sparql")(xmlns=RESULTS_NS)
        [Tag("head")[Tag("variable")(name="notimplemented")],
         Tag("results")(ordered="notimplemented", distinct="notimplemented")[
             (Tag("result")[(Tag("binding")(name=k)[term(v)]
                             for k, v in row.items() if v is not None)]
              for row in resultRows)]])
Пример #7
0
 def __call__(self, *args, **kw):
     for a in args:
         if isinstance(a, PrimaryNamespace):
             self.attributes['xmlns'] = a.uri
         elif isinstance(a, TagNamespace):
             self.attributes['xmlns:'+a.namespace] = a.uri
             
     for k,v in kw.items():
         if isinstance(v, PrimaryNamespace):
             self.attributes['xmlns'] = v.uri
         elif isinstance(v, TagNamespace):
             self.attributes['xmlns:'+k] = v.uri
             v.namespace = k
             del kw[k]
             
     return Tag.__call__(self, **kw)
Пример #8
0
    def startElementNS(self, ns_and_name, qname, attrs):

        filename = self.sourceFilename
        lineNumber = self.locator.getLineNumber()
        columnNumber = self.locator.getColumnNumber()

        ns, name = ns_and_name
        if ns == nevow.namespace:
            if name == 'invisible':
                name = ''
            elif name == 'slot':
                try:
                    # Try to get the default value for the slot
                    default = attrs[(None, 'default')]
                except KeyError:
                    # If there wasn't one, then use None to indicate no
                    # default.
                    default = None
                el = slot(
                    attrs[(None, 'name')], default=default,
                    filename=filename, lineNumber=lineNumber,
                    columnNumber=columnNumber)
                self.stack.append(el)
                self.current.append(el)
                self.current = el.children
                return

        attrs = dict(attrs)
        specials = {}
        attributes = self.attributeList
        directives = self.directiveMapping
        for k, v in list(attrs.items()):
            att_ns, nons = k
            if att_ns != nevow.namespace:
                continue
            if nons in directives:
                ## clean this up by making the names more consistent
                specials[directives[nons]] = directive(v)
                del attrs[k]
            if nons in attributes:
                specials[nons] = v
                del attrs[k]

        no_ns_attrs = {}
        for (attrNs, attrName), v in list(attrs.items()):
            nsPrefix = self.prefixMap.get(attrNs)
            if nsPrefix is None:
                no_ns_attrs[attrName] = v
            else:
                no_ns_attrs['%s:%s'%(nsPrefix,attrName)] = v

        if ns == nevow.namespace and name == 'attr':
            if not self.stack:
                # TODO: define a better exception for this?
                raise AssertionError( '<nevow:attr> as top-level element' )
            if 'name' not in no_ns_attrs:
                # TODO: same here
                raise AssertionError( '<nevow:attr> requires a name attribute' )
            el = Tag('', specials=specials, filename=filename,
                     lineNumber=lineNumber, columnNumber=columnNumber)
            self.stack[-1].attributes[no_ns_attrs['name']] = el
            self.stack.append(el)
            self.current = el.children
            return

        # Apply any xmlns attributes
        if self.xmlnsAttrs:
            no_ns_attrs.update(dict(self.xmlnsAttrs))
            self.xmlnsAttrs = []

        # Add the prefix that was used in the parsed template for non-Nevow
        # namespaces (which Nevow will consume anyway).
        if ns != nevow.namespace and ns is not None:
            prefix = self.prefixMap[ns]
            if prefix is not None:
                name = '%s:%s' % (self.prefixMap[ns],name)
        el = Tag(
            name, attributes=dict(no_ns_attrs), specials=specials,
            filename=filename, lineNumber=lineNumber,
            columnNumber=columnNumber)
        self.stack.append(el)
        self.current.append(el)
        self.current = el.children
Пример #9
0
def xmlCountResults(count):
    """a made-up format for count query results"""
    return '<?xml version="1.0"?>\n' + flat.flatten(
        Tag("sparql")(xmlns=RESULTS_NS, **{
            'xmlns:ext': EXTENDED_NS
        })[Tag("results")[Tag("ext:count")[count], ]])