JSON-RPC 2.0 handler.
506166
def jsonrpc(self, request):
        
        if request.method != "POST":
            return HttpResponseNotAllowed(["POST"])

        request_str = request.body.decode('utf8')
        try:
            jsonrpc_request = JSONRPCRequest.from_json(request_str)
        except (TypeError, ValueError, JSONRPCInvalidRequestException):
            response = JSONRPCResponseManager.handle(
                request_str, self.dispatcher)
        else:
            jsonrpc_request.params = jsonrpc_request.params or {}
            jsonrpc_request_params = copy.copy(jsonrpc_request.params)
            if isinstance(jsonrpc_request.params, dict):
                jsonrpc_request.params.update(request=request)

            t1 = time.time()
            response = JSONRPCResponseManager.handle_request(
                jsonrpc_request, self.dispatcher)
            t2 = time.time()
            logger.info('{0}({1}) {2:.2f} sec'.format(
                jsonrpc_request.method, jsonrpc_request_params, t2 - t1))

        if response:
            def serialize(s):
                return json.dumps(s, cls=DatetimeDecimalEncoder)

            response.serialize = serialize
            response = response.json

        return HttpResponse(response, content_type="application/json")
294385
def jsonp(func):
    """"""
    @wraps(func)
    def decorated(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            data = str(func(*args, **kwargs).data)
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype)
        else:
            return func(*args, **kwargs)
    return decorated
916461
def hume_process_jsonld():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    jsonld_str = body.get('jsonld')
    jsonld = json.loads(jsonld_str)
    hp = hume.process_jsonld(jsonld)
    return _stmts_from_proc(hp)
349861
function rpcCall(bugout, pk, call, args, nonce, callback) {
  var packet = {"y": "rr", "rn": nonce};
  if (bugout.api[call]) {
    bugout.api[call](bugout.address(pk), args, function(result) {
      packet["rr"] = JSON.stringify(result);
    });
  } else {
    packet["rr"] = JSON.stringify({"error": "No such API call."});
  }
  packet = makePacket(bugout, packet);
  packet = encryptPacket(bugout, pk, packet);
  sendRaw(bugout, packet);
}
970825
def handle_device_json(self, data):
        """"""
        self._device_json.insert(0, data)
        self._device_json.pop()
992555
async def _on_rpc_command(self, event):
        """"""

        payload = event['payload']
        rpc_id = payload['rpc_id']
        tag = payload['response_uuid']
        args = payload['payload']

        result = 'success'
        response = b''

        if self._rpc_dispatcher is None or not self._rpc_dispatcher.has_rpc(rpc_id):
            result = 'rpc_not_found'
        else:
            try:
                response = self._rpc_dispatcher.call_rpc(rpc_id, args)
                if inspect.iscoroutine(response):
                    response = await response
            except RPCInvalidArgumentsError:
                result = 'invalid_arguments'
            except RPCInvalidReturnValueError:
                result = 'invalid_response'
            except Exception: #pylint:disable=broad-except;We are being called in a background task
                self._logger.exception("Exception handling RPC 0x%04X", rpc_id)
                result = 'execution_exception'

        message = dict(response_uuid=tag, result=result, response=response)

        try:
            await self.send_command(OPERATIONS.CMD_RESPOND_RPC, message,
                                    MESSAGES.RespondRPCResponse)
        except:  #pylint:disable=bare-except;We are being called in a background worker
            self._logger.exception("Error sending response to RPC 0x%04X", rpc_id)
1115793
function (res, res_obj) {

    // return response if exist, otherwise response might be returned 
    // AFTER some callback is done handling (i.e., response will be returned within the handler)
    if (typeof res_obj === 'string') {
        LOG.sys('replying a string: ' + res_obj);
        res.writeHead(200, {'Content-Type': 'text/plain'});                     
        res.end(res_obj);            
    }
    else {
        LOG.sys('replying a JSON: ' + JSON.stringify(res_obj));
        res.writeHead(200, {'Content-Type': 'application/json'});                     
        res.end(JSON.stringify(res_obj));        
    }
}
172169
def json_exception(context, request):
    """"""
    request.response.status = context.code
    return {'error': context._status, 'messages': context.message}
918130
def rpc(rpc_method, attrs={}, req_opts=nil)
      body = Encoding.encode_json(attrs)

      resp = self.class.make_http_request(@conn, @service_full_name, rpc_method, Encoding::JSON, req_opts, body)
      if resp.status != 200
        return ClientResp.new(nil, self.class.error_from_response(resp))
      end

      data = Encoding.decode_json(resp.body)
      return ClientResp.new(data, nil)
    end
