Calls jsonrpc service's method and returns its return value in a JSON
        string or None if there is none.

        Arguments:
        jsondata -- remote method call in jsonrpc format
329
def call(self, jsondata):
        
        result = yield self.call_py(jsondata)
        if result is None:
            defer.returnValue(None)
        else:
            defer.returnValue(json.dumps(result))
704763
function parseData(json, callback) {
		try {
			var data = JSON.parse(json);
			if (data && data.hasOwnProperty('result'))
				doCallback(callback.success, data.result);
			else if (data && data.hasOwnProperty('error') && data.error)
				doCallback(callback.error, error(data.error.message, data.error.code, null));
			else
				doCallback(callback.error, error("INVALID_RESPONSE", -1, {
					responses: json.toString()
				}));
		}
		catch (e) {
			doCallback(callback.error, error("INVALID_RESPONSE", -1, {
				exception: e,
				response: json.toString()
			}));
		}
	}
536593
def json_or_jsonp(func):
    """"""
    @wraps(func)
    def _(*args, **kwargs):
        mimetype = 'application/javascript'
        callback = request.args.get('callback', None)
        if callback is None:
            content = func(*args, **kwargs)

        else:
            content = "%s(%s)" % (callback, func(*args, **kwargs))
        return current_app.response_class(content, mimetype=mimetype)
    return _
825433
def _http_call(self, url, method, data=None, **kwargs):
        
        response = self._http_response(url, method, data=data, **kwargs)
        if not response.content:
            return {}

        return response.json()
153388
def _get_responses(cls, requests, dispatcher):
        
        for request in requests:
            def response(**kwargs):
                return cls.RESPONSE_CLASS_MAP[request.JSONRPC_VERSION](
                    _id=request._id, **kwargs)

            try:
                method = dispatcher[request.method]
            except KeyError:
                output = response(error=JSONRPCMethodNotFound()._data)
            else:
                try:
                    result = method(*request.args, **request.kwargs)
                except JSONRPCDispatchException as e:
                    output = response(error=e.error._data)
                except Exception as e:
                    data = {
                        "type": e.__class__.__name__,
                        "args": e.args,
                        "message": str(e),
                    }
                    if isinstance(e, TypeError) and is_invalid_params(
                            method, *request.args, **request.kwargs):
                        output = response(
                            error=JSONRPCInvalidParams(data=data)._data)
                    else:
                        # logger.exception("API Exception: {0}".format(data))
                        print("API Exception: {0}".format(data))
                        output = response(
                            error=JSONRPCServerError(data=data)._data)
                else:
                    output = response(result=result)
            finally:
                if not request.is_notification:
                    yield output
149510
function(url, data, jsonpParam, callbacnName) {
		if (jsonpParam) {
			url = url.replace(jsonpParam + '=?', jsonpParam + '=' + callbacnName);
		} else {
			data['callback'] = callbacnName;
		}
		var buffer = [];
		for (var key in data) {
			buffer.push(key + '=' + encodeURIComponent(data[key]));
		}
		return url + (url.indexOf('?') > -1 ? '&' : '?') + buffer.join('&');
	}
701
def make_json_response(rv):
    
    # Tuple of (response, status, headers)
    rv, status, headers = normalize_response_value(rv)

    # JsonResponse
    if isinstance(rv, JsonResponse):
        return rv

    # Data
    return JsonResponse(rv, status, headers)
1158026
function processJsonpMock( requestSettings, mockHandler, origSettings ) {
		// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
		// because there isn't an easy hook for the cross domain script tag of jsonp

		processJsonpUrl( requestSettings );

		requestSettings.dataType = "json";
		if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {
			createJsonpCallback(requestSettings, mockHandler, origSettings);

			// We need to make sure
			// that a JSONP style response is executed properly

			var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
				parts = rurl.exec( requestSettings.url ),
				remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);

			requestSettings.dataType = "script";
			if(requestSettings.type.toUpperCase() === "GET" && remote ) {
				var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );

				// Check if we are supposed to return a Deferred back to the mock call, or just
				// signal success
				if(newMockReturn) {
					return newMockReturn;
				} else {
					return true;
				}
			}
		}
		return null;
	}
