Esempio n. 1
0
 def from_json(cls, status, data):
     try:
         content = json_loads(data, object_hook=JSONHydrant.json_to_packstream)
     except ValueError as error:
         raise_from(ProtocolError("Cannot decode response content as JSON"), error)
     else:
         return cls(status, content)
Esempio n. 2
0
    def _fetch(self):
        """ Fetch and process the next incoming message.

        This method does not raise an exception on receipt of a
        FAILURE message. Instead, it sets the response (and
        consequently the parent query and transaction) to a failed
        state. It is the responsibility of the caller to convert this
        failed state into an exception.
        """
        tag, fields = self.read_message()
        if tag == 0x70:
            self._responses.popleft().set_success(**fields[0])
            self._metadata.update(fields[0])
        elif tag == 0x71:
            self._responses[0].add_records(fields)
        elif tag == 0x7F:
            rs = self._responses.popleft()
            rs.set_failure(**fields[0])
            if rs.vital:
                self._wire.close()
        elif tag == 0x7E and not self._responses[0].vital:
            self._responses.popleft().set_ignored()
        else:
            self._wire.close()
            raise ProtocolError("Unexpected protocol message #%02X", tag)
Esempio n. 3
0
 def read_message_py2(self):
     chunks = []
     while True:
         try:
             hi, lo = self.wire.read(2)
         except WireError as error:
             raise_from(ConnectionBroken("Failed to read message"), error)
         else:
             if hi == lo == 0:
                 # We hit a zero chunk...
                 if chunks:
                     # ... and some non-zero chunks have been collected,
                     # therefore we can exit the loop with a message.
                     break
                 else:
                     # ... and no non-zero chunks have yet been collected,
                     # therefore, this must be a null message used for
                     # keep-alive and we should carry on looping.
                     pass
             else:
                 # We found a non-zero chunk which can be collected.
                 size = hi << 8 | lo
                 chunks.append(self.wire.read(size))
     message = bytearray(b"".join(map(bytes, chunks)))
     assert message  # the message should never be empty
     _, n = divmod(message[0], 0x10)
     try:
         fields = list(unpack(message, offset=2))
     except ValueError as error:
         raise_from(ProtocolError("Bad message content"), error)
     else:
         return message[1], fields
Esempio n. 4
0
 def _delete(self, url):
     log.debug("DELETE %r", url)
     try:
         return self.http_pool.request(method="DELETE",
                                       url=url,
                                       headers=dict(self.headers))
     except HTTPError as error:
         raise_from(ProtocolError("Failed to DELETE %r" % url), error)
Esempio n. 5
0
 def _hello(self, user_agent):
     self._assert_open()
     extra = {"scheme": "basic",
              "principal": self.profile.user,
              "credentials": self.profile.password}
     clean_extra = dict(extra)
     clean_extra.update({"credentials": "*******"})
     response = self.append_message(0x01, user_agent, extra, vital=True)
     self.send()
     self._fetch()
     self._audit(response)
     self.connection_id = response.metadata.get("connection_id")
     self.server_agent = response.metadata.get("server")
     if not self.server_agent.startswith("Neo4j/"):
         raise ProtocolError("Unexpected server agent {!r}".format(self.server_agent))
Esempio n. 6
0
 def accept(cls, wire, min_protocol_version=None):
     data = wire.read(20)
     if data[0:4] != BOLT_SIGNATURE:
         raise ProtocolError("Incoming connection did not provide Bolt signature")
     for major, minor in cls._proposed_versions(data, offset=4):
         if min_protocol_version and (major, minor) < min_protocol_version:
             continue
         try:
             subclass = Bolt._get_subclass((major, minor))
         except TypeError:
             continue
         else:
             wire.write(bytearray([0, 0, minor, major]))
             wire.send()
             return subclass(wire, ConnectionProfile(address=wire.remote_address))
     raise TypeError("Unable to agree supported protocol version")
Esempio n. 7
0
 def _post(self, url, statement=None, parameters=None):
     log.debug("POST %r %r %r", url, statement, parameters)
     if statement:
         statements = [
             OrderedDict([
                 ("statement", statement),
                 ("parameters", dehydrate(parameters or {})),
                 ("resultDataContents", ["REST"]),
                 ("includeStats", True),
             ])
         ]
     else:
         statements = []
     try:
         return self.http_pool.request(method="POST",
                                       url=url,
                                       headers=dict(self.headers, **{"Content-Type": "application/json"}),
                                       body=json_dumps({"statements": statements}))
     except HTTPError as error:
         raise_from(ProtocolError("Failed to POST to %r" % url), error)
Esempio n. 8
0
 def read_message_py2(self):
     chunks = []
     while True:
         try:
             hi, lo = self.wire.read(2)
         except WireError as error:
             raise_from(ConnectionBroken("Failed to read message"), error)
         else:
             if hi == lo == 0:
                 break
             size = hi << 8 | lo
             chunks.append(self.wire.read(size))
     message = bytearray(b"".join(map(bytes, chunks)))
     _, n = divmod(message[0], 0x10)
     try:
         unpacker = UnpackStream(message, offset=2)
         fields = [unpacker.unpack() for _ in range(n)]
     except ValueError as error:
         raise_from(ProtocolError("Bad message content"), error)
     else:
         return message[1], fields