Ejemplo n.º 1
0
    def handle(self):
        while True:
            try:
                data = self._read_message()
                log.debug("Got message: %s", data)

                if self._shutdown:
                    # Handle only the exit notification when we're shut down
                    JSONRPCResponseManager.handle(data, {'exit': self.exit})
                    break

                if isinstance(data, bytes):
                    data = data.decode("utf-8")

                msg = json.loads(data)
                if 'method' in msg:
                    # It's a notification or request
                    # Dispatch to the thread pool for handling
                    response = JSONRPCResponseManager.handle(data, self)
                    if response is not None:
                        self._write_message(response.data)
                else:
                    # Otherwise, it's a response message
                    on_result, on_error = self._callbacks.pop(msg['id'])
                    if 'result' in msg and on_result:
                        on_result(msg['result'])
                    elif 'error' in msg and on_error:
                        on_error(msg['error'])
            except Exception:
                log.exception("Language server exiting \
                               due to uncaught exception")
                break
    def process(self):
        """
        Each time this method is called, the socket tries to retrieve data and passes
        it to the JSONRPCResponseManager, which in turn passes the RPC to the
        ExposedObjectCollection.

        In case no data are available, the method does nothing. This behavior is required for
        Lewis where everything is running in one thread. The central loop can call process
        at some point to process remote calls, so the RPC-server does not introduce its own
        infinite processing loop.

        If the server has not been started yet (via :meth:`start_server`), a RuntimeError
        is raised.
        """
        if self._socket is None:
            raise RuntimeError('The server has not been started yet, use start_server to do so.')

        try:
            request = self._socket.recv_unicode(flags=zmq.NOBLOCK)

            try:
                response = JSONRPCResponseManager.handle(request, self._exposed_object)
                self._socket.send_unicode(response.json)
            except TypeError as e:
                self._socket.send_json(
                    self._unhandled_exception_response(json.loads(request)['id'], e))
        except zmq.Again:
            pass
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["echo"] = lambda s: s

    response = JSONRPCResponseManager.handle(
        request.get_data(cache=False, as_text=True), dispatcher)
    return Response(response.json, mimetype='application/json')
    def process(self, blocking=False):
        """
        Each time this method is called, the socket tries to retrieve data and passes
        it to the JSONRPCResponseManager, which in turn passes the RPC to the
        ExposedObjectCollection.

        In case no data are available, the method does nothing. This behavior is required for
        Lewis where everything is running in one thread. The central loop can call process
        at some point to process remote calls, so the RPC-server does not introduce its own
        infinite processing loop.

        If the server has not been started yet (via :meth:`start_server`), a RuntimeError
        is raised.

        :param blocking: If True, this function will block until it has received data or a timeout
                         is triggered. Default is False to preserve behavior of prior versions.
        """
        if self._socket is None:
            raise RuntimeError('The server has not been started yet, use start_server to do so.')

        try:
            request = self._socket.recv_unicode(flags=zmq.NOBLOCK if not blocking else 0)

            self.log.debug('Got request %s', request)

            try:
                response = JSONRPCResponseManager.handle(request, self._exposed_object)
                self._socket.send_unicode(response.json)

                self.log.debug('Sent response %s', response.json)
            except TypeError as e:
                self._socket.send_json(
                    self._unhandled_exception_response(json.loads(request)['id'], e))
        except zmq.Again:
            pass
Ejemplo n.º 5
0
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["echo"] = lambda s: s
    dispatcher["add"] = lambda a, b: a + b

    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 6
0
 def on_get(self, req, resp):
     params = req.params
     method = params['method']
     param = params.copy()
     param.pop('method')
     write_log(str(param))
     resp_data = {
         "method": method,
         "params": param,
         "jsonrpc": "2.0",
         "id": "0",
     }
     write_log(str(json.dumps(resp_data)))
     response = JSONRPCResponseManager.handle(json.dumps(resp_data),
                                              dispatcher)
     resp.content_type = 'application/json'
     resp.status = falcon.HTTP_200
     # 添加响应头
     resp.append_header("Access-Control-Allow-Origin", "*")
     resp.append_header("Access-Control-Allow-Methods", "*")
     # 设置cookies
     resp.set_cookie('my_cookie',
                     'Zxx',
                     max_age=600,
                     domain='95.169.12.124')
     # body 是json格式
     resp.body = response.json
