示例#1
0
    def create_zipfile(self, package):
        tmpfile = TemporaryFile()
        BindingDOMSupport.SetDefaultNamespace(u'http://bar.admin.ch/arelda/v4')
        with ZipFile(tmpfile, 'w', ZIP_DEFLATED, True) as zipfile:
            package.write_to_zipfile(zipfile)

        return tmpfile
 def __check_bds(cls, bds):
     if bds:
         return bds
     else:
         return BindingDOMSupport(
             namespace_prefix_map=namespace_prefix_map
         )
示例#3
0
def main():
    create_loggers()
    log.info('Dummy XML Encoder')

    tt = bindings.tt(sequenceIdentifier='testSequence001',
                     sequenceNumber='1',
                     timeBase='smpte',
                     lang='en-GB',
                     head=bindings.head_type(
                         metadata.headMetadata_type(
                             metadata.documentMetadata()),
                         bindings.styling(bindings.style(id='ID001')),
                         bindings.layout()),
                     body=BIND(
                         bindings.div_type(
                             bindings.p_type(
                                 bindings.span_type('Some example text...'),
                                 bindings.br_type(),
                                 bindings.span_type('And another line'),
                                 id='ID005',
                                 begin='00:00:00:50',
                                 end='00:00:03:24',
                             ))))

    print(
        tt.toDOM(bds=BindingDOMSupport(
            default_namespace=bindings.Namespace)).toprettyxml(indent='  '))
    log.info('XML output printed')
示例#4
0
    def __call__(self):
        BindingDOMSupport.SetDefaultNamespace(u'http://bar.admin.ch/arelda/v4')

        package = SIPPackage(self.context)
        tmpfile = self.create_zipfile(package)

        size = tmpfile.tell()
        response = self.request.response
        response.setHeader(
            "Content-Disposition",
            'inline; filename="%s.zip"' % package.get_folder_name())
        response.setHeader("Content-type", "application/zip")
        response.setHeader("Content-Length", size)

        return TempfileStreamIterator(tmpfile, size)
示例#5
0
文件: sdo.py 项目: unicornis/pybrreg
    def element(self):
        """
        Get the PyXB element for frivintVerifisertMelding

        :return: Completed element
        :rtype: :py:class:`pybrreg.xml.generated.frivintVerifisertMelding.SDO`
        """
        BindingDOMSupport.DeclareNamespace(frivintVerifisertMelding.Namespace,
                                           self.ns_prefix)
        elem = frivintVerifisertMelding.SDO()
        elem.SignedObject = self.signed_object
        elem.Signatures = frivintVerifisertMelding.Signatures()
        for signature in self.signatures:
            elem.Signatures.append(signature.element)

        return elem
示例#6
0
 def tearDown(self):
     BindingDOMSupport.Reset(prefix_map=True)
示例#7
0
 def setUp(self):
     BindingDOMSupport.DeclareNamespace(A.Namespace, 'a')
     BindingDOMSupport.DeclareNamespace(B.Namespace, 'b')
示例#8
0
from opengever.ech0147.bindings import ech0058
from opengever.ech0147.bindings import ech0147t0
from opengever.ech0147.bindings import ech0147t1
from opengever.ech0147.mappings import CLASSIFICATION_MAPPING
from opengever.ech0147.mappings import DOSSIER_STATUS_MAPPING
from opengever.ech0147.mappings import PRIVACY_LAYER_MAPPING
from opengever.ech0147.mappings import PUBLIC_TRIAL_MAPPING
from opengever.base.utils import file_checksum
from plone import api
from pyxb.utils.domutils import BindingDOMSupport
from uuid import uuid4

import os.path
import pkg_resources

BindingDOMSupport.DeclareNamespace(ech0147t1.Namespace, 'eCH-0147T1')
BindingDOMSupport.DeclareNamespace(ech0147t0.Namespace, 'eCH-0147T0')
BindingDOMSupport.DeclareNamespace(ech0039.Namespace, 'eCH-0039')
BindingDOMSupport.DeclareNamespace(ech0058.Namespace, 'eCH-0058')


