Ejemplo n.º 1
0
    def handle(self, request, response):
        xml_deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
        deserializers = {'application/xml': xml_deserializer,
                         'application/json': wsgi.JSONDeserializer()}
        xml_serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
        serializers = {'application/xml': xml_serializer,
                       'application/json': wsgi.JSONDictSerializer()}
        format_types = {'xml': 'application/xml',
                        'json': 'application/json'}

        path = [part for part in request.path_url.split("/") if part]
        id = path[-1].split('.')[0]

        content_type = format_types.get(None,
                                        request.best_match_content_type())
        deserializer = deserializers.get(content_type)
        serializer = serializers.get(content_type)

        body = None
        if request.body:
            body = deserializer.deserialize(request.body)['body']

        api_response = self._plugin.post_update_port(request.context,
                                                     id,
                                                     body)
        return serializer.serialize(api_response)
Ejemplo n.º 2
0
 def test_empty_dic_xml(self):
     data = {}
     # Since it is an empty dict, we use quantum:type='dict' and
     # an empty XML element to represent it. In addition, we use an
     # virtual XML root _v_root to wrap the XML doc.
     # XML is:
     # <_v_root quantum:type="dict"
     #          xmlns="http://openstack.org/quantum/api/v2.0"
     #          xmlns:quantum="http://openstack.org/quantum/api/v2.0"
     #          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
     serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
     result = serializer.serialize(data)
     deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
     new_data = deserializer.deserialize(result)['body']
     self.assertEqual(data, new_data)
Ejemplo n.º 3
0
    def test_non_root_one_item_dic_xml(self):
        data = {'test1': 1}
        # We have a key in this dict, and its value is an integer.
        # XML is:
        # <test1 quantum:type="int"
        #        xmlns="http://openstack.org/quantum/api/v2.0"
        #        xmlns:quantum="http://openstack.org/quantum/api/v2.0"
        #        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        # 1</test1>

        serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
        result = serializer.serialize(data)
        deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
        new_data = deserializer.deserialize(result)['body']
        self.assertEqual(data, new_data)
Ejemplo n.º 4
0
 def test_empty_dic_xml(self):
     data = {}
     # Since it is an empty dict, we use quantum:type='dict' and
     # an empty XML element to represent it. In addition, we use an
     # virtual XML root _v_root to wrap the XML doc.
     # XML is:
     # <_v_root quantum:type="dict"
     #          xmlns="http://openstack.org/quantum/api/v2.0"
     #          xmlns:quantum="http://openstack.org/quantum/api/v2.0"
     #          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
     serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
     result = serializer.serialize(data)
     deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
     new_data = deserializer.deserialize(result)['body']
     self.assertEqual(data, new_data)
Ejemplo n.º 5
0
 def test_None(self):
     data = None
     # Since it is None, we use xsi:nil='true'.
     # In addition, we use an
     # virtual XML root _v_root to wrap the XML doc.
     # XML is:
     # <_v_root xsi:nil="true"
     #          xmlns="http://openstack.org/quantum/api/v2.0"
     #          xmlns:quantum="http://openstack.org/quantum/api/v2.0"
     #          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
     serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
     result = serializer.serialize(data)
     deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
     new_data = deserializer.deserialize(result)['body']
     self.assertIsNone(new_data)
Ejemplo n.º 6
0
 def test_None(self):
     data = None
     # Since it is None, we use xsi:nil='true'.
     # In addition, we use an
     # virtual XML root _v_root to wrap the XML doc.
     # XML is:
     # <_v_root xsi:nil="true"
     #          xmlns="http://openstack.org/quantum/api/v2.0"
     #          xmlns:quantum="http://openstack.org/quantum/api/v2.0"
     #          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
     serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
     result = serializer.serialize(data)
     deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
     new_data = deserializer.deserialize(result)['body']
     self.assertIsNone(new_data)
