Search in sources :

Example 1 with Response

use of org.web3j.protocol.core.Response in project quorum-acceptance-tests by ConsenSys.

the class PluginSecurity method invokeMultipleWithExpectation.

@Step("`<clientId>` sends a batch `<apis>` to `<node>` and expect: <table>")
public void invokeMultipleWithExpectation(String clientId, String apis, QuorumNetworkProperty.Node node, Table table) {
    String token = mustHaveValue(DataStoreFactory.getScenarioDataStore(), clientId, String.class);
    Context.storeAccessToken(token);
    BatchRequest.Collector collector = BatchRequest.Collector.create();
    Arrays.stream(apis.split(",")).map(String::trim).forEach(n -> collector.add(n, Collections.emptyList()));
    Map<String, String> expect = table.getTableRows().stream().collect(Collectors.toMap(r -> StringUtils.removeEnd(StringUtils.removeStart(r.getCell("callApi"), "`"), "`"), r -> r.getCell("expectation")));
    rpcService.call(node, collector).blockingForEach(batchResponse -> {
        assertThat(batchResponse.getResponses()).as("Number of returned responses").hasSize(collector.size());
        for (ObjectResponse res : batchResponse.getResponses()) {
            assertThat(res.getId()).as("Response must have id").isNotZero();
            Request r = collector.getByID(res.getId());
            String policy = Optional.ofNullable(expect.get(r.getMethod())).orElseThrow(() -> new IllegalStateException("no such method in expectation table: " + r.getMethod()));
            boolean expectAuthorized = "success".equalsIgnoreCase(policy);
            String description = policy + ": " + r.getMethod() + "@" + node.getName();
            if (expectAuthorized) {
                assertThat(Optional.ofNullable(res.getError()).orElse(new Response.Error()).getMessage()).as(description).isNullOrEmpty();
            }
            assertThat(res.hasError()).as(description).isNotEqualTo(expectAuthorized);
            if (res.hasError()) {
                assertThat(res.getError().getMessage()).as(description).endsWith(policy);
            }
        }
    });
}
Also used : AbstractSpecImplementation(com.quorum.gauge.core.AbstractSpecImplementation) StringUtils(org.apache.commons.lang.StringUtils) java.util(java.util) Step(com.thoughtworks.gauge.Step) Logger(org.slf4j.Logger) ObjectResponse(com.quorum.gauge.ext.ObjectResponse) QuorumNode(com.quorum.gauge.common.QuorumNode) BatchRequest(com.quorum.gauge.ext.BatchRequest) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) QuorumNetworkProperty(com.quorum.gauge.common.QuorumNetworkProperty) LoggerFactory(org.slf4j.LoggerFactory) Response(org.web3j.protocol.core.Response) Collectors(java.util.stream.Collectors) Request(org.web3j.protocol.core.Request) Stream(java.util.stream.Stream) Context(com.quorum.gauge.common.Context) Service(org.springframework.stereotype.Service) Table(com.thoughtworks.gauge.Table) DataStoreFactory(com.thoughtworks.gauge.datastore.DataStoreFactory) ObjectResponse(com.quorum.gauge.ext.ObjectResponse) Response(org.web3j.protocol.core.Response) BatchRequest(com.quorum.gauge.ext.BatchRequest) BatchRequest(com.quorum.gauge.ext.BatchRequest) Request(org.web3j.protocol.core.Request) ObjectResponse(com.quorum.gauge.ext.ObjectResponse) Step(com.thoughtworks.gauge.Step)

Example 2 with Response

use of org.web3j.protocol.core.Response in project quorum-acceptance-tests by ConsenSys.

the class ContractService method readSimpleContractValue.

/**
 * Need to use EthCall to manipulate the error as webj3 doesn't
 *
 * @param node
 * @param contractAddress
 * @return
 */
