Beispiel #1
0
    def get_next_row_from_connection(self):
        """
        Reads the connection to get the next row, and sends it to the parser

        @raise WebserviceError: if the connection is interrupted
        """
        next_row = None
        try:
            line = self.connection.next()
            if line.startswith("]"):
                self.footer += line
                for otherline in self.connection:
                    self.footer += line
                self.check_return_status()
            else:
                line = line.strip().strip(',')
                if len(line) > 0:
                    try:
                        row = json.loads(line)
                    except json.decoder.JSONDecodeError, e:
                        raise WebserviceError(
                            "Error parsing line from results: '" + line +
                            "' - " + str(e))
                    next_row = self.parser(row)
        except StopIteration:
            raise WebserviceError("Connection interrupted")

        if next_row is None:
            self._is_finished = True
            raise StopIteration
        else:
            return next_row
Beispiel #2
0
    def __getattr__(self, name):
        if name in self._attr_cache:
            return self._attr_cache[name]

        if name == "type":
            return self._data["class"]

        fld = self._cld.get_field(name)
        attr = None
        if isinstance(fld, Attribute):
            if name in self._data:
                attr = self._data[name]
            if attr is None:
                attr = self._fetch_attr(fld)
        elif isinstance(fld, Reference):
            ref_paths = self._get_ref_paths(fld)
            if name in self._data:
                data = self._data[name]
            else:
                data = self._fetch_reference(fld)
            if isinstance(fld, Collection):
                if data is None:
                    attr = []
                else:
                    attr = map(lambda x: ResultObject(x, fld.type_class, ref_paths), data)
            else:
                if data is None:
                    attr = None
                else:
                    attr = ResultObject(data, fld.type_class, ref_paths)
        else:
            raise WebserviceError("Inconsistent model - This should never happen")
        self._attr_cache[name] = attr
        return attr
Beispiel #3
0
    def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
        """
        Handle 401 HTTP errors, attempting to return informative error messages
        =======================================================================

        401 errors indicate we don't have sufficient permission for the resource
        we requested - usually a list or a tempate

        @raise WebserviceError: in all circumstances

        """
        content = fp.read()
        fp.close()
        if self.using_authentication:
            raise WebserviceError("Insufficient permissions", errcode, errmsg, content)
        else:
            raise WebserviceError("No permissions - not logged in", errcode, errmsg, content)
Beispiel #4
0
 def parse_header(self):
     """Reads out the header information from the connection"""
     try:
         line = self.connection.next().strip()
         self.header += line
         if not line.endswith('"results":['):
             self.parse_header()
     except StopIteration:
         raise WebserviceError("The connection returned a bad header" + self.header)
Beispiel #5
0
 def delete(self, url):
     url = self.prepare_url(url)
     o = urlparse(url)
     con = httplib.HTTPConnection(o.hostname, o.port)
     con.request('DELETE', url, None, self.plain_post_header)
     resp = con.getresponse()
     content = resp.read()
     con.close()
     if resp.status != 200:
         raise WebserviceError(resp.status, resp.reason, content)
     return content
Beispiel #6
0
 def parse_header(self):
     """Reads out the header information from the connection"""
     self.LOG.debug('Connection = {0}'.format(self.connection))
     try:
         line = decode_binary(next(self.connection)).strip()
         self.header += line
         if not line.endswith('"results":['):
             self.parse_header()
     except StopIteration:
         raise WebserviceError("The connection returned a bad header" +
                               self.header)
Beispiel #7
0
    def check_return_status(self):
        """
        Perform status checks
        =====================

        The footer containts information as to whether the result
        set was successfully transferred in its entirety. This
        method makes sure we don't silently accept an
        incomplete result set.

        @raise WebserviceError: if the footer indicates there was an error
        """
        container = self.header + self.footer
        info = None
        try:
            info = json.loads(container)
        except:
            raise WebserviceError("Error parsing JSON container: " + container)

        if not info["wasSuccessful"]:
            raise WebserviceError(info["statusCode"], info["error"])
Beispiel #8
0
 def post_content(self, url, body, mimetype, charset = "utf-8"):
     headers = {
         "Content-Type": "%s; charset=%s" % (mimetype, charset),
         "UserAgent": USER_AGENT
     }
     url = self.prepare_url(url)
     o = urlparse(url)
     con = httplib.HTTPConnection(o.hostname, o.port)
     con.request('POST', url, body, headers)
     resp = con.getresponse()
     content = resp.read()
     con.close()
     if resp.status != 200:
         raise WebserviceError(resp.status, resp.reason, content)
     return content
Beispiel #9
0
    def http_error_400(self, url, fp, errcode, errmsg, headers, data=None):
        """
        Handle 400 HTTP errors, attempting to return informative error messages
        =======================================================================

        400 errors indicate that something about our request was incorrect

        @raise WebserviceError: in all circumstances

        """
        content = fp.read()
        fp.close()
        try:
            message = json.loads(content)["error"]
        except:
            message = content
        raise WebserviceError("There was a problem with our request", errcode, errmsg, message)
Beispiel #10
0
    def http_error_404(self, url, fp, errcode, errmsg, headers, data=None):
        """
        Handle 404 HTTP errors, attempting to return informative error messages
        =======================================================================

        404 errors indicate that the requested resource does not exist - usually
        a template that is not longer available.

        @raise WebserviceError: in all circumstances

        """
        content = fp.read()
        fp.close()
        try:
            message = json.loads(content)["error"]
        except:
            message = content
        raise WebserviceError("Missing resource", errcode, errmsg, message)
Beispiel #11
0
    def http_error_500(self, url, fp, errcode, errmsg, headers, data=None):
        """
        Handle 500 HTTP errors, attempting to return informative error messages
        =======================================================================

        500 errors indicate that the server borked during the request - ie: it wasn't
        our fault.

        @raise WebserviceError: in all circumstances

        """
        content = fp.read()
        fp.close()
        try:
            message = json.loads(content)["error"]
        except:
            message = content
        raise WebserviceError("Internal server error", errcode, errmsg, message)
Beispiel #12
0
 def http_error_default(self, url, fp, errcode, errmsg, headers):
     """Re-implementation of http_error_default, with content now supplied by default"""
     content = fp.read()
     fp.close()
     raise WebserviceError(errcode, errmsg, content)
Beispiel #13
0
 def next(self):
     """Return a parsed line of data"""
     line = self.connection.next().strip()
     if line.startswith("[ERROR]"):
         raise WebserviceError(line)
     return self.parser(line)