org.fisco.bcos.channel.handler.ChannelConnections Java Examples

The following examples show how to use org.fisco.bcos.channel.handler.ChannelConnections. 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: Web3Config.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * get a new config instance
 * @return
 */
private GroupChannelConnectionsConfig getGroupChannelConnectionsConfig() {
    List<ChannelConnections> channelConnectionsList = new ArrayList<>();

    List<String> connectionsList = new ArrayList<>();
    connectionsList.add(ip + ":" + channelPort);
    log.info("*****" + ip + ":" + channelPort);
    ChannelConnections channelConnections = new ChannelConnections();
    channelConnections.setConnectionsStr(connectionsList);
    channelConnections.setGroupId(independentGroupId);
    channelConnectionsList.add(channelConnections);

    GroupChannelConnectionsConfig groupChannelConnectionsConfig =
        new GroupChannelConnectionsConfig();
    groupChannelConnectionsConfig.setAllChannelConnections(channelConnectionsList);
    return groupChannelConnectionsConfig;
}
 
Example #2
Source File: Web3ApiService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * init a new web3j of group id, add in groupChannelConnectionsConfig's connections
 * @param groupId
 * @return
 */
private synchronized Web3j initWeb3j(int groupId) {
    log.info("initWeb3j of groupId:{}", groupId);
    List<ChannelConnections> channelConnectionsList =
            groupChannelConnectionsConfig.getAllChannelConnections();
    ChannelConnections channelConnections = new ChannelConnections();
    channelConnections.setConnectionsStr(channelConnectionsList.get(0).getConnectionsStr());
    channelConnections.setGroupId(groupId);
    channelConnectionsList.add(channelConnections);
    org.fisco.bcos.channel.client.Service service = new org.fisco.bcos.channel.client.Service();
    service.setOrgID(Web3Config.orgName);
    service.setGroupId(groupId);
    service.setThreadPool(threadPoolTaskExecutor);
    service.setAllChannelConnections(groupChannelConnectionsConfig);
    try {
        service.run();
    } catch (Exception e) {
        log.error("initWeb3j fail. groupId:{} error:[]", groupId, e);
        throw new FrontException("refresh web3j failed");
    }
    ChannelEthereumService channelEthereumService = new ChannelEthereumService();
    channelEthereumService.setTimeout(web3Config.getTimeout());
    channelEthereumService.setChannelService(service);
    Web3j web3j = Web3j.build(channelEthereumService, service.getGroupId());
    web3jMap.put(groupId, web3j);
    return web3j;
}
 
Example #3
Source File: TransService.java    From WeBASE-Transaction with Apache License 2.0 5 votes vote down vote up
/**
 * check groupId.
 * 
 * @param groupId info
 * @return
 */
public boolean checkGroupId(int groupId) {
    List<ChannelConnections> connList = web3Config.getGroupConfig().getAllChannelConnections();
    for (ChannelConnections conn : connList) {
        if (groupId == conn.getGroupId()) {
            return true;
        }
    }
    return false;
}
 
Example #4
Source File: Web3jV2BeanConfig.java    From WeBASE-Collect-Bee with Apache License 2.0 5 votes vote down vote up
@Bean
public GroupChannelConnectionsConfig getGroupChannelConnections() {
    GroupChannelConnectionsConfig groupChannelConnectionsConfig = new GroupChannelConnectionsConfig();
    ChannelConnections con = new ChannelConnections();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource ca = resolver.getResource("file:./config/ca.crt");
    Resource nodeCrt = resolver.getResource("file:./config/node.crt");
    Resource nodeKey = resolver.getResource("file:./config/node.key");
    groupChannelConnectionsConfig.setCaCert(ca);
    groupChannelConnectionsConfig.setSslCert(nodeCrt);
    groupChannelConnectionsConfig.setSslKey(nodeKey);
    ArrayList<String> list = new ArrayList<>();
    List<ChannelConnections> allChannelConnections = new ArrayList<>();
    String[] nodes = StringUtils.split(systemEnvironmentConfig.getNodeStr(), ";");
    for (int i = 0; i < nodes.length; i++) {
        if (nodes[i].contains("@")) {
            nodes[i] = StringUtils.substringAfter(nodes[i], "@");
        }
    }
    List<String> nodesList = Lists.newArrayList(nodes);
    list.addAll(nodesList);
    list.stream().forEach(s -> {
        log.info("connect address: {}", s);
    });
    con.setConnectionsStr(list);
    con.setGroupId(systemEnvironmentConfig.getGroupId());
    allChannelConnections.add(con);
    groupChannelConnectionsConfig.setAllChannelConnections(allChannelConnections);
    return groupChannelConnectionsConfig;
}
 