public Observable<BigInteger> readSimpleContractValue(Node node, String contractAddress) {
    Quorum client = connectionFactory().getConnection(node);
    Function function = new Function(FUNC_GET, Arrays.<Type>asList(), Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {
    }));
    return client.ethCoinbase().flowable().toObservable().map(Response::getResult).flatMap(address -> {
        Request<?, EthCall> req = client.ethCall(Transaction.createEthCallTransaction(address, contractAddress, FunctionEncoder.encode(function)), DefaultBlockParameterName.LATEST);
        return req.flowable().toObservable();
    }).map(ec -> {
        if (ec.hasError()) {
            throw new ContractCallException(ec.getError().getMessage());
        }
        List<Type> values = FunctionReturnDecoder.decode(ec.getValue(), function.getOutputParameters());
        Type result;
        if (!values.isEmpty()) {
            result = values.get(0);
        } else {
            throw new ContractCallException("Empty value (0x) returned from contract");
        }
        Object value = result.getValue();
        if (BigInteger.class.isAssignableFrom(value.getClass())) {
            return (BigInteger) value;
        } else {
            throw new ContractCallException("Unable to convert response: " + value + " to expected type: " + BigInteger.class.getSimpleName());
        }
    });
}
Also used : Response(org.web3j.protocol.core.Response) Transaction(org.web3j.protocol.core.methods.request.Transaction) Arrays(java.util.Arrays) EthChainId(com.quorum.gauge.ext.EthChainId) PrivacyFlag(com.quorum.gauge.common.PrivacyFlag) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) FunctionEncoder(org.web3j.abi.FunctionEncoder) Response(org.web3j.protocol.core.Response) Request(org.web3j.protocol.core.Request) FUNC_GET(com.quorum.gauge.sol.SimpleStorage.FUNC_GET) ReadonlyTransactionManager(org.web3j.tx.ReadonlyTransactionManager) Uint256(org.web3j.abi.datatypes.generated.Uint256) Charset(java.nio.charset.Charset) Service(org.springframework.stereotype.Service) Observable(io.reactivex.Observable) BigInteger(java.math.BigInteger) ClientTransactionManager(org.web3j.quorum.tx.ClientTransactionManager) FunctionReturnDecoder(org.web3j.abi.FunctionReturnDecoder) com.quorum.gauge.sol(com.quorum.gauge.sol) Type(org.web3j.abi.datatypes.Type) Node(com.quorum.gauge.common.QuorumNetworkProperty.Node) StreamUtils(org.springframework.util.StreamUtils) Quorum(org.web3j.quorum.Quorum) EthSendTransactionAsync(com.quorum.gauge.ext.EthSendTransactionAsync) Contract(org.web3j.tx.Contract) Logger(org.slf4j.Logger) EthStorageRoot(com.quorum.gauge.ext.EthStorageRoot) TypeReference(org.web3j.abi.TypeReference) Collections.emptyList(java.util.Collections.emptyList) QuorumNode(com.quorum.gauge.common.QuorumNode) QuorumNetworkProperty(com.quorum.gauge.common.QuorumNetworkProperty) PrivateTransactionAsync(com.quorum.gauge.ext.PrivateTransactionAsync) DefaultBlockParameterName(org.web3j.protocol.core.DefaultBlockParameterName) ContractCallException(org.web3j.tx.exceptions.ContractCallException) DefaultBlockParameter(org.web3j.protocol.core.DefaultBlockParameter) IOException(java.io.IOException) PrivateClientTransactionManager(com.quorum.gauge.ext.PrivateClientTransactionManager) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Web3j(org.web3j.protocol.Web3j) CollectionUtils(org.springframework.util.CollectionUtils) EthFilter(org.web3j.protocol.core.methods.request.EthFilter) TransactionManager(org.web3j.tx.TransactionManager) Function(org.web3j.abi.datatypes.Function) org.web3j.protocol.core.methods.response(org.web3j.protocol.core.methods.response) Collections(java.util.Collections) InputStream(java.io.InputStream) Function(org.web3j.abi.datatypes.Function) Quorum(org.web3j.quorum.Quorum) Type(org.web3j.abi.datatypes.Type) ContractCallException(org.web3j.tx.exceptions.ContractCallException) Request(org.web3j.protocol.core.Request) BigInteger(java.math.BigInteger) TypeReference(org.web3j.abi.TypeReference)

Example 3 with Response

use of org.web3j.protocol.core.Response in project teku by ConsenSys.

the class Web3jEth1ProviderTest method shouldThrowRejectedRequestExceptionWhenInfuraRejectsRequestWithTooManyLogs.

@Test
void shouldThrowRejectedRequestExceptionWhenInfuraRejectsRequestWithTooManyLogs() {
    final EthFilter filter = new EthFilter();
    final EthLog response = new EthLog();
    response.setError(new Response.Error(-32005, "query returned more than 10000 results"));
    when(web3.ethGetLogs(filter)).thenReturn(request1);
    when(request1.sendAsync()).thenReturn(SafeFuture.completedFuture(response));
    final SafeFuture<List<LogResult<?>>> result = provider.ethGetLogs(filter);
    SafeFutureAssert.assertThatSafeFuture(result).isCompletedExceptionallyWith(RejectedRequestException.class);
}
Also used : Response(org.web3j.protocol.core.Response) EthFilter(org.web3j.protocol.core.methods.request.EthFilter) EthLog(org.web3j.protocol.core.methods.response.EthLog) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 4 with Response

use of org.web3j.protocol.core.Response in project web3j by web3j.

the class Service method sendBatch.

@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;
        }
    }
}
Also used : BatchResponse(org.web3j.protocol.core.BatchResponse) Response(org.web3j.protocol.core.Response) BatchResponse(org.web3j.protocol.core.BatchResponse) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 5 with Response

use of org.web3j.protocol.core.Response in project web3j by web3j.

the class RawResponseDeserializer method deserialize.

@Override
public Response deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    Response deserializedResponse = (Response) defaultDeserializer.deserialize(jp, ctxt);
    deserializedResponse.setRawResponse(getRawResponse(jp));
    return deserializedResponse;
}
Also used : Response(org.web3j.protocol.core.Response)

Aggregations

Response (org.web3j.protocol.core.Response)11 QuorumNetworkProperty (com.quorum.gauge.common.QuorumNetworkProperty)5 List (java.util.List)5 Service (org.springframework.stereotype.Service)5 Request (org.web3j.protocol.core.Request)5 QuorumNode (com.quorum.gauge.common.QuorumNode)4 Step (com.thoughtworks.gauge.Step)4 Observable (io.reactivex.Observable)4 Collectors (java.util.stream.Collectors)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 AbstractSpecImplementation (com.quorum.gauge.core.AbstractSpecImplementation)3 DataStoreFactory (com.thoughtworks.gauge.datastore.DataStoreFactory)3 BigInteger (java.math.BigInteger)3 ArrayList (java.util.ArrayList)3 Arrays (java.util.Arrays)3 Autowired (org.springframework.beans.factory.annotation.Autowired)3 GethArgBuilder (com.quorum.gauge.common.GethArgBuilder)2 NodeType (com.quorum.gauge.common.NodeType)2 PrivacyFlag (com.quorum.gauge.common.PrivacyFlag)2