public static JsonRpcResponse fromString(String rawResponse) { JsonParser parser = new JsonParser(); JsonObject response = parser.parse(rawResponse).getAsJsonObject(); JsonElement id = response.get("id"); JsonElement errorElement = response.get("error"); int responseStatus = HttpServletResponse.SC_OK; String error; if (! (errorElement instanceof JsonNull)) { if (errorElement instanceof JsonObject) { error = errorElement.toString(); // try parsing it into RpcCallException to get the HttpStatus from there RpcCallException rpcEx = RpcCallException.fromJson(error); if (rpcEx != null) { responseStatus = rpcEx.getCategory().getHttpStatus(); JsonElement resultElement = response.get("result"); return new JsonRpcResponse(id, resultElement == null ? JsonNull.INSTANCE : resultElement, errorElement, responseStatus); } } error = errorElement.getAsString(); if (StringUtils.isNotBlank(error)) { responseStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } JsonElement resultElement = response.get("result"); return new JsonRpcResponse(id, resultElement == null ? JsonNull.INSTANCE : resultElement, errorElement, responseStatus); }
@Test public void verifyToString() { JsonRpcResponse response = new JsonRpcResponse(new JsonPrimitive(42), JsonNull.INSTANCE, new JsonPrimitive("none"), 200); assertThat(response.getId()).isEqualTo(new JsonPrimitive(42)); assertThat(response.toString()).contains("[id=42,result=null,error=\"none\"]"); }
@SuppressWarnings("unchecked") private JsonRpcResponse dispatchJsonRpcRequest(JsonRpcRequest rpcRequest, OrangeContext cxt) { JsonRpcResponse jsonResponse = new JsonRpcResponse(rpcRequest.getId(), JsonNull.INSTANCE, JsonNull.INSTANCE, HttpServletResponse.SC_OK); try { ServiceMethodHandler handler = handlers.getMethodHandler(rpcRequest.getMethod()); Message innerRequest = convertJsonToProtobuf(handler, rpcRequest); JsonElement idElement = rpcRequest.getId(); if (idElement == null) { jsonResponse.setId(new JsonPrimitive(-1)); } Message innerResponse = invokeHandlerChain(rpcRequest.getMethod(), handler, innerRequest, cxt); jsonResponse.setResult(ProtobufUtil.protobufToJson(innerResponse)); } catch (RpcCallException rpcEx) { logger.debug("Error processing request", rpcEx); jsonResponse.setError(rpcEx.toJson()); jsonResponse.setStatusCode(rpcEx.getCategory().getHttpStatus()); } catch (Exception ex) { logger.warn("Error processing request", ex); if (ex.getMessage() != null) { jsonResponse.setError(new JsonPrimitive(ex.getMessage())); } jsonResponse.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return jsonResponse; }