class MessageT1(object):
    """eCH-0147T1 message"""
    def __init__(self):
        self.directive = None
        self.dossiers = []
        self.documents = []
        self.addresses = []

        self.action = 1
        self.test_delivery_flag = False
    def encode(self,
               resource,
               pretty=False,
               encoding="utf-8",
               fields=None,
               attributes_only=False):
        # representation = self.get_representation(resource, fields=fields)

        try:
            id_attribute = resource.id_attribute
        except AttributeError:
            xml = tostring(self._build_elementtree(resource),
                           pretty_print=pretty,
                           encoding=encoding)
            return '<?xml version="1.0" encoding="utf-8"?>' + xml

        representation = {}

        if isinstance(resource, ContentInstance):
            instance = self._encode_contentinstance(resource, fields)
        elif isinstance(resource, MembersContent):
            instance = self._encode_memberscontent(resource, pretty, encoding)
        elif isinstance(resource, Notify):
            instance = self._encode_notify(resource, pretty, encoding)
        else:
            for attr in resource.attributes:
                a_name = attr.name
                if (fields is None or a_name == id_attribute or a_name in fields) \
                        and attr.accesstype is not None:
                    val = getattr(resource, "_" + a_name, None)
                    if val is None:
                        continue
                    if isinstance(attr, ListAttribute):
                        if attr.content_type is AnyURI:
                            representation[a_name] = l = AnyURIList()
                            l.reference = val
                        else:
                            wrappercls = self._get_wrapper_class(a_name)

                            if issubclass(attr.content_type, Entity):
                                valcls = self._get_mapper_class(a_name[:-1])
                                vals = [
                                    self._convert_value(
                                        v, attr.content_type, valcls)
                                    for v in val
                                ]
                            else:
                                vals = val
                            wrapper = wrappercls()
                            setattr(
                                wrapper,
                                wrappercls._ElementMap.keys()[0].localName(),
                                vals)
                            representation[a_name] = wrapper
                    elif isinstance(attr, EntityAttribute):
                        valcls = self._get_mapper_class(
                            attr.type.get_typename())
                        val = self._convert_value(val, attr.type, valcls)
                        representation[a_name] = val
                    else:
                        try:
                            val = val.isoformat()
                        except AttributeError:
                            pass
                        representation[a_name] = val

            if fields is None and not attributes_only:
                path = resource.path
                for sr in resource.subresources:
                    representation[sr.name +
                                   "Reference"] = path + "/" + sr.name

                for collection_member in resource.collections:
                    collection = getattr(resource, collection_member.name)

                    if collection_member.name == "contentInstanceCollection":
                        cr = ContentInstanceCollection()
                        instances = map(self._encode_contentinstance,
                                        collection)
                        """
                        for r in collection:
                            ci = binding.ContentInstance()
                            ci.searchStrings = SearchStrings(searchString=r.searchStrings)
                            ci.creationTime = r.creationTime
                            ci.href = r.href
                            ci.contentTypes = ContentTypes(contentType=r.contentTypes)
                            ci.lastModifiedTime = r.lastModifiedTime
                            ci.content_ = binding.Content(r.content["$t"],
                                                          contentType=r.content["contentType"])
                            ci.id = r.id
                            ci.contentSize = r.contentSize
                            instances.append(ci)
                        """
                        cr.contentInstance = instances
                    else:
                        cr = NamedReferenceCollection()
                        references = []
                        for item in collection:
                            r = ReferenceToNamedResource(item.path)
                            r.id = item.name
                            references.append(r)
                        cr.namedReference = references
                    representation[collection_member.name] = cr

                try:
                    latest = resource.latest
                    oldest = resource.oldest
                except AttributeError:
                    pass
                else:
                    if latest is not None:
                        representation["latest"] = ReferenceToNamedResource(
                            latest.path, id=latest.name)
                        representation["oldest"] = ReferenceToNamedResource(
                            oldest.path, id=oldest.name)

            cls = self._get_mapper_class(type(resource).__name__)

            self.logger.debug("Creating instance of %s with %s", cls,
                              representation)

            instance = cls()

            for k, v in representation.iteritems():
                setattr(instance, k, v)

            try:
                flex_values = resource.flex_values
            except AttributeError:
                pass
            else:
                # FIXME: find out how to set these
                for k, v in flex_values.items():
                    self.logger.debug("Set flex: %s - %s", k, v)

        bds = BindingDOMSupport()
        bds.declareNamespace(binding.Namespace, namespace_prefix)

        return instance.toDOM(element_name=namespace_prefix + ":" + resource.typename, bds=bds) \
            .toxml(encoding=encoding)
示例#10
0
文件: check.py 项目: balanced/PyXB
# -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
    logging.basicConfig()
_log = logging.getLogger(__name__)
import unittest

import wsse
import wsu

from pyxb.utils.domutils import BindingDOMSupport

BindingDOMSupport.DeclareNamespace(wsu.Namespace, 'wsu')
BindingDOMSupport.DeclareNamespace(wsse.Namespace, 'wsse')


class TestTrac0198(unittest.TestCase):
    def testFindWsu(self):
        self.assertEqual(3, len(wsse.tAttributedString._AttributeMap))
        for (n, ad) in wsse.tAttributedString._AttributeMap.iteritems():
            if (n.localName() == "agu"):
                self.assertEqual(None, n.namespace())
            else:
                self.assertEqual(wsu.Namespace, n.namespace())
        self.assertEqual(2, len(wsse.tComplexElt._ElementMap))
        for (n, ad) in wsse.tComplexElt._ElementMap.iteritems():
            if n.localName() == 'Elt':
                self.assertEqual(wsu.Namespace, n.namespace())
            elif n.localName() == 'local':
                self.assertEqual(None, n.namespace())
            else:
示例#11
0
# -*- coding: utf-8 -*-
from __future__ import print_function
import logging
if __name__ == '__main__':
    logging.basicConfig()
