Allow a user to query a device directly using XML-requests.

        :param rpc_command: (str) rpc command such as:
                                  <Get><Operational><LLDP><NodeTable></NodeTable></LLDP></Operational></Get>
771913
def make_rpc_call(self, rpc_command):
        
        # ~~~ hack: ~~~
        if not self.is_alive():
            self.close()  # force close for safety
            self.open()  # reopen
        # ~~~ end hack ~~~
        result = self._execute_rpc(rpc_command)
        return ET.tostring(result)
460650
def request(self, host, handler, request_body, verbose):
        
        headers = {'User-Agent': self.user_agent,
                   'Content-Type': 'text/xml',
                   }
        url = self._build_url(host, handler)
        kwargs = {}
        if StrictVersion(requests.__version__) >= StrictVersion('0.8.8'):
            kwargs['verify']=True
        else:
            if self.use_https:
                warnings.warn('using https transport but no certificate '
                              'verification. (Hint: upgrade requests package.)')
        try:
            resp = requests.post(url, data=request_body, headers=headers,
                                 **kwargs)
        except ValueError:
            raise
        except Exception:
            raise # something went wrong
        else:
            try:
                resp.raise_for_status()
            except requests.RequestException as e:
                raise xmlrpc.ProtocolError(url, resp.status_code, 
                                                        str(e), resp.headers)
            else:
                return self.parse_response(resp)
1049614
def _parse_request(self):
        '''
        
        '''
        self.req_method = 'unknown'
        self.req_params = {}
        self.req_rpc_version = '2.0'
        self.req_id = 0
        self.data = self.rfile.read(int(self.headers.get('content-length')))
        data_dict = json.loads(self.data)
        self.req_method = data_dict['method']
        self.req_params = decode_data(data_dict['params'])
        self.req_rpc_version = data_dict['jsonrpc']
        self.req_id = data_dict['id']
908133
def get_xmlrpc_server(self):
        
        check_proxy_setting()
        if os.environ.has_key('XMLRPC_DEBUG'):
            debug = 1
        else:
            debug = 0
        try:
            return xmlrpclib.Server(XML_RPC_SERVER, transport=ProxyTransport(), verbose=debug)
        except IOError:
            self.logger("ERROR: Can't connect to XML-RPC server: %s" \
                    % XML_RPC_SERVER)
922943
def exec_appcommand_post(self, attribute_list):
        
        # Prepare POST XML body for AppCommand.xml
        post_root = ET.Element("tx")

        for attribute in attribute_list:
            # Append tags for each attribute
            item = ET.Element("cmd")
            item.set("id", "1")
            item.text = attribute
            post_root.append(item)

        # Buffer XML body as binary IO
        body = BytesIO()
        post_tree = ET.ElementTree(post_root)
        post_tree.write(body, encoding="utf-8", xml_declaration=True)

        # Query receivers AppCommand.xml
        try:
            res = self.send_post_command(
                self._urls.appcommand, body.getvalue())
        except requests.exceptions.RequestException:
            _LOGGER.error("No connection to %s end point on host %s",
                          self._urls.appcommand, self._host)
            body.close()
        else:
            # Buffered XML not needed anymore: close
            body.close()

            try:
                # Return XML ElementTree
                root = ET.fromstring(res)
            except (ET.ParseError, TypeError):
                _LOGGER.error(
                    "End point %s on host %s returned malformed XML.",
                    self._urls.appcommand, self._host)
            else:
                return root
981193
def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query):
        
        url, params = self._prepare_request(command, query)
        return {
            "url": url, "params": params, "files": files, "stream": use_long_polling,
            "verify": True,  # No self signed certificates. Telegram should be trustworthy anyway...
            "timeout": request_timeout
        }
85523
def _send_rpc(self, device_info, control_info, address, rpc_id, payload, poll_interval, timeout):
        """"""

        write_address, write_data = control_info.format_rpc(address, rpc_id, payload)
        self._jlink.memory_write32(write_address, write_data)

        self._trigger_rpc(device_info)

        start = monotonic()
        now = start

        poll_address, poll_mask = control_info.poll_info()

        while (now - start) < timeout:
            time.sleep(poll_interval)
            value, = self._jlink.memory_read8(poll_address, 1)

            if value & poll_mask:
                break

            now = monotonic()

        if (now - start) >= timeout:
            raise HardwareError("Timeout waiting for RPC response", timeout=timeout, poll_interval=poll_interval)

        read_address, read_length = control_info.response_info()
        read_data = self._read_memory(read_address, read_length, join=True)

        return control_info.format_response(read_data)