432789
function _jsonLoaded(callback, err, data) {
  if (err) return callback(err);
  var parsed;
  try {
    parsed = JSON.parse(data);
  } catch(jerr) {
    return callback(jerr);
  }
  callback(null, parsed);
}
1332623
public void doJson(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        if (req.getParameter("jsonp") == null || permit(req)) {
            setHeaders(rsp);
            rsp.serveExposedBean(req,bean, req.getParameter("jsonp") == null ? Flavor.JSON : Flavor.JSONP);
        } else {
            rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "jsonp forbidden; implement jenkins.security.SecureRequester");
        }
    }
437914
def as_json(context):
    """"""
    info = {
        'info': cgi.escape(pprint.pformat(context.context)),
    }
    return Response(content_type='application/json', body=json.dumps(info))
77838
def json_loads(data):
    """"""
    if data is None:
        return ""

    if data == "-":
        return json.load(sys.stdin)
    elif os.path.exists(data):
        with open(data, 'r') as handle:
            return json.load(handle)
    else:
        return json.loads(data)
80696
function (result) {

      // don't send a second response
      if (responseHasBeenSent) {
        console.warn('JSON-RPC2 response has already been sent.')
        return
      }
      // notifications should not send error responses (JSON-RPC2 specs)
      if (!isMethodCall) {
        logNotificationResponseWarning(result, requestMessage)
        callback()
        return
      }

      // result should not be undefined
      if (result === undefined) {
        console.warn('JSON-RPC2 response from method ' + methodName + ' should return a result. (JSON-RPC2 spec)')
        result = ''
      }

      var rpcMessage = {
        jsonrpc: '2.0',
        result: result,
        id: id
      }

      callback(rpcMessage)
      responseHasBeenSent = true

    }
1028368
function JSONReporter(detector) {
  BaseReporter.call(this, detector);

  detector.on('start', function() {
    process.stdout.write('[');
  });

  detector.on('end', function() {
    process.stdout.write("]\n");
  });
}
1308474
private JsonError handleObject(final ObjectNode node, final OutputStream output) throws IOException {
		logger.debug("Request: {}", node);
		
		if (!isValidRequest(node)) {
			return writeAndFlushValueError(output, createResponseError(VERSION, NULL, JsonError.INVALID_REQUEST));
		}
		Object id = parseId(node.get(ID));
		
		String jsonRpc = hasNonNullData(node, JSONRPC) ? node.get(JSONRPC).asText() : VERSION;
		if (!hasNonNullData(node, METHOD)) {
			return writeAndFlushValueError(output, createResponseError(jsonRpc, id, JsonError.METHOD_NOT_FOUND));
		}

		final String fullMethodName = node.get(METHOD).asText();
		final String partialMethodName = getMethodName(fullMethodName);
		final String serviceName = getServiceName(fullMethodName);
		
		Set<Method> methods = findCandidateMethods(getHandlerInterfaces(serviceName), partialMethodName);
		if (methods.isEmpty()) {
			return writeAndFlushValueError(output, createResponseError(jsonRpc, id, JsonError.METHOD_NOT_FOUND));
		}
		AMethodWithItsArgs methodArgs = findBestMethodByParamsNode(methods, node.get(PARAMS));
		if (methodArgs == null) {
			return writeAndFlushValueError(output, createResponseError(jsonRpc, id, JsonError.METHOD_PARAMS_INVALID));
		}
		try (InvokeListenerHandler handler = new InvokeListenerHandler(methodArgs, invocationListener)) {
			try {
				if (this.requestInterceptor != null) {
					this.requestInterceptor.interceptRequest(node);
				}
				Object target = getHandler(serviceName);
				// interceptors preHandle
				for (JsonRpcInterceptor interceptor : interceptorList) {
					interceptor.preHandle(target, methodArgs.method, methodArgs.arguments);
				}
				// invocation
				JsonNode result = invoke(target, methodArgs.method, methodArgs.arguments);
				handler.result = result;
				// interceptors postHandle
				for (JsonRpcInterceptor interceptor : interceptorList) {
					interceptor.postHandle(target, methodArgs.method, methodArgs.arguments, result);
				}
				if (!isNotificationRequest(id)) {
					ObjectNode response = createResponseSuccess(jsonRpc, id, handler.result);
					writeAndFlushValue(output, response);
				}
				return JsonError.OK;
			} catch (Throwable e) {
				handler.error = e;
				return handleError(output, id, jsonRpc, methodArgs, e);
			}
		}
	}
246560
def RPC(self, url, opname, obj, replytype=None, **kw):
        '''
        '''
        self.Send(url, opname, obj, **kw)
        return self.Receive(replytype, **kw)