Example #5
Source File: Web3SDKConnector.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static Service initService(Long groupId, FiscoConfig fiscoConfig) throws BrokerException {
    log.info("begin to initialize web3sdk's Service, group id: {}", groupId);

    try {
        int web3sdkTimeout = fiscoConfig.getWeb3sdkTimeout();

        Service service = new Service();
        // change jdk.tls.namedGroups will cause https's bug: ERR_SSL_VERSION_OR_CIPHER_MISMATCH
        service.setSetJavaOpt(false);
        // group info
        service.setOrgID(fiscoConfig.getOrgId());
        service.setGroupId(groupId.intValue());
        service.setConnectSeconds(web3sdkTimeout / 1000);
        // reconnect idle time 100ms
        service.setConnectSleepPerMillis(100);

        // connect key and string
        GroupChannelConnectionsConfig connectionsConfig = new GroupChannelConnectionsConfig();
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        connectionsConfig.setCaCert(resolver.getResource("classpath:" + fiscoConfig.getCaCrtPath()));
        connectionsConfig.setSslCert(resolver.getResource("classpath:" + fiscoConfig.getSdkCrtPath()));
        connectionsConfig.setSslKey(resolver.getResource("classpath:" + fiscoConfig.getSdkKeyPath()));

        ChannelConnections channelConnections = new ChannelConnections();
        channelConnections.setGroupId(groupId.intValue());
        channelConnections.setConnectionsStr(Arrays.asList(fiscoConfig.getNodes().split(";")));
        connectionsConfig.setAllChannelConnections(Collections.singletonList(channelConnections));

        service.setAllChannelConnections(connectionsConfig);
        return service;
    } catch (Exception e) {
        log.error("init web3sdk's Service failed", e);
        throw new BrokerException(ErrorCode.WEB3SDK_INIT_SERVICE_ERROR);
    }
}
 
Example #6
Source File: Service.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public void updateTopicsToNode() {

        logger.info(" updateTopicToNode, groupId: {}, topics: {}", groupId, getTopics());

        // select send node
        ChannelConnections channelConnections =
                allChannelConnections
                        .getAllChannelConnections()
                        .stream()
                        .filter(x -> x.getGroupId() == groupId)
                        .findFirst()
                        .get();

        if (Objects.isNull(channelConnections)) {
            throw new IllegalArgumentException(
                    " No group configuration was found, groupId: " + groupId);
        }

        ConnectionCallback callback = (ConnectionCallback) channelConnections.getCallback();
        if (Objects.isNull(callback)) {
            throw new IllegalArgumentException(
                    " No callback was found for ChannelConnections, service is not initialized");
        }
        callback.setTopics(getTopics());

        /** send update topic message to all connected nodes */
        Map<String, ChannelHandlerContext> networkConnections =
                channelConnections.getNetworkConnections();
        for (ChannelHandlerContext ctx : networkConnections.values()) {
            if (Objects.nonNull(ctx) && ChannelHandlerContextHelper.isChannelAvailable(ctx)) {
                try {
                    callback.sendUpdateTopicMessage(ctx);
                } catch (Exception e) {
                    logger.debug(" e: ", e);
                }
            }
        }
    }
 
Example #7
Source File: Service.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public void asyncSendEthereumMessage(BcosRequest request, BcosResponseCallback callback) {
    BcosMessage bcosMessage = new BcosMessage();

    bcosMessage.setSeq(request.getMessageID());
    bcosMessage.setResult(0);
    bcosMessage.setType((short) 0x12);
    bcosMessage.setData(request.getContent().getBytes());
    // select node
    try {
        ChannelConnections channelConnections =
                allChannelConnections
                        .getAllChannelConnections()
                        .stream()
                        .filter(x -> x.getGroupId() == groupId)
                        .findFirst()
                        .get();

        if (channelConnections == null) {
            if (orgID != null) {
                logger.error("not found:{}", orgID);
                throw new TransactionException("not found orgID");
            } else {
                logger.error("not found:{}", agencyName);
                throw new TransactionException("not found agencyName");
            }
        }
        ChannelHandlerContext ctx =
                channelConnections.randomNetworkConnection(nodeToBlockNumberMap);

        ByteBuf out = ctx.alloc().buffer();
        bcosMessage.writeHeader(out);
        bcosMessage.writeExtra(out);

        seq2Callback.put(request.getMessageID(), callback);

        if (request.getTimeout() > 0) {
            final BcosResponseCallback callbackInner = callback;
            callback.setTimeout(
                    timeoutHandler.newTimeout(
                            new TimerTask() {
                                BcosResponseCallback _callback = callbackInner;

                                @Override
                                public void run(Timeout timeout) throws Exception {
                                    // handle timer
                                    _callback.onTimeout();
                                }
                            },
                            request.getTimeout(),
                            TimeUnit.MILLISECONDS));
        }

        ctx.writeAndFlush(out);
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        InetSocketAddress socketAddress = socketChannel.remoteAddress();
        logger.debug(
                "selected node {}:{} bcos request, seq:{}",
                socketAddress.getAddress().getHostAddress(),
                socketAddress.getPort(),
                bcosMessage.getSeq());

    } catch (Exception e) {
        logger.error(" error message:{}, error: {} ", e.getMessage(), e);

        BcosResponse response = new BcosResponse();
        response.setErrorCode(-1);
        response.setErrorMessage(
                e.getMessage()
                        + " requset send failed! please check the log file content for reasons.");
        response.setContent("");
        response.setMessageID(request.getMessageID());

        if (callback.getTimeout() != null) {
            callback.getTimeout().cancel();
        }
        callback.onResponse(response);
    }
}
 
Example #8
Source File: ChannelResponseCallback2.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public ChannelConnections getFromChannelConnections() {
    return fromChannelConnections;
}
 
Example #9
Source File: ChannelResponseCallback2.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public void setFromChannelConnections(ChannelConnections fromConnectionConnections) {
    this.fromChannelConnections = fromConnectionConnections;
}