Ejemplo n.º 7
0
def application(request):
    try:
        dispatcher["geo.district_number.numbers"] = json_rpc_except(
            geo_numbers_by_district_number
        )
        dispatcher["geo.suburb_number.numbers"] = json_rpc_except(
            geo_numbers_by_suburb_number
        )
        dispatcher["geo.suburb_number.genus.numbers"] = json_rpc_except(
            geo_genus_numbers_by_suburb_number
        )
        dispatcher["geo.suburb_number.age"] = json_rpc_except(geo_age_by_suburb_number)
        
        dispatcher["tree.attr.age.numbers"] = json_rpc_except(tree_attr_age_numbers)
        dispatcher["tree.attr.genus.numbers"] = json_rpc_except(tree_attr_genus_numbers)
        dispatcher["tree.attr.name_german.numbers"] = json_rpc_except(tree_attr_name_german_numbers)
        
        dispatcher["tree.geo.name_german.suburb.numbers"] = json_rpc_except(tree_geo_name_german_suburb_numbers)
        
        response = JSONRPCResponseManager.handle(request.data, dispatcher)
        return Response(response.json, mimetype="application/json")
    except Exception as e:
        return Response(
            json.dumps({"status": f"ERROR: {e}"}).encode(),
            content_type="application/json",
        )
    except HTTPException as e:
        return http_exception(request, e)
Ejemplo n.º 8
0
def application(request):
    # get the request path
    #    print(request.path)
    # get the request host
    #    print(request.host)
    # get the request method
    print(request.args.get('PATH_INFO'))

    arpObject = Arp()
    rpCloudObject = RpCloud()
    sysRpObject = SysRp()
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher['scanARP'] = arpObject.update
    dispatcher['getArpTable'] = arpObject.getTable
    dispatcher['login'] = rpCloudObject.login
    dispatcher['checkPassword'] = rpCloudObject.checkPassword
    dispatcher['checkLogin'] = rpCloudObject.checkLogin
    dispatcher['logout'] = rpCloudObject.logout
    dispatcher['getHostname'] = sysRpObject.getHostname
    dispatcher['reboot'] = sysRpObject.reboot
    dispatcher['setHostname'] = sysRpObject.setHostname
    dispatcher['generateJson'] = sysRpObject.generateJson
    dispatcher['storageJson'] = sysRpObject.storageJson

    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 9
0
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["submit_block"] = lambda block: child_chain.submit_block(block)
    dispatcher[
        "apply_transaction"] = lambda transaction: child_chain.apply_transaction(
            transaction)
    dispatcher[
        "get_transaction"] = lambda blknum, txindex: child_chain.get_transaction(
            blknum, txindex)
    dispatcher["get_current_block"] = lambda: child_chain.get_current_block()
    dispatcher[
        "get_current_block_num"] = lambda: child_chain.get_current_block_num()
    dispatcher["get_block"] = lambda blknum: child_chain.get_block(blknum)
    dispatcher["get_balances"] = lambda address: child_chain.get_balances(
        Web3.toChecksumAddress(address))
    dispatcher["get_utxos"] = lambda address, currency: child_chain.get_utxos(
        Web3.toChecksumAddress(address), currency)
    dispatcher["get_open_orders"] = lambda: child_chain.get_open_orders()
    dispatcher[
        "get_makeorder_txn"] = lambda address, currency, amount, tokenprice: child_chain.get_makeorder_txn(
            address, currency, int(amount), int(tokenprice))[1]
    dispatcher[
        "submit_signed_makeorder_txn"] = lambda address, currency, amount, tokenprice, makeorder_txn_hex, signature: child_chain.submit_signed_makeorder_txn(
            address, currency, int(amount), int(tokenprice), makeorder_txn_hex,
            signature)
    dispatcher[
        "get_takeorder_txn"] = lambda address, utxopos, amount: child_chain.get_takeorder_txn(
            address, int(utxopos), int(amount))[1]
    dispatcher[
        "submit_signed_takeorder_txn"] = lambda address, utxopos, amount, takeorder_txn_hex, signature: child_chain.submit_signed_takeorder_txn(
            address, int(utxopos), int(amount), takeorder_txn_hex, signature)
    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 10
0
def pub_response(d, mess):
    topic = "test-sn"
    message = mess.decode('ASCII')
    response = JSONRPCResponseManager.handle(message, d)
    print(response.data)
    socket_pub.send_string(topic, zmq.SNDMORE)
    socket_pub.send_string(json.dumps(response.data))
