org.web3j.protocol.core.Response Java Examples

The following examples show how to use org.web3j.protocol.core.Response. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSocketService.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<BatchResponse> sendBatchAsync(BatchRequest requests) {
    CompletableFuture<BatchResponse> result = new CompletableFuture<>();

    // replace first batch elements's id to handle response
    long requestId = nextBatchId.getAndIncrement();
    Request<?, ? extends Response<?>> firstRequest = requests.getRequests().get(0);
    long originId = firstRequest.getId();
    requests.getRequests().get(0).setId(requestId);

    requestForId.put(
            requestId, new WebSocketRequests(result, requests.getRequests(), originId));

    try {
        sendBatchRequest(requests, requestId);
    } catch (IOException e) {
        closeRequest(requestId, e);
    }

    return result;
}
 
Example #2
Source File: ObjectMapperFactory.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private static ObjectMapper configureObjectMapper(
        ObjectMapper objectMapper, boolean shouldIncludeRawResponses) {
    if (shouldIncludeRawResponses) {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
                                                          BeanDescription beanDesc,
                                                          JsonDeserializer<?> deserializer) {
                if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) {
                    return new RawResponseDeserializer(deserializer);
                }

                return deserializer;
            }
        });

        objectMapper.registerModule(module);
    }

    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example #3
Source File: WebSocketService.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Response> CompletableFuture<T> sendAsync(
        Request request,
        Class<T> responseType) {

    CompletableFuture<T> result = new CompletableFuture<>();
    long requestId = request.getId();
    requestForId.put(requestId, new WebSocketRequest<>(result, responseType));
    try {
        sendRequest(request, requestId);
    } catch (IOException e) {
        closeRequest(requestId, e);
    }

    return result;
}
 
Example #4
Source File: ResponseTest.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testErrorResponse() {
    buildResponse(
            "{"
                    + "  \"jsonrpc\":\"2.0\","
                    + "  \"id\":1,"
                    + "  \"error\":{"
                    + "    \"code\":-32602,"
                    + "    \"message\":\"Invalid address length, expected 40 got 64 bytes\","
                    + "    \"data\":null"
                    + "  }"
                    + "}"
    );

    EthBlock ethBlock = deserialiseResponse(EthBlock.class);
    assertTrue(ethBlock.hasError());
    assertThat(ethBlock.getError(), equalTo(
            new Response.Error(-32602, "Invalid address length, expected 40 got 64 bytes")));
}
 
Example #5
Source File: ResponseTester.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {

    if (jsonResponse == null) {
        throw new UnsupportedOperationException("Response has not been configured");
    }

    okhttp3.Response response = new okhttp3.Response.Builder()
            .body(ResponseBody.create(JSON_MEDIA_TYPE, jsonResponse))
            .request(chain.request())
            .protocol(Protocol.HTTP_2)
            .code(200)
            .message("")
            .build();

    return response;
}
 
Example #6
Source File: Service.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Override
public BatchResponse sendBatch(BatchRequest batchRequest) throws IOException {
    if (batchRequest.getRequests().isEmpty()) {
        return new BatchResponse(Collections.emptyList(), Collections.emptyList());
    }

    String payload = objectMapper.writeValueAsString(batchRequest.getRequests());

    try (InputStream result = performIO(payload)) {
        if (result != null) {
            ArrayNode nodes = (ArrayNode) objectMapper.readTree(result);
            List<Response<?>> responses = new ArrayList<>(nodes.size());

            for (int i = 0; i < nodes.size(); i++) {
                Request<?, ? extends Response<?>> request = batchRequest.getRequests().get(i);
                Response<?> response =
                        objectMapper.treeToValue(nodes.get(i), request.getResponseType());
                responses.add(response);
            }

            return new BatchResponse(batchRequest.getRequests(), responses);
        } else {
            return null;
        }
    }
}
 
Example #7
Source File: ContractTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
@SuppressWarnings("unchecked")
public void testInvalidTransactionReceipt() throws Throwable {
    prepareNonceRequest();
    prepareTransactionRequest();

    PlatonGetTransactionReceipt ethGetTransactionReceipt = new PlatonGetTransactionReceipt();
    ethGetTransactionReceipt.setError(new Response.Error(1, "Invalid transaction receipt"));

    Request<?, PlatonGetTransactionReceipt> getTransactionReceiptRequest = mock(Request.class);
    when(getTransactionReceiptRequest.sendAsync())
            .thenReturn(Async.run(() -> ethGetTransactionReceipt));
    when(web3j.platonGetTransactionReceipt(TRANSACTION_HASH))
            .thenReturn((Request) getTransactionReceiptRequest);

    testErrorScenario();
}
 
Example #8
Source File: ContractTest.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
@SuppressWarnings("unchecked")
public void testInvalidTransactionReceipt() throws Throwable {
    prepareNonceRequest();
    prepareTransactionRequest();

    EthGetTransactionReceipt ethGetTransactionReceipt = new EthGetTransactionReceipt();
    ethGetTransactionReceipt.setError(new Response.Error(1, "Invalid transaction receipt"));

    Request<?, EthGetTransactionReceipt> getTransactionReceiptRequest = mock(Request.class);
    when(getTransactionReceiptRequest.sendAsync())
            .thenReturn(Async.run(() -> ethGetTransactionReceipt));
    when(web3j.ethGetTransactionReceipt(TRANSACTION_HASH))
            .thenReturn((Request) getTransactionReceiptRequest);

    testErrorScenario();
}
 
