Search in sources :

Example 1 with WebSocketClient

use of org.web3j.protocol.websocket.WebSocketClient in project besu by hyperledger.

the class BesuNode method checkIfWebSocketEndpointIsAvailable.

private void checkIfWebSocketEndpointIsAvailable(final String url) {
    final WebSocketClient webSocketClient = new WebSocketClient(URI.create(url));
    // Web3j implementation always invoke the listener (even when one hasn't been set). We are using
    // this stub implementation to avoid a NullPointerException.
    webSocketClient.setListener(new WebSocketListener() {

        @Override
        public void onMessage(final String message) {
        // DO NOTHING
        }

        @Override
        public void onError(final Exception e) {
        // DO NOTHING
        }

        @Override
        public void onClose() {
        // DO NOTHING
        }
    });
    // Because we can't trust the connection timeout of the WebSocket client implementation, we are
    // using this approach to verify if the endpoint is enabled.
    webSocketClient.connect();
    try {
        Awaitility.await().atMost(5, TimeUnit.SECONDS).until(webSocketClient::isOpen);
    } catch (final ConditionTimeoutException e) {
        throw new WebsocketNotConnectedException();
    } finally {
        webSocketClient.close();
    }
}
Also used : WebSocketListener(org.web3j.protocol.websocket.WebSocketListener) ConditionTimeoutException(org.awaitility.core.ConditionTimeoutException) WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException) WebSocketClient(org.web3j.protocol.websocket.WebSocketClient) ConditionTimeoutException(org.awaitility.core.ConditionTimeoutException) WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException) ConnectException(java.net.ConnectException) IOException(java.io.IOException)

Example 2 with WebSocketClient

use of org.web3j.protocol.websocket.WebSocketClient in project besu by hyperledger.

the class BesuNode method nodeRequests.