Ejemplo n.º 11
0
    def application(self, request):
        """Define the JSON-RPC callbacks and handle an incoming request."""
        dispatcher['getPeers'] = self.__handle_get_peers
        dispatcher['advertisePeer'] = self.__handle_advertise_peer
        dispatcher['sendBlock'] = self.__handle_send_block
        dispatcher['sendTransaction'] = self.__handle_send_transaction
        dispatcher['requestBlock'] = self.__handle_request_block
        dispatcher['requestBlockByHash'] = self.__handle_request_block_by_hash
        dispatcher['requestTransaction'] = self.__handle_request_transaction
        dispatcher[
            'requestBlocksByHashRange'] = self.__handle_request_blocks_by_hash_range

        # insert IP address of peer if advertise peer is called
        try:
            request_body_dict = json.loads(request.data.decode())
        except ValueError:
            return Response(status=HTTP_BAD_REQUEST)
        if request_body_dict['method'] == 'advertisePeer':
            if 'params' not in request_body_dict:
                request_body_dict['params'] = [6666]
            request_body_dict['params'].insert(0, request.remote_addr)
        request.data = json.dumps(request_body_dict)

        response = JSONRPCResponseManager.handle(request.data, dispatcher)
        return Response(response.json, mimetype='application/json')
Ejemplo n.º 12
0
def application(request):
    dispatcher["echo"] = lambda s: s
    dispatcher["barcode"] = processBarcodeImg

    response = JSONRPCResponseManager.handle(
        request.get_data(cache=False, as_text=True), dispatcher)
    return Response(response.json, mimetype='application/json') 
    def _process_request(self, input_json_str):
        """
        Handles incoming requests or rather dispatches to appropriate
        rpc method

        Parameters :
            input_json_str - JSON formatted str of the request
        Returns :
            response - data field from the response received which is a dict
        """
        response = {}
        response['error'] = {}
        response['error']['code'] = \
            JRPCErrorCodes.INVALID_PARAMETER_FORMAT_OR_VALUE

        try:
            input_json = json.loads(input_json_str)
            logger.info("Received request: %s", input_json['method'])
        except Exception as err:
            logger.error("exception loading Json: %s", str(err))
            response["error"]["message"] = "Improper Json request"
            return response

        # save the full json for WorkOrderSubmit
        input_json["params"]["raw"] = input_json_str
        data = json.dumps(input_json).encode('utf-8')
        response = JSONRPCResponseManager.handle(data, self.dispatcher)
        return response.data