Example #9
Source File: WebSocketService.java    From web3j with Apache License 2.0 6 votes vote down vote up
private void processBatchRequestReply(String replyStr, ArrayNode replyJson) throws IOException {
    long replyId = getReplyId(replyJson.get(0));
    WebSocketRequests webSocketRequests = (WebSocketRequests) getAndRemoveRequest(replyId);
    try {
        // rollback request id of first batch elt
        ((ObjectNode) replyJson.get(0)).put("id", webSocketRequests.getOriginId());

        List<Request<?, ? extends Response<?>>> requests = webSocketRequests.getRequests();
        List<Response<?>> responses = new ArrayList<>(replyJson.size());

        for (int i = 0; i < replyJson.size(); i++) {
            Response<?> response =
                    objectMapper.treeToValue(
                            replyJson.get(i), requests.get(i).getResponseType());
            responses.add(response);
        }

        sendReplyToListener(webSocketRequests, new BatchResponse(requests, responses));
    } catch (IllegalArgumentException e) {
        sendExceptionToListener(replyStr, webSocketRequests, e);
    }
}
 
Example #10
Source File: ResponseTester.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {

    if (jsonResponse == null) {
        throw new UnsupportedOperationException("Response has not been configured");
    }

    okhttp3.Response response = new okhttp3.Response.Builder()
            .body(ResponseBody.create(JSON_MEDIA_TYPE, jsonResponse))
            .request(chain.request())
            .protocol(Protocol.HTTP_2)
            .code(200)
            .message("")
            .build();

    return response;
}
 
Example #11
Source File: ObjectMapperFactory.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static ObjectMapper configureObjectMapper(
        ObjectMapper objectMapper, boolean shouldIncludeRawResponses) {
    if (shouldIncludeRawResponses) {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
                                                          BeanDescription beanDesc,
                                                          JsonDeserializer<?> deserializer) {
                if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) {
                    return new RawResponseDeserializer(deserializer);
                }

                return deserializer;
            }
        });

        objectMapper.registerModule(module);
    }

    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example #12
Source File: ResponseTester.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {

    if (jsonResponse == null) {
        throw new UnsupportedOperationException("Response has not been configured");
    }

    okhttp3.Response response =
            new okhttp3.Response.Builder()
                    .body(ResponseBody.create(JSON_MEDIA_TYPE, jsonResponse))
                    .request(chain.request())
                    .protocol(Protocol.HTTP_2)
                    .code(200)
                    .message("")
                    .build();

    return response;
}
 
Example #13
Source File: Service.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T extends Response> T send(
        Request request, Class<T> responseType) throws IOException {
    String payload = objectMapper.writeValueAsString(request);

    try (InputStream result = performIO(payload)) {
        if (result != null) {
            return objectMapper.readValue(result, responseType);
        } else {
            return null;
        }
    }
}
 
Example #14
Source File: ContractTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
@SuppressWarnings("unchecked")
public void testInvalidTransactionResponse() throws Throwable {
    prepareNonceRequest();

    EthSendTransaction ethSendTransaction = new EthSendTransaction();
    ethSendTransaction.setError(new Response.Error(1, "Invalid transaction"));

    Request<?, EthSendTransaction> rawTransactionRequest = mock(Request.class);
    when(rawTransactionRequest.sendAsync()).thenReturn(Async.run(() -> ethSendTransaction));
    when(web3j.ethSendRawTransaction(any(String.class)))
            .thenReturn((Request) rawTransactionRequest);

    testErrorScenario();
}
 
Example #15
Source File: ResponseTester.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
protected <T extends Response> T deserialiseResponse(Class<T> type) {
    T response = null;
    try {
        response = web3jService.send(new Request(), type);
    } catch (IOException e) {
        fail(e.getMessage());
    }
    return response;
}
 
Example #16
Source File: PollingTransactionReceiptProcessorTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private static <T extends Response<?>> Request<String, T> requestReturning(T response) {
    Request<String, T> request = mock(Request.class);
    try {
        when(request.send()).thenReturn(response);
    } catch (IOException e) {
        // this will never happen
    }
    return request;
}
 
Example #17
Source File: EeaSendRawTransaction.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public String request(final String value) {
  final Request<?, ? extends Response<?>> sendRawTransactionRequest =
      eeaJsonRpc.eeaSendRawTransaction(value);
  sendRawTransactionRequest.setId(77);

  return Json.encode(sendRawTransactionRequest);
}
 
Example #18
Source File: Web3jEth1Provider.java    From teku with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private <S, T extends Response> SafeFuture<T> sendAsync(final Request<S, T> request) {
  try {
    return SafeFuture.of(request.sendAsync());
  } catch (RejectedExecutionException ex) {
    LOG.debug("shutting down, ignoring error", ex);
    return new SafeFuture<>();
  }
}
 