Ejemplo n.º 7
0
    def test_non_root_one_item_dic_xml(self):
        data = {'test1': 1}
        # We have a key in this dict, and its value is an integer.
        # XML is:
        # <test1 quantum:type="int"
        #        xmlns="http://openstack.org/quantum/api/v2.0"
        #        xmlns:quantum="http://openstack.org/quantum/api/v2.0"
        #        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        # 1</test1>

        serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
        result = serializer.serialize(data)
        deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
        new_data = deserializer.deserialize(result)['body']
        self.assertEqual(data, new_data)
Ejemplo n.º 8
0
    def test_non_root_two_items_dic_xml(self):
        data = {'test1': 1, 'test2': '2'}
        # We have no root element in this data, We will use a virtual
        # root element _v_root to wrap the doct.
        # The XML is:
        # <_v_root xmlns="http://openstack.org/quantum/api/v2.0"
        #          xmlns:quantum="http://openstack.org/quantum/api/v2.0"
        #          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        #    <test1 quantum:type="int">1</test1><test2>2</test2>
        # </_v_root>

        serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
        result = serializer.serialize(data)
        deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
        new_data = deserializer.deserialize(result)['body']
        self.assertEqual(data, new_data)
Ejemplo n.º 9
0
    def _req(self, method, resource, data=None, fmt=None,
             id=None, subresource=None, sub_id=None, params=None, action=None):
        if not fmt:
            fmt = self.fmt
        if id and action:
            path = '/lb/%(resource)s/%(id)s/%(action)s.%(fmt)s' % locals()
        elif id and subresource and sub_id:
            path = (
                '/lb/%(resource)s/%(id)s/%(subresource)s/'
                '%(sub_id)s.%(fmt)s') % locals()
        elif id and subresource:
            path = (
                '/lb/%(resource)s/%(id)s/'
                '%(subresource)s.%(fmt)s') % locals()
        elif id:
            path = '/lb/%(resource)s/%(id)s.%(fmt)s' % locals()
        else:
            path = '/lb/%(resource)s.%(fmt)s' % locals()

        content_type = 'application/%s' % fmt
        body = None
        if data is not None:  # empty dict is valid
            body = wsgi.Serializer(
                attributes.get_attr_metadata()).serialize(data, content_type)

        req = create_request(path,
                             body,
                             content_type,
                             method,
                             query_string=params)
        return req
Ejemplo n.º 10
0
    def test_non_root_two_items_dic_xml(self):
        data = {'test1': 1, 'test2': '2'}
        # We have no root element in this data, We will use a virtual
        # root element _v_root to wrap the doct.
        # The XML is:
        # <_v_root xmlns="http://openstack.org/quantum/api/v2.0"
        #          xmlns:quantum="http://openstack.org/quantum/api/v2.0"
        #          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        #    <test1 quantum:type="int">1</test1><test2>2</test2>
        # </_v_root>

        serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
        result = serializer.serialize(data)
        deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
        new_data = deserializer.deserialize(result)['body']
        self.assertEqual(data, new_data)
Ejemplo n.º 11
0
 def setUp(self):
     super(WebTestCase, self).setUp()
     json_deserializer = wsgi.JSONDeserializer()
     xml_deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
     self._deserializers = {
         'application/json': json_deserializer,
         'application/xml': xml_deserializer,
     }
Ejemplo n.º 12
0
 def setUp(self):
     super(WebTestCase, self).setUp()
     json_deserializer = wsgi.JSONDeserializer()
     xml_deserializer = wsgi.XMLDeserializer(
         attributes.get_attr_metadata())
     self._deserializers = {
         'application/json': json_deserializer,
         'application/xml': xml_deserializer,
     }
Ejemplo n.º 13
0
 def serialize(self, data):
     ctype = 'application/%s' % self.fmt
     result = wsgi.Serializer(attributes.get_attr_metadata()).serialize(
         data, ctype)
     return result
