Search in sources :

Example 1 with ChannelMessage2

use of org.fisco.bcos.channel.dto.ChannelMessage2 in project web3sdk by FISCO-BCOS.

the class Service method sendResponseMessage2.

public void sendResponseMessage2(ChannelResponse response, ChannelHandlerContext ctx, String seq, String topic) {
    try {
        ChannelMessage2 responseMessage = new ChannelMessage2();
        responseMessage.setData(response.getContentByteArray());
        responseMessage.setResult(response.getErrorCode());
        responseMessage.setSeq(seq);
        responseMessage.setType((short) ChannelMessageType.AMOP_RESPONSE.getType());
        responseMessage.setTopic(topic);
        ByteBuf out = ctx.alloc().buffer();
        responseMessage.writeHeader(out);
        responseMessage.writeExtra(out);
        ctx.writeAndFlush(out);
        logger.info("response seq:{} length:{}", response.getMessageID(), out.readableBytes());
    } catch (Exception e) {
        logger.error("system error:{}", e);
    }
}
Also used : ChannelMessage2(org.fisco.bcos.channel.dto.ChannelMessage2) ByteBuf(io.netty.buffer.ByteBuf) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 2 with ChannelMessage2

use of org.fisco.bcos.channel.dto.ChannelMessage2 in project web3sdk by FISCO-BCOS.

the class Service method asyncSendChannelMessage2.

public void asyncSendChannelMessage2(ChannelRequest request, ChannelResponseCallback2 callback) {
    try {
        if (request.getContentByteArray().length >= 32 * 1024 * 1024) {
            logger.error("send byte length should not greater than 32M now length:{}", request.getContentByteArray().length);
            throw new AmopException("send byte length should not greater than 32M");
        }
        logger.debug("ChannelRequest:{} ", request.getMessageID());
        callback.setService(this);
        ChannelMessage2 channelMessage = new ChannelMessage2();
        channelMessage.setSeq(request.getMessageID());
        channelMessage.setResult(0);
        // channelMessage.setType((short) ChannelMessageType.AMOP_REQUEST.getType());
        if (request.getType() == 0) {
            channelMessage.setType((short) ChannelMessageType.AMOP_REQUEST.getType());
        } else {
            channelMessage.setType(request.getType());
        }
        channelMessage.setData(request.getContentByteArray());
        channelMessage.setTopic(request.getToTopic());
        logger.info("msgid:{} type:{} topic:{}", request.getMessageID(), channelMessage.getType(), request.getToTopic());
        try {
            List<ConnectionInfo> fromConnectionInfos = new ArrayList<ConnectionInfo>();
            // select send node
            ChannelConnections fromChannelConnections = allChannelConnections.getAllChannelConnections().stream().filter(x -> x.getGroupId() == groupId).findFirst().get();
            if (fromChannelConnections == null) {
                if (orgID != null) {
                    logger.error("not found:{}", orgID);
                    throw new Exception("not found orgID");
                } else {
                    logger.error("not found:{}", agencyName);
                    throw new Exception("not found agencyName");
                }
            }
            fromConnectionInfos.addAll(fromChannelConnections.getConnections());
            logger.debug("FromOrg:{} nodes:{}", request.getFromOrg(), fromChannelConnections.getConnections().size());
            callback.setFromChannelConnections(fromChannelConnections);
            callback.setFromConnectionInfos(fromConnectionInfos);
            // set request content
            callback.setRequest(channelMessage);
            logger.info("put msgid:{} into callback map", request.getMessageID());
            seq2Callback.put(request.getMessageID(), callback);
            if (request.getTimeout() > 0) {
                logger.info("timeoutms:{}", request.getTimeout());
                final ChannelResponseCallback2 callbackInner = callback;
                callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {

                    ChannelResponseCallback2 _callback = callbackInner;

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        // process timeout logic
                        _callback.onTimeout();
                        logger.error("process channel message timeout, seq: {}, timeout: {}", channelMessage.getSeq(), request.getTimeout());
                    }
                }, request.getTimeout(), TimeUnit.MILLISECONDS));
            }
            callback.retrySendMessage();
        } catch (Exception e) {
            logger.error("send message fail:", e);
            ChannelResponse response = new ChannelResponse();
            response.setErrorCode(ChannelMessageError.MESSAGE_SEND_EXCEPTION.getError());
            response.setMessageID(request.getMessageID());
            response.setErrorMessage(e.getMessage());
            response.setContent("");
            callback.onResponse(response);
            return;
        }
    } catch (Exception e) {
        logger.error("system error", e);
    }
}
Also used : ChannelConnections(org.fisco.bcos.channel.handler.ChannelConnections) ChannelMessage2(org.fisco.bcos.channel.dto.ChannelMessage2) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) ArrayList(java.util.ArrayList) ConnectionInfo(org.fisco.bcos.channel.handler.ConnectionInfo) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 3 with ChannelMessage2

