Example #1
0
def _resolve_multipart_related(cid, request):
    """ Resolve reference to another part of the multi-part request."""
    # iterate over the parts to find the correct one
    for headers, data in mp.iterate(request):
        if headers.get("Content-ID") == cid:
            return data
    raise ValueError("No part with content-id '%s'." % cid)
Example #2
0
 def get_decoder(self, request):
     if request.method == "GET":
         return WPS10ExecuteKVPDecoder(request.GET)
     elif request.method == "POST":
         # support for multipart items
         if request.META["CONTENT_TYPE"].startswith("multipart/"):
             _, data = next(mp.iterate(request.body))
             return WPS10ExecuteXMLDecoder(data)
         return WPS10ExecuteXMLDecoder(request.body)
Example #3
0
def result_set_from_raw_data(data):
    """ Create a result set from raw HTTP data. This can either be a single
        or a multipart string. It returns a list containing objects of the 
        `ResultBuffer` type that reference substrings of the given data.
    """
    return [
        ResultBuffer(data, *parse_headers(headers))
        for headers, data in mp.iterate(data)
        if not headers.get("Content-Type").startswith("multipart")
    ]
Example #4
0
 def get_decoder(request):
     """ Get request decoder matching the request format. """
     if request.method == "GET":
         return WPS10ExecuteKVPDecoder(
             parse_query_string(request.META['QUERY_STRING']))
     elif request.method == "POST":
         # support for multipart items
         if request.META["CONTENT_TYPE"].startswith("multipart/"):
             _, data = next(mp.iterate(request.body))
             return WPS10ExecuteXMLDecoder(data)
         return WPS10ExecuteXMLDecoder(request.body)
Example #5
0
    def test_multipart_iteration(self):
        parsed = map(
            lambda i: (i[0], str(i[1])), mp.iterate(self.example_multipart)
        )

        self.assertEqual([
                ({"MIME-Version": "1.0", "Content-Type": "multipart/mixed; boundary=frontier"}, ""),
                ({"Content-Type": "text/plain"}, "This is the body of the message."),
                ({"Content-Type": "application/octet-stream", "Content-Transfer-Encoding": "base64"}, "PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUgYm9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==")
            ], parsed
        )
Example #6
0
    def _unpackMultipartContent(self, response):
        if getattr(response, "streaming", False):
            content = "".join(response)
        else:
            content = response.content

        for headers, data in mp.iterate(content, headers=response):
            if RE_MIME_TYPE_XML.match(headers["Content-Type"]):
                self.xmlData = str(data)
            else:
                self.imageData = str(data)
Example #7
0
    def _unpackMultipartContent(self, response):
        if getattr(response, "streaming", False):
            content = "".join(response)
        else:
            content = response.content

        for headers, data in mp.iterate(content, headers=response):
            if RE_MIME_TYPE_XML.match(headers["Content-Type"]):
                self.xmlData = str(data)
            else:
                self.imageData = str(data)
Example #8
0
 def get_decoder(request):
     """ Get request decoder matching the request format. """
     if request.method == "GET":
         return WPS10ExecuteKVPDecoder(
             parse_query_string(request.META['QUERY_STRING'])
         )
     elif request.method == "POST":
         # support for multipart items
         if request.META["CONTENT_TYPE"].startswith("multipart/"):
             _, data = next(mp.iterate(request.body))
             return WPS10ExecuteXMLDecoder(data)
         return WPS10ExecuteXMLDecoder(request.body)
Example #9
0
def result_set_from_raw_data(data):
    """ Create a result set from raw HTTP data. This can either be a single
        or a multipart string. It returns a list containing objects of the
        :class:`ResultBuffer` type that reference substrings of the given data.

        :param data: the raw byte data
        :returns: a result set: a list containing :class:`ResultBuffer`
    """
    return [
        ResultBuffer(d, *parse_headers(headers))
        for headers, d in mp.iterate(data)
        if not headers.get(b"Content-Type").startswith(b"multipart")
    ]
Example #10
0
    def _unpackMultipartContent(self, response):

        if getattr(response, "streaming", False):
            content = "".join(response)
        else:
            content = response.content
        headers = {b(key): b(value) for key, value in response.items()}
        for headers, data in mp.iterate(content, headers=headers):
            if RE_MIME_TYPE_XML.match(
                    headers[b"Content-Type"].decode("utf-8")):
                self.xmlData = data.tobytes()
            else:
                self.imageData = data.tobytes()
