Creates a success response.

@param jsonRpc the version string
@param id      the id of the request
@param result  the result object
@return the response object
191846
private ObjectNode createResponseSuccess(String jsonRpc, Object id, JsonNode result) {
		ObjectNode response = mapper.createObjectNode();
		response.put(JSONRPC, jsonRpc);
		if (Integer.class.isInstance(id)) {
			response.put(ID, Integer.class.cast(id).intValue());
		} else if (Long.class.isInstance(id)) {
			response.put(ID, Long.class.cast(id).longValue());
		} else if (Float.class.isInstance(id)) {
			response.put(ID, Float.class.cast(id).floatValue());
		} else if (Double.class.isInstance(id)) {
			response.put(ID, Double.class.cast(id).doubleValue());
		} else if (BigDecimal.class.isInstance(id)) {
			response.put(ID, BigDecimal.class.cast(id));
		} else {
			response.put(ID, String.class.cast(id));
		}
		response.set(RESULT, result);
		return response;
	}
1204548
protected function createResponse(ActionEvent\AbstractOnMethodEvent $event) : JsonRpcResponse
    {
        if ($event instanceof ActionEvent\OnMethodSuccessEvent) {
            return $this->responseCreator->createResultResponse($event->getResult(), $event->getJsonRpcRequest());
        } else {
            /** @var $event ActionEvent\OnMethodFailureEvent */
            return $this->responseCreator->createErrorResponse(
                $event->getException(),
                $event->getJsonRpcRequest()
            );
        }
    }
133930
def rpc_request(method_name: str, *args, **kwargs) -> rpcq.messages.RPCRequest:
    
    if args:
        kwargs['*args'] = args

    return rpcq.messages.RPCRequest(
        jsonrpc='2.0',
        id=str(uuid.uuid4()),
        method=method_name,
        params=kwargs
    )
177675
def response_builder(self, response):
        '''
        '''
        try:
            r = response.json()
            result = r['query']['results']
            response = {
                'num_result': r['query']['count'] ,
                'result': result
            }
        except (Exception,) as e:
            print(e)
            return response.content

        return response
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")
1204589
@FFDCIgnore({ Exception.class })
    public ProviderAuthenticationResult createResultWithJose4J(String responseState,
            Map<String, String> tokens,
            ConvergedClientConfig clientConfig,
            OidcClientRequest oidcClientRequest) {
        //oidcClientRequest.setTokenType(OidcClientRequest.TYPE_); // decided by the caller
        // This is for ID Token only at the writing time
        ProviderAuthenticationResult oidcResult = null;
        String tokenStr = getIdToken(tokens, clientConfig);
        String accessToken = tokens.get(Constants.ACCESS_TOKEN);
        String refreshToken = tokens.get(Constants.REFRESH_TOKEN);
        String clientId = clientConfig.getClientId();
        try {
            if (tokenStr == null) {
                // This is for ID Token only
                Tr.error(tc, "OIDC_CLIENT_IDTOKEN_REQUEST_FAILURE", new Object[] { clientId, clientConfig.getTokenEndpointUrl() });
                return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            }

            JwtContext jwtContext = parseJwtWithoutValidation(tokenStr);
            JwtClaims jwtClaims = parseJwtWithValidation(clientConfig, tokenStr, jwtContext, oidcClientRequest);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "post jwtClaims: " + jwtClaims + " firstPass jwtClaims=" + jwtContext.getJwtClaims());
            }
            OidcTokenImplBase idToken = new OidcTokenImplBase(jwtClaims, accessToken, refreshToken, clientId, oidcClientRequest.getTokenTypeNoSpace());

            if (idToken.getSubject() == null) {
                return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            }
            AttributeToSubject attributeToSubject = new AttributeToSubject(clientConfig, idToken);
            if (attributeToSubject.checkUserNameForNull()) {
                return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            }

            boolean isImplicit = Constants.IMPLICIT.equals(clientConfig.getGrantType());
            // verify nonce when nonce is enabled
            // this id for ID Token only
            if (clientConfig.isNonceEnabled() || isImplicit) {
                String nonceInIDToken = idToken.getNonce();
                boolean bNonceVerified = OidcUtil.verifyNonce(oidcClientRequest, nonceInIDToken, clientConfig, responseState);
                if (!bNonceVerified) {
                    // Error handling
                    Tr.error(tc, "OIDC_CLIENT_REQUEST_NONCE_FAILED", new Object[] { clientId, nonceInIDToken });
                    return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
                }
            }

            // if social login flow, put tokens and anything else social might want
            // into PAR props here and return it. Social will build the subject.
            if (clientConfig.isSocial()) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "social login flow, storing id token in result");
                }
                Hashtable<String, Object> props = new Hashtable<String, Object>();
                props.put(Constants.ID_TOKEN, tokenStr);
                props.put(Constants.ACCESS_TOKEN, accessToken);
                if (idToken != null) {
                    props.put(Constants.ID_TOKEN_OBJECT, idToken);
                }
                oidcResult = new ProviderAuthenticationResult(AuthResult.SUCCESS, HttpServletResponse.SC_OK, null, null, props, null);
                return oidcResult;
            }

            Hashtable<String, Object> customProperties = new Hashtable<String, Object>();
            if (clientConfig.isIncludeCustomCacheKeyInSubject() || clientConfig.isDisableLtpaCookie()) {
                long storingTime = new Date().getTime();
                String customCacheKey = oidcClientRequest.getAndSetCustomCacheKeyValue(); //username + tokenStr.toString().hashCode();
                customProperties.put(ClientConstants.CREDENTIAL_STORING_TIME_MILLISECONDS, Long.valueOf(storingTime));
                customProperties.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY, customCacheKey);
                customProperties.put(AuthenticationConstants.INTERNAL_ASSERTION_KEY, Boolean.TRUE); // TODO checking?
            }
            Subject subject = null;
            if (clientConfig.isIncludeIdTokenInSubject()) {
                subject = new Subject();
                subject.getPrivateCredentials().add(idToken); // add the external IDToken
                customProperties.putAll(tokens); // add ALL tokens to props.
            } else {
                if (refreshToken != null) {
                    customProperties.put(Constants.REFRESH_TOKEN, refreshToken);
                }
                if (accessToken != null) {
                    customProperties.put(Constants.ACCESS_TOKEN, accessToken);
                }
            }
            if (idToken != null) {
                customProperties.put(Constants.ID_TOKEN_OBJECT, idToken); // pass back to authenticator
            }

            //addJWTTokenToSubject(customProperties, idToken, clientConfig);

            //doIdAssertion(customProperties, payload, clientConfig);
            oidcResult = attributeToSubject.doMapping(customProperties, subject);
            //oidcResult = new ProviderAuthenticationResult(AuthResult.SUCCESS, HttpServletResponse.SC_OK, username, subject, customProperties, null);

        } catch (Exception e) {
            Tr.error(tc, "OIDC_CLIENT_IDTOKEN_VERIFY_ERR", new Object[] { e.getLocalizedMessage(), clientId });
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }

        return oidcResult;
    }