use of org.fisco.bcos.channel.dto.ChannelMessage2 in project web3sdk by FISCO-BCOS.

the class ChannelMessage2Test method channelMessage2CodecTest2.

@Test
public void channelMessage2CodecTest2() {
    ChannelMessage2 channelMessage2 = new ChannelMessage2();
    String seq = UUID.randomUUID().toString().replaceAll("-", "");
    Integer result = Integer.valueOf(0);
    String content = "中文测试";
    String topic = "中文topic测试";
    channelMessage2.setSeq(seq);
    channelMessage2.setResult(result);
    channelMessage2.setType((short) ChannelMessageType.AMOP_REQUEST.getType());
    channelMessage2.setData(content.getBytes());
    channelMessage2.setTopic(topic);
    ByteBuf buffer = Unpooled.buffer();
    channelMessage2.writeHeader(buffer);
    channelMessage2.writeExtra(buffer);
    ChannelMessage2 channelMessage21 = new ChannelMessage2();
    channelMessage21.readHeader(buffer);
    channelMessage21.readExtra(buffer);
    assertEquals(channelMessage21.getTopic(), topic);
    assertEquals(new String(channelMessage21.getData()), content);
    assertEquals(channelMessage21.getResult(), result);
    assertEquals(channelMessage21.getSeq(), seq);
    assertEquals(channelMessage21.getType().intValue(), ChannelMessageType.AMOP_REQUEST.getType());
}
Also used : ChannelMessage2(org.fisco.bcos.channel.dto.ChannelMessage2) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 4 with ChannelMessage2

use of org.fisco.bcos.channel.dto.ChannelMessage2 in project web3sdk by FISCO-BCOS.

the class Service method asyncMulticastChannelMessage2.

public void asyncMulticastChannelMessage2(ChannelRequest request) {
    try {
        logger.debug("ChannelRequest:{} ", request.getMessageID());
        ChannelMessage2 channelMessage = new ChannelMessage2();
        channelMessage.setSeq(request.getMessageID());
        channelMessage.setResult(0);
        channelMessage.setType((short) ChannelMessageType.AMOP_MULBROADCAST.getType());
        channelMessage.setData(request.getContentByteArray());
        channelMessage.setTopic(request.getToTopic());
        try {
            // set request content
            ChannelConnections fromChannelConnections = allChannelConnections.getAllChannelConnections().stream().filter(x -> x.getGroupId() == groupId).findFirst().get();
            if (fromChannelConnections == null) {
                if (orgID != null) {
                    logger.error("not found:{}", orgID);
                    throw new Exception("not found orgID");
                } else {
                    logger.error("not found:{}", agencyName);
                    throw new Exception("not found agencyName");
                }
            }
            logger.debug("FromOrg:{} nodes:{}", request.getFromOrg(), fromChannelConnections.getConnections().size());
            for (ConnectionInfo connectionInfo : fromChannelConnections.getConnections()) {
                ChannelHandlerContext ctx = fromChannelConnections.getNetworkConnectionByHost(connectionInfo.getHost(), connectionInfo.getPort());
                if (ctx != null && ChannelHandlerContextHelper.isChannelAvailable(ctx)) {
                    ByteBuf out = ctx.alloc().buffer();
                    channelMessage.writeHeader(out);
                    channelMessage.writeExtra(out);
                    ctx.writeAndFlush(out);
                    logger.debug("send message to{}:{} success ", connectionInfo.getHost(), connectionInfo.getPort());
                } else {
                    logger.error("sending node unavailable, {}:{}", connectionInfo.getHost(), connectionInfo.getPort());
                }
            }
        } catch (Exception e) {
            logger.error("send message fail:{}", e);
            ChannelResponse response = new ChannelResponse();
            response.setErrorCode(ChannelMessageError.MESSAGE_SEND_EXCEPTION.getError());
            response.setMessageID(request.getMessageID());
            response.setErrorMessage(e.getMessage());
            response.setContent("");
            return;
        }
    } catch (Exception e) {
        logger.error("system error:{}", e);
    }
}
Also used : ChannelConnections(org.fisco.bcos.channel.handler.ChannelConnections) ChannelMessage2(org.fisco.bcos.channel.dto.ChannelMessage2) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ConnectionInfo(org.fisco.bcos.channel.handler.ConnectionInfo) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) ByteBuf(io.netty.buffer.ByteBuf) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 5 with ChannelMessage2

use of org.fisco.bcos.channel.dto.ChannelMessage2 in project web3sdk by FISCO-BCOS.

the class ConnectionCallback method onMessage.