private NodeRequests nodeRequests() {
    Optional<WebSocketService> websocketService = Optional.empty();
    if (nodeRequests == null) {
        final Web3jService web3jService;
        if (useWsForJsonRpc) {
            final String url = wsRpcBaseUrl().orElse("ws://" + LOCALHOST + ":" + 8546);
            final Map<String, String> headers = new HashMap<>();
            if (token != null) {
                headers.put("Authorization", "Bearer " + token);
            }
            final WebSocketClient wsClient = new WebSocketClient(URI.create(url), headers);
            web3jService = new WebSocketService(wsClient, false);
            try {
                ((WebSocketService) web3jService).connect();
            } catch (final ConnectException e) {
                throw new RuntimeException(e);
            }
            websocketService = Optional.of((WebSocketService) web3jService);
        } else {
            final String url = jsonRpcBaseUrl().orElse(HTTP + LOCALHOST + ":" + 8545);
            web3jService = new HttpService(url);
            if (token != null) {
                ((HttpService) web3jService).addHeader("Authorization", "Bearer " + token);
            }
        }
        final ConsensusType bftType = getGenesisConfig().map(gc -> gc.toLowerCase().contains("ibft") ? ConsensusType.IBFT2 : ConsensusType.QBFT).orElse(ConsensusType.IBFT2);
        nodeRequests = new NodeRequests(new JsonRpc2_0Web3j(web3jService, 2000, Async.defaultExecutorService()), new CliqueRequestFactory(web3jService), new BftRequestFactory(web3jService, bftType), new PermissioningJsonRpcRequestFactory(web3jService), new AdminRequestFactory(web3jService), new PrivacyRequestFactory(web3jService), new CustomRequestFactory(web3jService), new MinerRequestFactory(web3jService), new TxPoolRequestFactory(web3jService), websocketService, loginRequestFactory());
    }
    return nodeRequests;
}
Also used : KeyPairUtil(org.hyperledger.besu.crypto.KeyPairUtil) Collections.unmodifiableList(java.util.Collections.unmodifiableList) ConsensusType(org.hyperledger.besu.tests.acceptance.dsl.transaction.bft.ConsensusType) PermissioningConfiguration(org.hyperledger.besu.ethereum.permissioning.PermissioningConfiguration) LoggerFactory(org.slf4j.LoggerFactory) WebSocketService(org.web3j.protocol.websocket.WebSocketService) WebSocketConfiguration(org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration) Transaction(org.hyperledger.besu.tests.acceptance.dsl.transaction.Transaction) NetworkName(org.hyperledger.besu.cli.config.NetworkName) Map(java.util.Map) Web3jService(org.web3j.protocol.Web3jService) TxPoolRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.txpool.TxPoolRequestFactory) GenesisConfigurationProvider(org.hyperledger.besu.tests.acceptance.dsl.node.configuration.genesis.GenesisConfigurationProvider) URI(java.net.URI) Path(java.nio.file.Path) WebSocketClient(org.web3j.protocol.websocket.WebSocketClient) MinerRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.miner.MinerRequestFactory) NetworkingConfiguration(org.hyperledger.besu.ethereum.p2p.config.NetworkingConfiguration) Files.copyResource(org.apache.tuweni.io.file.Files.copyResource) MiningParameters(org.hyperledger.besu.ethereum.core.MiningParameters) ConditionTimeoutException(org.awaitility.core.ConditionTimeoutException) PrivacyRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.privacy.PrivacyRequestFactory) List(java.util.List) Optional(java.util.Optional) WebsocketNotConnectedException(org.java_websocket.exceptions.WebsocketNotConnectedException) Awaitility(org.awaitility.Awaitility) Condition(org.hyperledger.besu.tests.acceptance.dsl.condition.Condition) CliqueRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.clique.CliqueRequestFactory) HttpService(org.web3j.protocol.http.HttpService) Async(org.web3j.utils.Async) HashMap(java.util.HashMap) Address(org.hyperledger.besu.datatypes.Address) Util(org.hyperledger.besu.ethereum.core.Util) TLSConfiguration(org.hyperledger.besu.ethereum.p2p.rlpx.connections.netty.TLSConfiguration) ArrayList(java.util.ArrayList) AdminRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.admin.AdminRequestFactory) LoginRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.login.LoginRequestFactory) JsonRpcConfiguration(org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration) ConnectException(java.net.ConnectException) BftRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.bft.BftRequestFactory) Properties(java.util.Properties) Logger(org.slf4j.Logger) JsonRpc2_0Web3j(org.web3j.protocol.core.JsonRpc2_0Web3j) Files(java.nio.file.Files) MoreObjects(com.google.common.base.MoreObjects) NodeConfiguration(org.hyperledger.besu.tests.acceptance.dsl.node.configuration.NodeConfiguration) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) RecursiveDeleteOption(com.google.common.io.RecursiveDeleteOption) MetricsConfiguration(org.hyperledger.besu.metrics.prometheus.MetricsConfiguration) PermissioningJsonRpcRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.perm.PermissioningJsonRpcRequestFactory) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) WebSocketListener(org.web3j.protocol.websocket.WebSocketListener) JsonRpcIpcConfiguration(org.hyperledger.besu.ethereum.api.jsonrpc.ipc.JsonRpcIpcConfiguration) KeyPair(org.hyperledger.besu.crypto.KeyPair) MoreFiles(com.google.common.io.MoreFiles) CustomRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.net.CustomRequestFactory) PrivacyParameters(org.hyperledger.besu.ethereum.core.PrivacyParameters) PkiKeyStoreConfiguration(org.hyperledger.besu.pki.config.PkiKeyStoreConfiguration) NodeRequests(org.hyperledger.besu.tests.acceptance.dsl.transaction.NodeRequests) HashMap(java.util.HashMap) NodeRequests(org.hyperledger.besu.tests.acceptance.dsl.transaction.NodeRequests) PrivacyRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.privacy.PrivacyRequestFactory) CliqueRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.clique.CliqueRequestFactory) WebSocketClient(org.web3j.protocol.websocket.WebSocketClient) BftRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.bft.BftRequestFactory) TxPoolRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.txpool.TxPoolRequestFactory) ConsensusType(org.hyperledger.besu.tests.acceptance.dsl.transaction.bft.ConsensusType) HttpService(org.web3j.protocol.http.HttpService) AdminRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.admin.AdminRequestFactory) Web3jService(org.web3j.protocol.Web3jService) CustomRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.net.CustomRequestFactory) MinerRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.miner.MinerRequestFactory) WebSocketService(org.web3j.protocol.websocket.WebSocketService) JsonRpc2_0Web3j(org.web3j.protocol.core.JsonRpc2_0Web3j) PermissioningJsonRpcRequestFactory(org.hyperledger.besu.tests.acceptance.dsl.transaction.perm.PermissioningJsonRpcRequestFactory) ConnectException(java.net.ConnectException)