Ejemplo n.º 14
0
def handle_message(json, methods=['GET', 'POST']):
    user_name_info = requests.form['user_name']
    message_info = requests.form['message']
    add_info = Dialogue(user=user_name_info, message=message_info)
    add_info.save()
    response = JSONRPCResponseManager.handle(message_info, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 15
0
 def index(self):
     try:
         data = cherrypy.request.body.read().decode('utf-8')
     except ValueError:
         raise cherrypy.HTTPError(400, 'Invalid JSON document')
     response = JSONRPCResponseManager.handle(data, dispatcher)
     return response.json
Ejemplo n.º 16
0
def application(request):
    dispatcher["echo"] = lambda s: s
    dispatcher["add"] = lambda a, b: a + b

    response = JSONRPCResponseManager.handle(
        request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 17
0
def main() -> None:
    if os.environ.get("AUTOREST_PYTHON_ATTACH_VSCODE_DEBUG", False):
        try:
            import ptvsd  # pylint: disable=import-outside-toplevel
        except ImportError:
            raise SystemExit(
                "Please pip install ptvsd in order to use VSCode debugging")

        # 5678 is the default attach port in the VS Code debug configurations
        ptvsd.enable_attach(address=("localhost", 5678), redirect_output=True)
        ptvsd.wait_for_attach()
        breakpoint()  # pylint: disable=undefined-variable

    _LOGGER.debug("Starting JSON RPC server")

    while True:
        _LOGGER.debug("Trying to read")
        message = read_message()

        response = JSONRPCResponseManager.handle(message, dispatcher).json
        _LOGGER.debug("Produced: %s", response)
        write_message(response)
        _LOGGER.debug("Message processed")

    _LOGGER.debug("Ending JSON RPC server")
Ejemplo n.º 18
0
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["findKeyWords"] = findKeyWords
    dispatcher["cutWords"] = cutWords
    dispatcher["calcKeyWords"] = calcKeyWords
    dispatcher['crawl'] = crawl
    dispatcher['getMovieInfo'] = getMovieInfo
    dispatcher['recommendForUser'] = recommendForUser
    dispatcher['getSimilarMovies'] = getSimilarMovies
    dispatcher[
        'get_hist_distribution_of_imdb_score'] = get_hist_distribution_of_imdb_score
    dispatcher[
        'get_hist_distribution_of_imdb_review_count'] = get_hist_distribution_of_imdb_review_count
    dispatcher['get_cdf_of_imdb_score'] = get_cdf_of_imdb_score
    dispatcher['get_kde_of_imdb_score'] = get_kde_of_imdb_score
    dispatcher['get_kde_of_imdb_review_count'] = get_kde_of_imdb_review_count
    dispatcher['get_score_of_single_year'] = get_score_of_single_year
    dispatcher['get_box_office_of_single_year'] = get_box_office_of_single_year
    dispatcher['predict_score'] = predict_score
    dispatcher['predict_box_office'] = predict_box_office
    dispatcher['crawlForPredication'] = crawlForPredication
    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    print("Request:", request.data)
    print("Response:", response.json)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 19
0
 def handle_request(self, body):
     response = JSONRPCResponseManager.handle(body, self.dispatcher)
     if isinstance(response.result, Future):
         response.result.add_done_callback(
             partial(self.on_done, data=response.data))
     else:
         self.send_data(response.data)
Ejemplo n.º 20
0
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["Say.Hello"] = lambda s: "hello " + s["name"]

    response = JSONRPCResponseManager.handle(
        request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 21
0
    def _process_request(self, input_json_str):
        response = {}
        response['error'] = {}
        response['error']['code'] = \
            WorkOrderStatus.INVALID_PARAMETER_FORMAT_OR_VALUE

        try:
            input_json = json.loads(input_json_str)
        except Exception as err:
            logger.exception("exception loading Json: %s", str(err))
            response = {
                "error": {
                    "code": WorkOrderStatus.INVALID_PARAMETER_FORMAT_OR_VALUE,
                    "message": "Error: Improper Json. Unable to load",
                },
            }
            return response

        logger.info("Received request: %s", input_json['method'])
        # save the full json for WorkOrderSubmit
        input_json["params"]["raw"] = input_json_str

        data = json.dumps(input_json).encode('utf-8')
        response = JSONRPCResponseManager.handle(data, self.dispatcher)
        return response.data
Ejemplo n.º 22
0
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["setPosition"] = set_position
    dispatcher["get_position"] = get_position
    dispatcher["find_text"] = find_text
    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 23
0
    def application(request):
        # Dispatcher is dictionary {<method_name>: callable}
        dispatcher["Endpoint.WaitForData"] = wait_for_data
        dispatcher["Endpoint.SendToDownLink"] = send_to_down_link

        response = JSONRPCResponseManager.handle(request.data, dispatcher)
        return Response(response.json, mimetype='application/json')
Ejemplo n.º 24
0
def evaluate_jrpc_request(string):
    """ Evaluates a JSON-RPC request provided as a string.

        Returns the result of this evaluation (a JSON-RPC response) as a string.
    """
    response = JSONRPCResponseManager.handle(string, dispatcher)
    return response.json
Ejemplo n.º 25
0
    def serveApplication(self, request):
        try:
            rjson = json.loads(request.data.decode("ascii"))
        except:
            apiresponse = Response({}, mimetype="application/json")
            apiresponse.headers.add("Access-Control-Allow-Origin", "*")
            apiresponse.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH")
            apiresponse.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")
            return apiresponse

        if rjson["method"] in self.RPCDispatcher:
            nargs = len(inspect.getargspec(self.RPCDispatcher[rjson["method"]]).args) - 1

            if len(rjson["params"]) != nargs:
                logger.error('Client invalid request arguments: "%s" %s', rjson["method"], str(rjson["params"]))
            else:
                if rjson["method"].find("get") == -1 and rjson["method"].find("info") == -1:
                    logger.debug("Client request: %s", rjson["method"])
        else:
            logger.error('Client invalid request: "%s" %s', rjson["method"], str(rjson["params"]))

        response = JSONRPCResponseManager.handle(request.data, self.RPCDispatcher)
        apiresponse = Response(response.json, mimetype="application/json")
        apiresponse.headers.add("Access-Control-Allow-Origin", "*")
        apiresponse.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH")
        apiresponse.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")
        return apiresponse
Ejemplo n.º 26
0
def application(request):

    # default status dispatch method (returns "OK")
    dispatcher["Status.Ping"] = lambda: "OK"

    # if we pass in the arg "tictactoe" then we know to accept tictactoe messages
    if sys.argv[1] == "tictactoe":  

        if json.loads(request.data)['params'] is not None:
            jsonLoad = json.loads(request.data)
            gamestate = jsonLoad['params']['gamestate']

        dispatcher["TicTacToe.Error"] = TicTacToe.Error
        dispatcher["TicTacToe.NextMove"] = TicTacToe.NextMove
        dispatcher["TicTacToe.Complete"] = TicTacToe.Complete
    elif sys.argv[1] == 'scrabble':
        s = Scrabble()
        dispatcher["Scrabble.Ping"] = Scrabble.Ping
        pass
        #todo - put scrabble functions in here

    response = JSONRPCResponseManager.handle(
        request.data, dispatcher)
    
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 27
0
def application(request):
    agent = ServerAgent()

    for x in ['get_angle', 'set_angle', 'get_posture', 'execute_keyframes', 'get_transform', 'set_transform']:
        dispatcher[x] = getattr(agent, x)

    return Response(JSONRPCResponseManager.handle(request.data, dispatcher).json, mimetype = 'application/json')
Ejemplo n.º 28
0
def application(request):
     # Dispatcher is dictionary {<method_name>: callable}
    for func in [get_balance, get_transactions, broadcast_transaction]:
        dispatcher[func.__name__] = func

    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 29
0
def pub_response(d, mess):
    message = mess.decode('ASCII')
    topic, request = message.split(" ", 1)
    new_topic = get_new_topic(topic)
    response = JSONRPCResponseManager.handle(request, d)
    print(topic, new_topic)
    socket_pub.send_string("%s %s" % (new_topic, json.dumps(response.data)))
Ejemplo n.º 30
0
 def handle(self):
     while True:
         data = self.__read_message()
         logger.debug(f"Receive message: {data}")
         response = JSONRPCResponseManager.handle(data, self.dispatcher)
         if response is not None:
             logger.debug(f"Send message: {response.data}")
             self.__write_message(data=response.data)
Ejemplo n.º 31
0
	def handle(self):
		request = recvBytes(self.request)
		self._logger.info("Received request")
		response = JSONRPCResponseManager.handle(request, self.dispatcher)
		sendBytes(self.request, response.json)
		if response.error is not None:
			self._logger.info("Received request, ERROR [%s] %s",
					response.error['code'], response.error['message'])
Ejemplo n.º 32
0
def application(request):
    dispatcher["hello"] = hello
    dispatcher["add"] = lambda a, b: a + b

    print("debug " + request.data)
    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    print("debug " + response.json)
    return Response(response.json, mimetype="application/ json")
Ejemplo n.º 33
0
def application(request):
    player = Player()
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["soundList"] = lambda: player.soundList()
    dispatcher["play"] = lambda soundName: player.play(soundName)

    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 34
0
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["echo"] = lambda s: s
    dispatcher['checkPassword'] = checkPassword
    dispatcher['scanARP'] = scan

    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 35
0
	def handle(self):
		self.data = self.rfile.readline()
		print("{} wrote:".format(self.client_address[0]))
		print(self.data)
		# msg = json.loads(self.data)
		# meth = msg["method"]
		response = JSONRPCResponseManager.handle(self.data, dispatcher)
		self.wfile.write(response.json.encode("utf-8"))
Ejemplo n.º 36
0
    def on_message(self, message):
        response = JSONRPCResponseManager.handle(message, dispatcher)

        if response.error:
            logger.error(response.error)

        response.serialize = response_serialize
        self.write_message(response.json)
Ejemplo n.º 37
0
def handle_rpc_client_stateful(sock, cert, key_file, state_dispatchers, global_dispatcher, get_state_lock_func):
    ssl_sock = wrap_server_socket(sock, cert, key_file)

    # Wait for input, and respond
    with ssl_sock:
        while True:
            data = recv_ssl_msg(ssl_sock)
            rpc_input = data.decode()
            print("RPC STATEFUL DEBUG INPUT: " + str(rpc_input)[0:120])
            (state, rwlock) = get_state_lock_func()[0:2]
            with rwlock.reader:
                rpc_output = JSONRPCResponseManager.handle(rpc_input, state_dispatchers[state])
                if rpc_output.error and rpc_output.error["code"] == JSONRPCMethodNotFound.CODE:
                    rpc_output = JSONRPCResponseManager.handle(rpc_input, global_dispatcher)
            if rpc_output:
                print("RPC STATEFUL DEBUG OUTPUT: " + str(rpc_output.json)[0:120])
                send_ssl_msg(ssl_sock, rpc_output.json.encode())
Ejemplo n.º 38
0
def recv_handler(handler, data):
    request = data.decode('utf-8').strip()
    response = JSONRPCResponseManager.handle(request, dispatcher)
    print('=' * 50)
    print('Request: ' + request)
    echo_server.send_data(handler, response.json.encode('utf-8'))
    print('Response: ' + response.json)
    print('=' * 50)
Ejemplo n.º 39
0
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["echo"] = lambda s: s
    dispatcher["add"] = lambda a, b: a + b

    response = JSONRPCResponseManager.handle(
        request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 40
0
def application(request):
    dispatcher["ydl.getQueue"] = download.GetQueue
    dispatcher["ydl.addQueue"] = download.AddItemQueue
    dispatcher["ydl.setSettings"] = download.SetSettings
    dispatcher["ydl.getSettings"] = download.GetSettings

    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 41
0
def application(request):

    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher["checkversion"] = CheckVersion
    dispatcher["ServerLog"] = ServerLog
    response = JSONRPCResponseManager.handle(
        request.get_data(cache=False, as_text=True), dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 42
0
 def run(self):
     try:
         while True:
             message = self.rpc_socket.recv_string()
             response = JSONRPCResponseManager.handle(message, self.dispatcher)
             self.rpc_socket.send_string(response.json)
     finally:
         self.gpio_manager.clean_up()
Ejemplo n.º 43
0
    def receive(self, request):
        response = None
        try:
            response = JSONRPCResponseManager.handle(
                request.data, dispatcher)
        except Exception:
            response = "Not Found"

        return Response(response.json, mimetype='application/json')
Ejemplo n.º 44
0
 def select_task(self, data):
     if data:
         data_split = data.splitlines()
         for line in data_split:
             if line:
                 try:
                     self.transport.write(JSONRPCResponseManager.handle(line, dispatcher).json.encode())
                 except TypeError as te:
                     log.warning("Can't send response: %s", te)
Ejemplo n.º 45
0
	def application(self,request):
		# Dispatcher is dictionary {<method_name>: callable}
		dispatcher["echo"] = lambda s: s
		dispatcher["cl2ct_report"] = self.recv_report
		print 'revice data',request.data

		response = JSONRPCResponseManager.handle(
			request.data, dispatcher)
		return Response(response.json, mimetype='application/json')
Ejemplo n.º 46
0
 def on_message(self, message):
     """
     Passes an incoming JSON-RPC message to the dispatcher for processing.
     """
     LOGGER.debug('Message received from {0}: {1}'.format(
         self.request.remote_ip, message))
     response = JSONRPCResponseManager.handle(message, self.dispatcher)
     LOGGER.debug('Sending response to {0}: {1}'.format(
             self.request.remote_ip, response._data))
     self.write_message(response.json)
Ejemplo n.º 47
0
def application(request):
    dispatcher["mightywatt_readstatus"] = mightywatt.read_status
    dispatcher["mightywatt_setpower"] = mightywatt.set_power
    dispatcher["charger_readstatus"] = charger.read_status
    dispatcher["discharger_readstatus"] = discharger.read_status
    dispatcher["mppt_readstatus"] = mppt.read_status

    response = JSONRPCResponseManager.handle(
        request.data, dispatcher)
    return Response(response.json, mimetype='application/json')
Ejemplo n.º 48
0
def application(request):
    response = JSONRPCResponseManager.handle(
        request.data,
        dispatcher,
    )
    response = Response(
        json.dumps(force_obj_to_text(response.data, True)),
        headers=RESPONSE_HEADERS,
        mimetype='application/json',
    )
    return response
Ejemplo n.º 49
0
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    dispatcher['auth'] = auth
    dispatcher['shutdown'] = shutdown
    dispatcher['send_message'] = send_message

    response = JSONRPCResponseManager.handle(
        request.get_data(cache=False, as_text=True),
        dispatcher
    )

    return Response(response.json, mimetype='application/json')
Ejemplo n.º 50
0
def application(request):
    # Dispatcher is dictionary {<method_name>: callable}
    response = JSONRPCResponseManager.handle(
        request.data, dispatcher)
    rv = Response(response.json, mimetype='application/json')

    rv.headers.add('Access-Control-Allow-Origin', '*')
    rv.headers.add('Access-Control-Allow-Methods',
                   'GET,PUT,POST,DELETE,PATCH')
    rv.headers.add('Access-Control-Allow-Headers',
                   'Content-Type, Authorization')    
    
    return rv
Ejemplo n.º 51
0
def application(request):
	# Dispatcher is dictionary {<method_name>: callable}
	dispatcher["echo"] = lambda s: "ok"
	dispatcher["add"] = lambda a, b: a + b
	resp_dict = {'ret':0}
	print 'revice data',request.data
	print 'revice data',request
	print 'revice data',request.host_url
	print 'revice data',request.host

	response = JSONRPCResponseManager.handle(
		request.data, dispatcher)
	print response.json
	return Response(response.json, mimetype='application/json')
Ejemplo n.º 52
0
 def application(self, request ):
     """    Nxt2Btc_Mapping_Comments
          1 BitcoinD Command/RPC	
          2 Parameters	
          3 Description	
          4 Requires unlocked wallet? (v0.4.0+)	
          5 Supported in nxtcoind v1.0	
          6 BitcoinD return format	
          7 NXT API	
          8 NXT format	
          9 Implementation Rules How to map a NXT API return to a XXXCOIND API return
         """
      
     response = JSONRPCResponseManager.handle(request.get_data(cache=False, as_text=True), dispatcher)
     return    Response(response.json, mimetype='application/json') 
Ejemplo n.º 53
0
            def index(self):
                cherrypy.response.headers["Content-Type"] = "application/json"
                cherrypy.response.headers["Access-Control-Allow-Origin"] = '*'
                cherrypy.response.headers["Access-Control-Allow-Methods"] = 'POST, GET, OPTIONS'
                cherrypy.response.headers["Access-Control-Allow-Headers"] = 'Origin, X-Requested-With, Content-Type, Accept'

                if cherrypy.request.method == "OPTIONS": #web client will send us this before making a request
                    return

                try:
                    data = cherrypy.request.body.read().decode('utf-8')
                except ValueError:
                    raise cherrypy.HTTPError(400, 'Invalid JSON document')
                response = JSONRPCResponseManager.handle(data, dispatcher)
                return response.json.encode()
Ejemplo n.º 54
0
 def application(self,request):
     # Dispatcher is dictionary {<method_name>: callable}
     bmcUtil = Util()
     bmcListOfMethods = {}
     bmcListOfMethod = bmcUtil.readLocalAppVariableFile("BMC_JSONRPCCALL_METHODS")
     bmcListOfMethod = bmcUtil.removeDoubleQuotas(bmcListOfMethod)
     bmcListOfMethods = bmcListOfMethod.split(",")
     for methodName in bmcListOfMethods:
         dispatcher[methodName] = lambda methodName: methodName
         #dispatcher["event"] = lambda a: a
     response = JSONRPCResponseManager.handle(
     request.data, dispatcher)
     print response.json
     bmcUtil.writeRPCCallDataTOFile(response.json)
     return Response(response.json, mimetype='application/json')
Ejemplo n.º 55
0
    def do_POST(self):
        varLen = int(self.headers['Content-Length'])
        post_data = self.rfile.read(varLen)
        # You now have a dictionary of the post data

        [print(c) for c in dispatcher]
        response = JSONRPCResponseManager.handle(
            post_data, dispatcher)

        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.flush_headers()

        self.wfile.write(response.json.encode("utf-8"))
Ejemplo n.º 56
0
    def do_POST(self):
        try:
            #Get arguments by reading body of request.
            #We read this in chunks to avoid straining
            #socket.read(); around the 10 or 15Mb mark, some platforms
            #begin to have problems (bug #792570).
            max_chunk_size = 10*1024*1024
            size_remaining = int(self.headers["Content-Length"])
            L = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                chunk = self.rfile.read(chunk_size)
                if not chunk:
                    break
                L.append(chunk)
                size_remaining -= len(L[-1])
            data = b''.join(L)
            headers_str = str(self.headers).strip()
            self.log_message('Received communication:\n%s\n%s', 
                             headers_str, data)
            #.NET will put a Byte Order Mark before UTF-8 text, which will cause
            #an error in the JSON parser. Delete the BOM if it's there.
            if data.startswith(codecs.BOM_UTF8):
                data = data[len(codecs.BOM_UTF8):]

            #Parse the JSON-RPC request and execute the function
            response = JSONRPCResponseManager.handle(data, dispatcher)
            response_json = response.json
            self.log_message("Responding with: %s", response_json)
        except Exception as e: 
            #Things like invalid function names or exceptions in called 
            #methods won't cause an exception, the jsonrpc module will 
            #return an 'error' field in the response, per the JSON RPC 2.0 
            #spec. This will only happen if there's a bug in the block above.
            self.send_response(500)
            exception_header = '{}:{}'.format(e.__class__.__name__, str(e))
            self.send_header("Atragon-Exception", exception_header)
            trace = traceback.format_exc()
            trace = str(trace.encode('utf-8', 'backslashreplace'), 'utf-8')
            self.send_header("Atragon-Traceback", trace)
            self.send_header("Content-Length", "0")
            self.end_headers()
        else:
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Content-Length', str(len(response_json)))
            self.end_headers()
            self.wfile.write(bytes(response_json, 'utf-8'))
Ejemplo n.º 57
0
    async def post(self):
        dispatcher = self.request.app.get("jsonrpc_dispatcher", None)
        if dispatcher is None:
            raise IskHttpServerException("JSONRPC dispatcher not found. Place it in server app")

        request_text = await self.request.text()

        # TODO: Make this non-blocking
        # TODO: Meaningful error handling of JSON-RPC calls
        try:
            response = JSONRPCResponseManager.handle(request_text, dispatcher)
        except Exception:
            response = JSONRPCServerError()
            logger.error("JSON-RPC Error", exc_info=True)

        return self.basic_response(text=response.json, content_type="application/json")
Ejemplo n.º 58
0
	def dispatch_request(self, request):
		print "hello"
			
		# JSON RPC Handler
		
		response = JSONRPCResponseManager.handle(
					request.data, dispatcher)
		#	print "dispatch", response.json,response.error
		if response.error:
			# if the error is a parse json error (-32700) means it is not an RPC call
			if response.error['code']!=-32700:
				# return the error json
				return returnJson(response.json) 
			else:
				pass # continue to process request below
		else:
			#print "*********#### "+help(request)
			print  request.remote_addr, request.remote_user #.host_url+" "+request.url
			return returnJson(response.json)
		
		adapter = self.url_map.bind_to_environ(request.environ)
		
		# Normal Request Handler
		try:
			endpoint, values = adapter.match()
			if hasattr(self, 'on_' + endpoint):
				return getattr(self, 'on_' + endpoint)(request, **values)
			else:
				for pxClass in self.pxClasses:
					if hasattr(pxClass, 'on_' + endpoint):
						pxClass.render_template=self.render_template
						if 'docs' in request.args:
							return Response("<pre>Documentation"+str(dir(request))+"\n"+request.path+'\n'+request.remote_addr+
											getattr(pxClass, 'on_' + endpoint).__doc__+"</pre>",
											mimetype='text/html')
						result = getattr(pxClass, 'on_' + endpoint)(request, **values)
						if result.__class__!=Response:
							return returnJson(result)
						return result

		except NotFound, e:
			return self.error_404(request)
Ejemplo n.º 59
0
    def application(self,request):
        self.request = json.loads(request.data.decode("utf-8"))
        #print(request)
        # Dispatcher is dictionary {<method_name>: callable}
        dispatcher["update"] = self.update
        dispatcher["connect"] = self.player_connect
        dispatcher["status"] = self.status
        dispatcher["wizard_conditions"] = self.wizard_conditions
        dispatcher["player_data"] = self.player_data
        dispatcher["allocation"] = self.allocation_command


        response = JSONRPCResponseManager.handle(
            request.data, dispatcher)
        if response.data['id'] != 1 and 'result' not in response.data:
            print(request.data,'\n',response.data)
            logging.error('_______________________________________________' +
                          '\nRequiest is faulty or its handling was not successfull:\n'+
                          request.data + '\nResponce:\n' + response.data +
                          '\n---------------------------------------------')
        if response.data['id'] == 1000:
            print(request.data,'\n',response.data)

        return Response(response.json, mimetype='application/json')
def application(request):
    response = JSONRPCResponseManager.handle(request.data, dispatcher)
    return Response(response.json, mimetype='application/json')