Search in sources :

Example 1 with WebSocketService

use of org.web3j.protocol.websocket.WebSocketService 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 2 with WebSocketService

use of org.web3j.protocol.websocket.WebSocketService 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)

Example 3 with WebSocketService

use of org.web3j.protocol.websocket.WebSocketService in project starcoin-search by starcoinorg.

the class SubscribeHandler method run.

@Override
public void run() {
    try {
        WebSocketService service = new WebSocketService("ws://" + seedHost + ":9870", true);
        service.connect();
        StarcoinSubscriber subscriber = new StarcoinSubscriber(service);
        Flowable<PendingTransactionNotification> flowableTxns = subscriber.newPendingTransactionsNotifications();
        TransactionRPCClient rpc = new TransactionRPCClient(new URL("http://" + seedHost + ":9850"));
        for (PendingTransactionNotification notifications : flowableTxns.blockingIterable()) {
            for (String notification : notifications.getParams().getResult()) {
                logger.info("notification: {}", notification);
                PendingTransaction transaction = rpc.getPendingTransaction(notification);
                elasticSearchHandler.savePendingTransaction(transaction);
            }
        }
    } catch (ConnectException | MalformedURLException | JSONRPC2SessionException e) {
        logger.error("handle subscribe exception:", e);
    }
}
Also used : PendingTransactionNotification(org.starcoin.bean.PendingTransactionNotification) TransactionRPCClient(org.starcoin.api.TransactionRPCClient) PendingTransaction(org.starcoin.bean.PendingTransaction) MalformedURLException(java.net.MalformedURLException) JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) StarcoinSubscriber(org.starcoin.api.StarcoinSubscriber) WebSocketService(org.web3j.protocol.websocket.WebSocketService) URL(java.net.URL) ConnectException(java.net.ConnectException)

Example 4 with WebSocketService

use of org.web3j.protocol.websocket.WebSocketService in project starcoin-java by starcoinorg.

the class SubscribeSample method main.

public static void main(String... args) throws ConnectException {
    WebSocketService service = new WebSocketService("ws://localhost:9870", true);
    service.connect();
    StarcoinSubscriber subscriber = new StarcoinSubscriber(service);
    EventFilter eventFilter = new EventFilter(0, "b75994d55eae88219dc57e7e62a11bc0");
    Flowable<EventNotification> flowableTxns = subscriber.newTxnSendRecvEventNotifications(eventFilter);
    for (EventNotification notification : flowableTxns.blockingIterable()) {
        System.out.println(notification.getParams().getResult().toString());
    }
}
Also used : EventNotification(org.starcoin.bean.EventNotification) WebSocketService(org.web3j.protocol.websocket.WebSocketService) EventFilter(org.starcoin.bean.EventFilter)

Aggregations

WebSocketService (org.web3j.protocol.websocket.WebSocketService)4 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 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 WebSocketClient (org.web3j.protocol.websocket.WebSocketClient)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 JSONRPC2SessionException (com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException)1 Disposable (io.reactivex.disposables.Disposable)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1