1053207
private JSONObject getDataFromRestCallPost(GitHubParsed gitHubParsed, GitHubRepo repo, String password, String personalAccessToken, JSONObject query) throws MalformedURLException, HygieiaException {
        ResponseEntity<String> response = makeRestCallPost(gitHubParsed.getGraphQLUrl(), repo.getUserId(), password, personalAccessToken, query);
        JSONObject data = (JSONObject) parseAsObject(response).get("data");
        JSONArray errors = getArray(parseAsObject(response), "errors");

        if (CollectionUtils.isEmpty(errors)) {
            return data;
        }

        JSONObject error = (JSONObject) errors.get(0);

        if (!error.containsKey("type") || !error.get("type").equals("NOT_FOUND")) {
            throw new HygieiaException("Error in GraphQL query:" + errors.toJSONString(), HygieiaException.JSON_FORMAT_ERROR);
        }

        RedirectedStatus redirectedStatus = checkForRedirectedRepo(repo);

        if (!redirectedStatus.isRedirected()) {
            throw new HygieiaException("Error in GraphQL query:" + errors.toJSONString(), HygieiaException.JSON_FORMAT_ERROR);
        }

        String redirectedUrl = redirectedStatus.getRedirectedUrl();
        LOG.debug("Repo was redirected from: " + repo.getRepoUrl() + " to " + redirectedUrl);
        repo.setRepoUrl(redirectedUrl);
        gitHubParsed.updateForRedirect(redirectedUrl);

        JSONParser parser = new JSONParser();
        try {
            JSONObject variableJSON = (JSONObject) parser.parse(str(query, "variables"));
            variableJSON.put("name", gitHubParsed.getRepoName());
            variableJSON.put("owner", gitHubParsed.getOrgName());
            query.put("variables", variableJSON.toString());
        } catch (ParseException e) {
            LOG.error("Could not parse JSON String", e);
        }
        return getDataFromRestCallPost(gitHubParsed, repo, password, personalAccessToken, query);
    }
989931
def json_data(self, name, default=None):
        
        value = self.get(name)
        if value is Missing.Value:
            return default
        return value
502851
def json_rpc_format(self):
        

        error = {
            'name': smart_text(self.__class__.__name__),
            'code': self.code,
            'message': "%s: %s" %
            (smart_text(self.__class__.__name__), smart_text(self.message)),
            'data': self.data
        }

        from django.conf import settings

        if settings.DEBUG:
            import sys, traceback
            error['stack'] = traceback.format_exc()
            error['executable'] = sys.executable

        return error
76206
def req(self, method, params=()):
        """"""

        response = self.session.post(
            self.url,
            data=json.dumps({"method": method, "params": params, "jsonrpc": "1.1"}),
        ).json()

        if response["error"] is not None:
            return response["error"]
        else:
            return response["result"]
1319183
def _call_method(self, request):
        """"""
        method = self.method_data[request['method']]['method']
        params = request['params']
        result = None
        try:
            if isinstance(params, list):
                # Does it have enough arguments?
                if len(params) < self._man_args(method):
                    raise InvalidParamsError('not enough arguments')
                # Does it have too many arguments?
                if not self._vargs(method) \
                        and len(params) > self._max_args(method):
                    raise InvalidParamsError('too many arguments')

                result = yield defer.maybeDeferred(method, *params)
            elif isinstance(params, dict):
                # Do not accept keyword arguments if the jsonrpc version is
                # not >=1.1.
                if request['jsonrpc'] < 11:
                    raise KeywordError

                result = yield defer.maybeDeferred(method, **params)
            else:  # No params
                result = yield defer.maybeDeferred(method)
        except JSONRPCError:
            raise
        except Exception:
            # Exception was raised inside the method.
            log.msg('Exception raised while invoking RPC method "{}".'.format(
                    request['method']))
            log.err()
            raise ServerError

        defer.returnValue(result)