Example #11
0
    def resolve_reference(self, reference, request):
        url = urlparse(reference.href)

        # if the href references a part in the multipart request, iterate over
        # all parts and return the correct one
        if url.scheme == "cid":
            for headers, data in mp.iterate(request):
                if headers.get("Content-ID") == url.path:
                    return data
            raise ReferenceException("No part with content-id '%s'." % url.path)

        try:
            request = urllib2.Request(reference.href, reference.body)
            response = urllib2.urlopen(request)
            return response.read()
        except urllib2.URLError, e:
            raise ReferenceException(str(e))
Example #12
0
    def test_multipart_iteration(self):
        parsed = map(lambda i: (i[0], str(i[1])),
                     mp.iterate(self.example_multipart))

        self.assertEqual([
            ({
                "MIME-Version": "1.0",
                "Content-Type": "multipart/mixed; boundary=frontier"
            }, ""),
            ({
                "Content-Type": "text/plain"
            }, "This is the body of the message."),
            ({
                "Content-Type": "application/octet-stream",
                "Content-Transfer-Encoding": "base64"
            },
             "PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUgYm9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg=="
             )
        ], parsed)
Example #13
0
    def test_multipart_iteration(self):
        parsed = [(i[0],
                   i[1].tobytes() if isinstance(i[1], memoryview) else i[1])
                  for i in mp.iterate(self.example_multipart)]

        self.assertEqual([
            ({
                b"MIME-Version": b"1.0",
                b"Content-Type": b"multipart/mixed; boundary=frontier"
            }, b""),
            ({
                b"Content-Type": b"text/plain"
            }, b"This is the body of the message."),
            ({
                b"Content-Type": b"application/octet-stream",
                b"Content-Transfer-Encoding": b"base64"
            },
             b"PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUgYm9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg=="
             )
        ], parsed)
Example #14
0
        logger.debug("MapServer: Dispatch took %f seconds." % (te - ts))
    except Exception, e:
        raise MapServerException(str(e), "NoApplicableCode")
    
    raw_bytes = msIO_getStdoutBufferBytes()

    # check whether an error occurred
    if status != 0:
        # First try to get the error message through the error object
        obj = msGetErrorObj()
        if obj and obj.message:
            raise MapServerException(obj.message, obj.code)

        try:
            # try to parse the output as XML
            _, data = iterate(raw_bytes).next()
            tree = etree.fromstring(str(data))
            exception_elem = tree.xpath("*[local-name() = 'Exception']")[0]
            locator = exception_elem.attrib["locator"]
            code = exception_elem.attrib["exceptionCode"]
            message = exception_elem[0].text

            raise MapServerException(message, locator, code)

        except (etree.XMLSyntaxError, IndexError, KeyError):
            pass

        # Fallback: raise arbitrary error
        raise MapServerException("Unexpected Error.", "NoApplicableCode")

    logger.debug("MapServer: Performing MapServer cleanup.")
Example #15
0
        logger.debug("MapServer: Dispatch took %f seconds." % (te - ts))
    except Exception, e:
        raise MapServerException(str(e), "NoApplicableCode")

    raw_bytes = msIO_getStdoutBufferBytes()

    # check whether an error occurred
    if status != 0:
        # First try to get the error message through the error object
        obj = msGetErrorObj()
        if obj and obj.message:
            raise MapServerException(obj.message, obj.code)

        try:
            # try to parse the output as XML
            _, data = iterate(raw_bytes).next()
            tree = etree.fromstring(str(data))
            exception_elem = tree.xpath("*[local-name() = 'Exception']")[0]
            locator = exception_elem.attrib["locator"]
            code = exception_elem.attrib["exceptionCode"]
            message = exception_elem[0].text

            raise MapServerException(message, locator, code)

        except (etree.XMLSyntaxError, IndexError, KeyError):
            pass

        # Fallback: raise arbitrary error
        raise MapServerException("Unexpected Error.", "NoApplicableCode")

    logger.debug("MapServer: Performing MapServer cleanup.")