_log = logging.getLogger(__name__)
import unittest

import qq0196 as qq
import qu0196 as qu
import uq0196 as uq
import uu0196 as uu
import mix
from pyxb.utils.domutils import BindingDOMSupport

BindingDOMSupport.DeclareNamespace(qq.Namespace, 'qq')
BindingDOMSupport.DeclareNamespace(qu.Namespace, 'qu')
BindingDOMSupport.DeclareNamespace(uq.Namespace, 'uq')
BindingDOMSupport.DeclareNamespace(uu.Namespace, 'uu')
BindingDOMSupport.DeclareNamespace(mix.Namespace, 'mix')

qq_bds = BindingDOMSupport(default_namespace=qq.Namespace)

elt_kw = {
    'te': 'te',
    'teq': 'teq',
    'teu': 'teu',
    'e': 'e',
    'eq': 'eq',
    'eu': 'eu',
    'a': 'a',
    def encode_resource(self, resource, response, pretty=False,
                        encoding="utf-8", fields=None):
        # representation = self.get_representation(resource, fields=fields)

        try:
            id_attribute = resource.id_attribute
        except AttributeError:
            xml = tostring(self._build_elementtree(resource),
                           pretty_print=pretty,
                           encoding=encoding)
            return '<?xml version="1.0" encoding="utf-8"?>' + xml

        representation = {}

        if False:
            pass
        else:
            for attr in resource.attributes:
                a_name = attr.name
                if (fields is None or a_name == id_attribute or
                        a_name in fields) and attr.accesstype is not None:
                    val = getattr(resource, "_" + a_name, None)
                    if val is None:
                        continue
                    if isinstance(attr, ListAttribute):
                        if a_name == "childResource":
                            children = [
                                childResourceRef(child.path, name=child.name,
                                                 type=self.__resource_types[
                                                     type(child)])
                                for child in resource.childResource]
                            representation["childResource"] = children
                        elif attr.content_type is AnyURI:
                            representation[a_name] = l = listOfURIs()
                            l.reference = val
                        else:
                            wrappercls = self._get_wrapper_class(a_name)

                            if issubclass(attr.content_type, Entity):
                                valcls = self._get_mapper_class(a_name[:-1])
                                vals = [self._convert_value(v,
                                                            attr.content_type,
                                                            valcls)
                                        for v in val]
                            else:
                                vals = val
                            wrapper = wrappercls()
                            if issubclass(wrappercls, STD_list):
                                wrapper[:] = vals
                            else:
                                setattr(wrapper, wrappercls._ElementMap.keys()[0].localName(), vals)
                            representation[a_name] = wrapper
                    elif isinstance(attr, StringListAttribute):
                        if attr.content_type is AnyURI:
                            representation[a_name] = l = listOfURIs()
                            l.reference = val
                        elif val:
                            representation[a_name] = ' '.join(map(str, val))
                    elif isinstance(attr, EntityAttribute):
                        if issubclass(attr.type, Entity):
                            valcls = self._get_mapper_class(attr.type.typename)
                            val = self._convert_value(val, attr.type,
                                                      valcls)
                        representation[a_name] = val
                    else:
                        if not isinstance(val, Enum):
                            try:
                                enum_values = self.__enum_values[a_name]
                            except KeyError:
                                try:
                                    val = val.strftime('%Y%m%dT%H%M%S')
                                except AttributeError:
                                    pass
                            else:
                                val = enum_values[val]

                        if a_name in ("name", "content"):
                            a_name += "_"
                        representation[a_name] = val

            content_encoding = representation.get("encoding")
            if content_encoding is not None and content_encoding != EncodingType.opaque:
                representation["content_"] = b64decode(representation["content_"])

            cls = self._get_mapper_class(type(resource).__name__)

            self.logger.debug("Creating instance of %s with %s", cls, representation)

            instance = cls()
            #representation.setdefault("expirationTime", '1970-01-01T00:00:00+00:00')

            for k, v in representation.iteritems():
                if k == 'latest' and isinstance(v, model.ContentInstance):
                    v = v.path
                setattr(instance, k.replace("-", "_"), v)

            if (type(resource) not in (model.Discovery, model.Notification) and
                    response):
                instance.resourceType = resource.resourceType
                #try:
                #    instance.resourceType = self.__resource_types[type(resource)]
                #except KeyError:
                #    pass
                instance.resourceID = resource.path
                instance.parentID = resource.parent_path or "/onem2m"

                if type(resource) == CSEBase:
                    instance.expirationTime = datetime(1970, 1, 1)
                instance.stateTag = 0

        bds = BindingDOMSupport()
        bds.declareNamespace(binding.Namespace, namespace_prefix)

        xml = instance.toDOM(
            element_name=namespace_prefix + ":" + resource.typename,
            bds=bds).toxml(encoding=encoding)
        self.logger.debug("XML representation of %s: %s", resource, xml)
        return xml
示例#13
0
文件: tst-a.py 项目: gothub/pyxb-d1
 def tearDown (self):
     BindingDOMSupport.Reset()