Example #19
Source File: Web3jProxyContract.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
private String mapErrorToMessage(Response.Error error) {
  return "Code: "
      + error.getCode()
      + "\nmessage: "
      + error.getMessage()
      + "\nData: "
      + error.getData();
}
 
Example #20
Source File: RawResponseDeserializer.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Override
public Response deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    Response deserializedResponse = (Response) defaultDeserializer.deserialize(jp, ctxt);

    deserializedResponse.setRawResponse(getRawResponse(jp));
    return deserializedResponse;
}
 
Example #21
Source File: Service.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Response> T send(Request request, Class<T> responseType) throws IOException {
    String payload = objectMapper.writeValueAsString(request);

    try (InputStream result = performIO(payload)) {
        if (result != null) {
            return objectMapper.readValue(result, responseType);
        } else {
            return null;
        }
    }
}
 
Example #22
Source File: WebSocketRequests.java    From web3j with Apache License 2.0 5 votes vote down vote up
public WebSocketRequests(
        CompletableFuture<BatchResponse> onReply,
        List<Request<?, ? extends Response<?>>> requests,
        Long originId) {

    super(onReply, BatchResponse.class);
    this.requests = requests;
    this.originId = originId;
}
 
Example #23
Source File: WebSocketService.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Response> CompletableFuture<T> sendAsync(
        Request request, Class<T> responseType) {

    CompletableFuture<T> result = new CompletableFuture<>();
    long requestId = request.getId();
    requestForId.put(requestId, new WebSocketRequest<>(result, responseType));
    try {
        sendRequest(request, requestId);
    } catch (IOException e) {
        closeRequest(requestId, e);
    }

    return result;
}
 
Example #24
Source File: WebSocketService.java    From web3j with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> void reportSubscriptionError(
        BehaviorSubject<T> subject, EthSubscribe subscriptionReply) {
    Response.Error error = subscriptionReply.getError();
    log.error("Subscription request returned error: {}", error.getMessage());
    subject.onError(
            new IOException(
                    String.format(
                            "Subscription request failed with error: %s", error.getMessage())));
}
 
Example #25
Source File: ObjectMapperFactory.java    From web3j with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper configureObjectMapper(
        ObjectMapper objectMapper, boolean shouldIncludeRawResponses) {
    if (shouldIncludeRawResponses) {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(
                new BeanDeserializerModifier() {
                    @Override
                    public JsonDeserializer<?> modifyDeserializer(
                            DeserializationConfig config,
                            BeanDescription beanDesc,
                            JsonDeserializer<?> deserializer) {
                        if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) {
                            return new RawResponseDeserializer(deserializer);
                        }

                        return deserializer;
                    }
                });

        objectMapper.registerModule(module);
    }

    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example #26
Source File: PollingTransactionReceiptProcessorTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
private static <T extends Response<?>> Request requestReturning(T response) {
    Request request = mock(Request.class);
    try {
        when(request.send()).thenReturn(response);
    } catch (IOException e) {
        // this will never happen
    }
    return request;
}
 
Example #27
Source File: WebSocketServiceTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceiveError() throws Exception {
    CompletableFuture<Web3ClientVersion> reply =
            service.sendAsync(request, Web3ClientVersion.class);
    sendErrorReply();

    assertTrue(reply.isDone());
    Web3ClientVersion version = reply.get();
    assertTrue(version.hasError());
    assertEquals(new Response.Error(-1, "Error message"), version.getError());
}
 
Example #28
Source File: ResponseTester.java    From web3j with Apache License 2.0 5 votes vote down vote up
protected <T extends Response> T deserialiseResponse(Class<T> type) {
    T response = null;
    try {
        response = web3jService.send(new Request(), type);
    } catch (IOException e) {
        fail(e.getMessage());
    }
    return response;
}
 
Example #29
Source File: Service.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Response> T send(
        Request request, Class<T> responseType) throws IOException {
    String payload = objectMapper.writeValueAsString(request);
    try (InputStream result = performIO(payload)) {
        if (result != null) {
            return objectMapper.readValue(result, responseType);
        } else {
            return null;
        }
    }
}
 
Example #30
Source File: EeaSendRawTransaction.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public String request() {
  final Request<?, ? extends Response<?>> sendRawTransactionRequest =
      eeaJsonRpc.eeaSendRawTransaction(
          "0xf90110a0e04d296d2460cfb8472af2c5fd05b5a214109c25688d3704aed5484f9a7792f28609184e72a0008276c094d46e8dd67c5d32be8058bb8eb970870f0724456780a9d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f07244567536a00b528cefb87342b2097318cd493d13b4c9bd55bf35bf1b3cf2ef96ee14cee563a06423107befab5530c42a2d7d2590b96c04ee361c868c138b054d7886966121a6aa307837353737393139616535646634393431313830656163323131393635663237356364636533313464ebaa3078643436653864643637633564333262653830353862623865623937303837306630373234343536378a72657374726963746564");
  sendRawTransactionRequest.setId(77);
  return Json.encode(sendRawTransactionRequest);
}