266625
async def query_handler(self):
        
        while True:
            request = await self.read()
            if request is None:
                break
            ID = request.get('ID')
            try:
                if request.get("AUTH"):
                    self._check_auth_handler(request)
                elif request.get("HEARTBEAT"):
                    response = {
                        "MPRPC": self.VERSION,
                        "CODE": 101,
                        "HEARTBEAT": "pong"
                    }
                    self.writer(response)
                elif ID:
                    fut = asyncio.ensure_future(
                        self._RPC_handler(request),
                        loop=self._loop)
                    if asyncio.isfuture(fut):
                        self.tasks[ID] = fut
                        self.__class__.TASKS.append(fut)
                else:
                    raise ProtocolSyntaxException("Protocol Syntax Error")
            except MethodError as se:
                exinfo = traceback.TracebackException.from_exception(
                    se).format(chain=True)
                frames = "".join([i + "/n" for i in exinfo])
                response = {
                    "MPRPC": self.VERSION,
                    "CODE": se.status_code,
                    "MESSAGE": {
                        "ID": ID,
                        'EXCEPTION': str(type(se)),
                        'MESSAGE': str(se),
                        "DATA": {
                            'METHOD': request.get("METHOD"),
                            "ARGS": request.get("ARGS"),
                            "KWARGS": request.get("KWARGS"),
                            'FRAME': frames}
                    }
                }
                self.writer(response)
            except ServerException as me:
                response = {
                    "MPRPC": self.VERSION,
                    "CODE": me.status_code,

                }
                self.writer(response)
            except Exception as e:
                if self.debug:
                    logger.info("Unknow Error: {}[{}]".format(
                        type(e).__name__, str(e)
                    ))
471194
def request(self, type, command_list):
        '''
        
        '''
        req = self._build_request(type, command_list)
        if self.nxargs['connect_over_uds']:
            self.connection.request('POST', req['url'], req['payload'], req['headers'])
            response = self.connection.getresponse()
        else:
            response = self.connection(req['url'],
                                       method='POST',
                                       opts=req['opts'],
                                       data=req['payload'],
                                       header_dict=req['headers'],
                                       decode=True,
                                       decode_type='json',
                                       **self.nxargs)

        return self.parse_response(response, command_list)
1268670
def _execute_show(self, show_command):
        
        rpc_command = '<CLI><Exec>{show_command}</Exec></CLI>'.format(
            show_command=escape_xml(show_command)
        )
        response = self._execute_rpc(rpc_command)
        raw_response = response.xpath('.//CLI/Exec')[0].text
        return raw_response.strip() if raw_response else ''
258052
def _execute_command(self, create_command, tag_info, mode, dic={}):
        
        xml = self._create_dynamic_xml(
            create_command, tag_info, mode, dic)
        d = self._request_ilo(xml)
        data = self._parse_output(d)
        LOG.debug(self._("Received response data: %s"), data)
        return data
1012721
List<QueryResponse> broadcast(ClusteredQueryCommand clusteredQueryCommand) {
      // invoke on own node
      Future<QueryResponse> localResponse = localInvoke(clusteredQueryCommand);
      Map<Address, Response> responses = rpcManager.invokeRemotely(null, clusteredQueryCommand, rpcOptions);
      List<QueryResponse> queryResponses = cast(responses);
      try {
         queryResponses.add(localResponse.get());
      } catch (InterruptedException e) {
         throw new SearchException("Interrupted while searching locally", e);
      } catch (ExecutionException e) {
         throw new SearchException("Exception while searching locally", e);
      }
      return queryResponses;
   }