Example 3 with WebSocketClient

use of org.web3j.protocol.websocket.WebSocketClient in project wuhanchain by BSN-DDC.

the class EventListenerByBlock method getBlockEventByListener.

/**
 * get block event
 *
 * @param startBlockNum blockNumber
 * @return ddc official contract event data
 * @throws Exception
 */
public void getBlockEventByListener(BigInteger startBlockNum, String wsUrl, Map<String, String> httpHeaders) {
    try {
        // webSocketClient
        WebSocketClient webSocketClient = new WebSocketClient(new URI(wsUrl), httpHeaders);
        WebSocketService webSocketService = new WebSocketService(webSocketClient, false);
        webSocketService.connect();
        web3j = Web3j.build(webSocketService);
        // ThreadPool
        executorService = new ThreadPoolExecutor(8, 8, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100000), new ThreadPoolExecutor.CallerRunsPolicy());
        // startBlock, endBlock, fullTransactionObjects
        subscribe = web3j.replayPastAndFutureBlocksFlowable(DefaultBlockParameter.valueOf(startBlockNum), true).doOnError(e -> logger.error("doOnError:" + e.getMessage())).subscribe(this::executeBlock, ex -> logger.error("subscribe:" + ex.getMessage()), () -> onCompleted());
        while (true) {
            if (subscriptions) {
                break;
            }
        }
    } catch (Exception e) {
        logger.error("analysisResult:" + e);
    }
}
Also used : EthBlock(org.web3j.protocol.core.methods.response.EthBlock) Logger(org.slf4j.Logger) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) LoggerFactory(org.slf4j.LoggerFactory) DefaultBlockParameter(org.web3j.protocol.core.DefaultBlockParameter) WebSocketService(org.web3j.protocol.websocket.WebSocketService) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) Disposable(io.reactivex.disposables.Disposable) List(java.util.List) BaseEventBean(com.reddate.ddc.dto.ddc.BaseEventBean) Web3j(org.web3j.protocol.Web3j) CollectionUtils(org.springframework.util.CollectionUtils) Map(java.util.Map) JSONObject(com.alibaba.fastjson.JSONObject) BigInteger(java.math.BigInteger) URI(java.net.URI) WebSocketClient(org.web3j.protocol.websocket.WebSocketClient) WebSocketService(org.web3j.protocol.websocket.WebSocketService) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) WebSocketClient(org.web3j.protocol.websocket.WebSocketClient) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) URI(java.net.URI)

Aggregations

WebSocketClient (org.web3j.protocol.websocket.WebSocketClient)3 IOException (java.io.IOException)2 ConnectException (java.net.ConnectException)2 URI (java.net.URI)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Map (java.util.Map)2 TimeUnit (java.util.concurrent.TimeUnit)2 ConditionTimeoutException (org.awaitility.core.ConditionTimeoutException)2 WebsocketNotConnectedException (org.java_websocket.exceptions.WebsocketNotConnectedException)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 WebSocketListener (org.web3j.protocol.websocket.WebSocketListener)2 WebSocketService (org.web3j.protocol.websocket.WebSocketService)2 JSONObject (com.alibaba.fastjson.JSONObject)1 MoreObjects (com.google.common.base.MoreObjects)1 MoreFiles (com.google.common.io.MoreFiles)1 RecursiveDeleteOption (com.google.common.io.RecursiveDeleteOption)1 BaseEventBean (com.reddate.ddc.dto.ddc.BaseEventBean)1 Disposable (io.reactivex.disposables.Disposable)1