@Override
public void onMessage(ChannelHandlerContext ctx, ByteBuf message) {
    try {
        Message msg = new Message();
        try {
            msg.readHeader(message);
        } catch (Exception e) {
            String host = ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress();
            Integer port = ((SocketChannel) ctx.channel()).remoteAddress().getPort();
            logger.error(" Maybe p2p port is used to channel connection, please check the configuration, peer {}:{}", host, port);
            throw new RuntimeException(e.getCause());
        }
        logger.trace("onMessage, seq:{}, type: {}, result: {}", msg.getSeq(), msg.getType(), msg.getResult());
        if (msg.getType() == ChannelMessageType.AMOP_REQUEST.getType() || msg.getType() == ChannelMessageType.AMOP_RESPONSE.getType() || msg.getType() == ChannelMessageType.AMOP_MULBROADCAST.getType()) {
            ChannelMessage2 channelMessage = new ChannelMessage2(msg);
            channelMessage.readExtra(message);
            channelService.onReceiveChannelMessage2(ctx, channelMessage);
        } else if (msg.getType() == ChannelMessageType.CHANNEL_RPC_REQUEST.getType()) {
            BcosMessage fiscoMessage = new BcosMessage(msg);
            fiscoMessage.readExtra(message);
            channelService.onReceiveEthereumMessage(ctx, fiscoMessage);
        } else if (msg.getType() == ChannelMessageType.CLIENT_HEARTBEAT.getType()) {
            msg.readExtra(message);
            channelService.onReceiveHeartbeat(ctx, msg);
        } else if (msg.getType() == ChannelMessageType.CLIENT_HANDSHAKE.getType()) {
            BcosMessage fiscoMessage = new BcosMessage(msg);
            fiscoMessage.readExtra(message);
            channelService.onReceiveEthereumMessage(ctx, fiscoMessage);
        } else if (msg.getType() == ChannelMessageType.CLIENT_REGISTER_EVENT_LOG.getType()) {
            ChannelMessage2 channelMessage = new ChannelMessage2(msg);
            channelMessage.readExtra(message);
            channelService.onReceiveRegisterEventResponse(ctx, channelMessage);
        } else if (msg.getType() == ChannelMessageType.TRANSACTION_NOTIFY.getType()) {
            BcosMessage fiscoMessage = new BcosMessage(msg);
            fiscoMessage.readExtra(message);
            channelService.onReceiveTransactionMessage(ctx, fiscoMessage);
        } else if (msg.getType() == ChannelMessageType.BLOCK_NOTIFY.getType()) {
            // new block notify
            ChannelMessage2 channelMessage = new ChannelMessage2(msg);
            channelMessage.readExtra(message);
            channelService.onReceiveBlockNotify(ctx, channelMessage);
        } else if (msg.getType() == ChannelMessageType.EVENT_LOG_PUSH.getType()) {
            BcosMessage bcosMessage = new BcosMessage(msg);
            bcosMessage.readExtra(message);
            channelService.onReceiveEventLogPush(ctx, bcosMessage);
        } else if (msg.getType() == ChannelMessageType.REQUEST_TOPICCERT.getType()) {
            logger.info("get generate rand value request data");
            TopicVerifyMessage channelMessage = new TopicVerifyMessage(msg);
            channelMessage.readExtra(message);
            try {
                channelService.checkTopicVerify(ctx, channelMessage);
            } catch (IOException e) {
                logger.error("on receive channel failed");
            }
        } else {
            logger.error("unknown message type:{}", msg.getType());
        }
    } finally {
        message.release();
    }
}
Also used : BigInteger(java.math.BigInteger) SocketChannel(io.netty.channel.socket.SocketChannel) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) ChannelMessage2(org.fisco.bcos.channel.dto.ChannelMessage2) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) TopicVerifyMessage(org.fisco.bcos.channel.dto.TopicVerifyMessage) IOException(java.io.IOException) MessageDecodingException(org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) TopicVerifyMessage(org.fisco.bcos.channel.dto.TopicVerifyMessage)

Aggregations

ChannelMessage2 (org.fisco.bcos.channel.dto.ChannelMessage2)6 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 ByteBuf (io.netty.buffer.ByteBuf)4 IOException (java.io.IOException)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 NoSuchProviderException (java.security.NoSuchProviderException)3 CertificateException (java.security.cert.CertificateException)3 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)3 TransactionException (org.fisco.bcos.web3j.protocol.exceptions.TransactionException)3 ChannelResponse (org.fisco.bcos.channel.dto.ChannelResponse)2 ChannelConnections (org.fisco.bcos.channel.handler.ChannelConnections)2 ConnectionInfo (org.fisco.bcos.channel.handler.ConnectionInfo)2 Test (org.junit.Test)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 SocketChannel (io.netty.channel.socket.SocketChannel)1 Timeout (io.netty.util.Timeout)1 TimerTask (io.netty.util.TimerTask)1 BigInteger (java.math.BigInteger)1