534517
def rpc(method):
    
    @wraps(method)
    def rpc_wrapper(*args, **kwargs):
        controller_instance = args[0]

        if not isinstance(controller_instance, RemoteControllerDeamon):
            raise Exception("'rpc' decorator must use in a RemoteControllerDeamon (-derived) class method!")

        # Decide the call origin: if the current pid is the daemon pid, this is server side,
        # so call registered method. If not, start a jsonrpc request.
        call_from_server = os.getpid() == controller_instance.get_pid()

        logger.debug("Initiate RPC method '%s' in '%s'", method.__name__, 'daemon' if call_from_server else 'cli')

        if call_from_server:
            return method(*args, **kwargs)
        else:
            url = "http://{}:{}/jsonrpc".format(controller_instance.host, controller_instance.port)
            headers = {'content-type': 'application/json'}

            payload = {
                "method": method.__name__,
                "params": kwargs,
                "jsonrpc": "2.0",
                "id": 0,
            }
            try:
                response = requests.post(url, data=json.dumps(payload), headers=headers).json()
                if 'result' in response:
                    return response['result']
                else:
                    logger.error("There is an error during rpc call. Response:\n%s", json.dumps(response, indent=4))
                    return "Error: {}. (see logs for details)".format(response['error']['message'])
            except requests.exceptions.ConnectionError as e:
                logger.error("Command server not runnning (%s), args: %s, kwargs: %s", e, args, kwargs)
                return None

    rpc_wrapper.registered_for_rpc = method
    return rpc_wrapper
347652
private Serializable executeCommand(RemoteCommand command, Serializable... args) throws RPCException
   {
      try
      {
         return command.execute(args);
      }
      catch (Throwable e)//NOSONAR
      {
         throw new RPCException(e.getMessage(), e);
      }
   }
326975
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):
        

        self._ensure_connection(conn_id, True)
        connection_string = self._get_property(conn_id, "connection_string")

        msg = dict(address=address, rpc_id=rpc_id, payload=base64.b64encode(payload),
                   timeout=timeout, connection_string=connection_string)

        response = await self._send_command(OPERATIONS.SEND_RPC, msg, COMMANDS.SendRPCResponse,
                                            timeout=timeout)

        return unpack_rpc_response(response.get('status'), response.get('payload'),
                                   rpc_id=rpc_id, address=address)
117916
def rpc_request(self, frame_out, connection_adapter=None):
        
        with self.rpc.lock:
            uuid = self.rpc.register_request(frame_out.valid_responses)
            self._connection.write_frame(self.channel_id, frame_out)
            return self.rpc.get_request(
                uuid, connection_adapter=connection_adapter
            )
1253171
def request(command, messages)
      response = StringIO.new String.new(""), "w"
      response.set_encoding "ASCII-8BIT"
      status   = -1
      version  = 0
      length   = 0
      message  = Riddle.encode(Array(messages).join(""), 'ASCII-8BIT')

      connect do |socket|
        case command
        when :search
          if Versions[command] >= 0x118
            socket.send request_header(command, message.length) +
              [0, messages.length].pack('NN') + message, 0
          else
            socket.send request_header(command, message.length) +
              [messages.length].pack('N') + message, 0
          end
        when :status
          socket.send request_header(command, message.length), 0
        else
          socket.send request_header(command, message.length) + message, 0
        end

        header = socket.recv(8)
        status, version, length = header.unpack('n2N')

        while response.length < (length || 0)
          part = socket.recv(length - response.length)

          # will return 0 bytes if remote side closed TCP connection, e.g, searchd segfaulted.
          break if part.length == 0 && socket.is_a?(TCPSocket)

          response << part if part
        end
      end

      response = response.string

      if response.empty? || response.length != length
        raise ResponseError, "No response from searchd (status: #{status}, version: #{version})"
      end

      case status
      when Statuses[:ok]
        if version < Versions[command]
          puts format("searchd command v.%d.%d older than client (v.%d.%d)",
            version >> 8, version & 0xff,
            Versions[command] >> 8, Versions[command] & 0xff)
        end
        response
      when Statuses[:warning]
        length = response[0, 4].unpack('N*').first
        puts response[4, length]
        response[4 + length, response.length - 4 - length]
      when Statuses[:error], Statuses[:retry]
        message = response[4, response.length - 4]
        klass = message[/out of bounds/] ? OutOfBoundsError : ResponseError
        raise klass, "searchd error (status: #{status}): #{message}"
      else
        raise ResponseError, "Unknown searchd error (status: #{status})"
      end
    end