1120775
def send_single_request(method, args)
      post_data = {
          'jsonrpc' => JSON_RPC_VERSION,
          'method'  => method,
          'params'  => args,
          'id'      => self.class.make_id
      }.to_json
      resp = RestClient.post(@url, post_data, content_type: 'application/json', user_agent: "syncano-ruby-#{Syncano::VERSION}")
      if resp.nil? || resp.body.nil? || resp.body.empty?
        raise Jimson::ClientError::InvalidResponse.new
      end

      return resp.body

    rescue Exception, StandardError
      raise Jimson::ClientError::InternalError.new($!)
    end
40228
def jsonp(data, **json_kwargs):
    
    from uliweb import request
    
    if 'jsonp' in json_kwargs:
        cb = json_kwargs.pop('jsonp')
    else:
        cb = 'callback'
        
    begin = str(request.GET.get(cb))
    if not begin:
        raise BadRequest("Can't found %s parameter in request's query_string" % cb)
    if not r_callback.match(begin):
        raise BadRequest("The callback name is not right, it can be alphabetic, number and underscore only")
    
    if callable(data):
        @wraps(data)
        def f(*arg, **kwargs):
            ret = data(*arg, **kwargs)
            return Response(begin + '(' + json_dumps(ret) + ');', **json_kwargs)
        return f
    else:
        return Response(begin + '(' + json_dumps(data) + ');', **json_kwargs)
591136
def get_json_from_remote_server(func, **kwargs):
    
    rawjson = func(**kwargs)
    if rawjson is None:
        # If the request failed we already logged in in PiwikRequest;
        # no need to get into the exception handler below.
        return {}
    try:
        data = json.loads(rawjson)
        if isinstance(data, dict) and data.get('result') == 'error':
            current_plugin.logger.error('The Piwik server responded with an error: %s', data['message'])
            return {}
        return data
    except Exception:
        current_plugin.logger.exception('Unable to load JSON from source %s', rawjson)
        return {}
1100648
def rpc(self, request, args):
        
        if request.method != 'POST':
            return self.error(405, request)
        payload = request.get_data(as_text=True) or '{}'
        request_method = request.args.get('method')
        if not request_method:
            return self.error(
                400, request,
                message="A query string parameter method= is missing."
            )
        name_map = self.service.__nirum_method_names__
        try:
            method_facial_name = name_map.behind_names[request_method]
        except KeyError:
            return self.error(
                400,
                request,
                message="Service doesn't have procedure named '{}'.".format(
                    request_method
                )
            )
        try:
            service_method = getattr(self.service, method_facial_name)
        except AttributeError:
            return self.error(
                400,
                request,
                message="Service has no procedure '{}'.".format(
                    request_method
                )
            )
        if not callable(service_method):
            return self.error(
                400, request,
                message="Remote procedure '{}' is not callable.".format(
                    request_method
                )
            )
        try:
            request_json = json.loads(payload)
        except ValueError:
            return self.error(
                400,
                request,
                message="Invalid JSON payload: '{}'.".format(payload)
            )
        type_hints = self.service.__nirum_service_methods__[method_facial_name]
        try:
            arguments = self._parse_procedure_arguments(
                type_hints,
                request_json
            )
        except (NirumProcedureArgumentValueError,
                NirumProcedureArgumentRequiredError) as e:
            return self.error(400, request, message=str(e))
        method_error_types = self.service.__nirum_method_error_types__
        if not callable(method_error_types):  # generated by older compiler
            method_error_types = method_error_types.get
        method_error = method_error_types(method_facial_name, ())
        try:
            result = service_method(**arguments)
        except method_error as e:
            return self._raw_response(400, serialize_meta(e))
        return_type = type_hints['_return']
        if type_hints.get('_v', 1) >= 2:
            return_type = return_type()
        if not self._check_return_type(return_type, result):
            return self.error(
                400,
                request,
                message="Incorrect return type '{0}' "
                        "for '{1}'. expected '{2}'.".format(
                            typing._type_repr(result.__class__),
                            request_method,
                            typing._type_repr(return_type)
                        )
            )
        else:
            return self._raw_response(200, serialize_meta(result))