Ejemplo n.º 14
0
def Resource(controller, faults=None, deserializers=None, serializers=None):
    """Represents an API entity resource and the associated serialization and
    deserialization logic
    """
    xml_deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
    default_deserializers = {'application/xml': xml_deserializer,
                             'application/json': wsgi.JSONDeserializer()}
    xml_serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
    default_serializers = {'application/xml': xml_serializer,
                           'application/json': wsgi.JSONDictSerializer()}
    format_types = {'xml': 'application/xml',
                    'json': 'application/json'}
    action_status = dict(create=201, delete=204)

    default_deserializers.update(deserializers or {})
    default_serializers.update(serializers or {})

    deserializers = default_deserializers
    serializers = default_serializers
    faults = faults or {}

    @webob.dec.wsgify(RequestClass=Request)
    def resource(request):
        route_args = request.environ.get('wsgiorg.routing_args')
        if route_args:
            args = route_args[1].copy()
        else:
            args = {}

        # NOTE(jkoelker) by now the controller is already found, remove
        #                it from the args if it is in the matchdict
        args.pop('controller', None)
        fmt = args.pop('format', None)
        action = args.pop('action', None)
        content_type = format_types.get(fmt,
                                        request.best_match_content_type())
        deserializer = deserializers.get(content_type)
        serializer = serializers.get(content_type)

        try:
            if request.body:
                args['body'] = deserializer.deserialize(request.body)['body']

            method = getattr(controller, action)

            result = method(request=request, **args)
        except (exceptions.QuantumException,
                netaddr.AddrFormatError) as e:
            LOG.exception(_('%s failed'), action)
            body = serializer.serialize({'QuantumError': e})
            kwargs = {'body': body, 'content_type': content_type}
            for fault in faults:
                if isinstance(e, fault):
                    raise faults[fault](**kwargs)
            raise webob.exc.HTTPInternalServerError(**kwargs)
        except webob.exc.HTTPException as e:
            LOG.exception(_('%s failed'), action)
            e.body = serializer.serialize({'QuantumError': e})
            e.content_type = content_type
            raise
        except Exception as e:
            # NOTE(jkoelker) Everyting else is 500
            LOG.exception(_('%s failed'), action)
            # Do not expose details of 500 error to clients.
            msg = _('Request Failed: internal server error while '
                    'processing your request.')
            body = serializer.serialize({'QuantumError': msg})
            kwargs = {'body': body, 'content_type': content_type}
            raise webob.exc.HTTPInternalServerError(**kwargs)

        status = action_status.get(action, 200)
        body = serializer.serialize(result)
        # NOTE(jkoelker) Comply with RFC2616 section 9.7
        if status == 204:
            content_type = ''
            body = None

        return webob.Response(request=request, status=status,
                              content_type=content_type,
                              body=body)
    return resource
Ejemplo n.º 15
0
        #    <int quantum:type="float">5.0</int>  # Float text
        #    <dict quantum:type="dict" />     # Empty Dict
        #    <name>net1</name>
        #    <admin_state_up quantum:type="bool">True</admin_state_up> # Bool
        #    <test xsi:nil="true" />          # None
        #    <tenant_id>test-tenant</tenant_id>
        #    # We must have a namespace defined in root for prefix:external
        #    <prefix:external quantum:type="bool">True</prefix:external>
        #    <tests>                          # List
        #       <test><test1>value1</test1></test>
        #       <test><test3 quantum:type="int">3</test3>
        #             <test2 quantum:type="int">2</test2>
        #       </test></tests>
        # </network>

        metadata = attributes.get_attr_metadata()
        ns = {'prefix': 'http://xxxx.yy.com'}
        metadata[constants.EXT_NS] = ns
        metadata['plurals'] = {'tests': 'test'}
        serializer = wsgi.XMLDictSerializer(metadata)
        result = serializer.serialize(NETWORK)
        deserializer = wsgi.XMLDeserializer(metadata)
        new_net = deserializer.deserialize(result)['body']
        self.assertEqual(NETWORK, new_net)

    def test_None(self):
        data = None
        # Since it is None, we use xsi:nil='true'.
        # In addition, we use an
        # virtual XML root _v_root to wrap the XML doc.
        # XML is:
Ejemplo n.º 16
0
 def serialize(self, data):
     ctype = 'application/%s' % self.fmt
     result = wsgi.Serializer(
         attributes.get_attr_metadata()).serialize(data, ctype)
     return result