763324
def _request_callback(self, request_id):
        """"""
        def callback(future):
            # Remove the future from the client requests map
            self._client_request_futures.pop(request_id, None)

            if future.cancelled():
                future.set_exception(JsonRpcRequestCancelled())

            message = {
                'jsonrpc': JSONRPC_VERSION,
                'id': request_id,
            }

            try:
                message['result'] = future.result()
            except JsonRpcException as e:
                log.exception("Failed to handle request %s", request_id)
                message['error'] = e.to_dict()
            except Exception:  # pylint: disable=broad-except
                log.exception("Failed to handle request %s", request_id)
                message['error'] = JsonRpcInternalError.of(sys.exc_info()).to_dict()

            self._consumer(message)

        return callback
1204711
public static<R> Result<R> create(R value, Result<?> result) {
    	return new Result<R>(value,result.status,result.details,result.variables);
    }
53369
public static void returnStatusResponse(HttpServletResponse response, int status, String message) {
		if (response == null) {
			return;
		}
		PrintWriter out = null;
		try {
			response.setStatus(status);
			response.setContentType(MediaType.APPLICATION_JSON);
			out = response.getWriter();
			ParaObjectUtils.getJsonWriter().writeValue(out, getStatusResponse(Response.Status.
					fromStatusCode(status), message).getEntity());
		} catch (Exception ex) {
			logger.error(null, ex);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
820638
public static Response success(SessionId sessionId, Object value) {
    Response response = new Response();
    response.setSessionId(sessionId != null ? sessionId.toString() : null);
    response.setValue(value);
    response.setStatus(ErrorCodes.SUCCESS);
    response.setState(ErrorCodes.SUCCESS_STRING);
    return response;
  }
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)
1319330
public void setResponse(JsonRpcResponse response) {
    if (response.isError()) {
      setException(response.error());
      return;
    }

    try {
      set((V) Messages.fromJson(method.outputBuilder(), response.result()));
    } catch (Exception e) {
      setException(e);
    }
  }
161470
void writeResult(final RpcResult<?, ?> result, final HttpServletResponse resp)
			throws IOException {
		if (result.isSuccess()) {
			resp.setStatus(HttpServletResponse.SC_OK);
			resp.setContentType(JSON_CONTENT_TYPE);
		} else {
			resp.setStatus(APPLICATION_EXC_STATUS);
			resp.setContentType(JSON_CONTENT_TYPE);
		}

		PrintWriter writer = resp.getWriter();
		result.toJson(writer, true);
		writer.flush();
	}
169199
<O extends Message> JsonResponseFuture<O> newProvisionalResponse(ClientMethod<O> method) {
    long requestId = RANDOM.nextLong();
    JsonResponseFuture<O> outputFuture = new JsonResponseFuture<>(requestId, method);
    inFlightRequests.put(requestId, outputFuture);
    return outputFuture;
  }
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

    }
366843
public static <T> T executeJsonResult(HttpUriRequest request,Class<T> clazz){
		return execute(request,JsonResponseHandler.createResponseHandler(clazz));
	}
1055493
public function completedResponse(JsonResponse $response)
    {
        $data = $response->getData();
        $response->setData([
            'jsonrpc' => '2.0',
            'result' => $data,
        ]);

        return $response;
    }