Ejemplo n.º 17
0
def Resource(controller, faults=None, deserializers=None, serializers=None):
    """Represents an API entity resource and the associated serialization and
    deserialization logic
    """
    xml_deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
    default_deserializers = {'application/xml': xml_deserializer,
                             'application/json': wsgi.JSONDeserializer()}
    xml_serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
    default_serializers = {'application/xml': xml_serializer,
                           'application/json': wsgi.JSONDictSerializer()}
    format_types = {'xml': 'application/xml',
                    'json': 'application/json'}
    action_status = dict(create=201, delete=204)

    default_deserializers.update(deserializers or {})
    default_serializers.update(serializers or {})

    deserializers = default_deserializers
    serializers = default_serializers
    faults = faults or {}

    @webob.dec.wsgify(RequestClass=Request)
    def resource(request):
        route_args = request.environ.get('wsgiorg.routing_args')
        if route_args:
            args = route_args[1].copy()
        else:
            args = {}

        # NOTE(jkoelker) by now the controller is already found, remove
        #                it from the args if it is in the matchdict
        args.pop('controller', None)
        fmt = args.pop('format', None)
        action = args.pop('action', None)
        content_type = format_types.get(fmt,
                                        request.best_match_content_type())
        deserializer = deserializers.get(content_type)
        serializer = serializers.get(content_type)

        try:
            if request.body:
                args['body'] = deserializer.deserialize(request.body)['body']

            method = getattr(controller, action)

            result = method(request=request, **args)
        except (ValueError, AttributeError,
                exceptions.QuantumException,
                netaddr.AddrFormatError) as e:
            LOG.exception(_('%s failed'), action)
            body = serializer.serialize({'QuantumError': str(e)})
            kwargs = {'body': body, 'content_type': content_type}
            for fault in faults:
                if isinstance(e, fault):
                    raise faults[fault](**kwargs)
            raise webob.exc.HTTPInternalServerError(**kwargs)
        except webob.exc.HTTPException as e:
            LOG.exception(_('%s failed'), action)
            e.body = serializer.serialize({'QuantumError': str(e)})
            e.content_type = content_type
            raise
        except Exception as e:
            # NOTE(jkoelker) Everyting else is 500
            LOG.exception(_('%s failed'), action)
            # Do not expose details of 500 error to clients.
            msg = _('Request Failed: internal server error while '
                    'processing your request.')
            body = serializer.serialize({'QuantumError': msg})
            kwargs = {'body': body, 'content_type': content_type}
            raise webob.exc.HTTPInternalServerError(**kwargs)

        status = action_status.get(action, 200)
        body = serializer.serialize(result)
        # NOTE(jkoelker) Comply with RFC2616 section 9.7
        if status == 204:
            content_type = ''
            body = None

        return webob.Response(request=request, status=status,
                              content_type=content_type,
                              body=body)
    return resource
Ejemplo n.º 18
0
        #    <int quantum:type="float">5.0</int>  # Float text
        #    <dict quantum:type="dict" />     # Empty Dict
        #    <name>net1</name>
        #    <admin_state_up quantum:type="bool">True</admin_state_up> # Bool
        #    <test xsi:nil="true" />          # None
        #    <tenant_id>test-tenant</tenant_id>
        #    # We must have a namespace defined in root for prefix:external
        #    <prefix:external quantum:type="bool">True</prefix:external>
        #    <tests>                          # List
        #       <test><test1>value1</test1></test>
        #       <test><test3 quantum:type="int">3</test3>
        #             <test2 quantum:type="int">2</test2>
        #       </test></tests>
        # </network>

        metadata = attributes.get_attr_metadata()
        ns = {'prefix': 'http://xxxx.yy.com'}
        metadata[constants.EXT_NS] = ns
        metadata['plurals'] = {'tests': 'test'}
        serializer = wsgi.XMLDictSerializer(metadata)
        result = serializer.serialize(NETWORK)
        deserializer = wsgi.XMLDeserializer(metadata)
        new_net = deserializer.deserialize(result)['body']
        self.assertEqual(NETWORK, new_net)

    def test_None(self):
        data = None
        # Since it is None, we use xsi:nil='true'.
        # In addition, we use an
        # virtual XML root _v_root to wrap the XML doc.
        # XML is: