Search in sources :

Example 6 with ChannelResponse

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

the class Channel2ClientBinNeedVerify method main.

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.out.println("param: target topic filename of request");
        return;
    }
    String topic = args[0];
    String filename = args[1];
    Integer count = 10;
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    logger.debug("init client");
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Service service = context.getBean(Service.class);
    service.run();
    System.out.println("3s ...");
    Thread.sleep(1000);
    System.out.println("2s ...");
    Thread.sleep(1000);
    System.out.println("1s ...");
    Thread.sleep(1000);
    System.out.println("start test");
    System.out.println("===================================================================");
    for (Integer i = 0; i < count; ++i) {
        Thread.sleep(2000);
        ChannelRequest request = new ChannelRequest();
        request.setToTopic(topic);
        request.setMessageID(service.newSeq());
        request.setTimeout(5000);
        /*设置为-128表示为传输二进制*/
        int flag = -128;
        byte[] byteflag = intToByteArray(flag);
        int filelength = filename.length();
        byte[] bytelength = intToByteArray(filelength);
        byte[] bytefilename = filename.getBytes();
        byte[] contentfile = toByteArrFromFile(filename);
        byte[] content = byteCat(byteCat(byteCat(byteflag, bytelength), bytefilename), contentfile);
        request.setContent(content);
        logger.info("msg:" + Arrays.toString(content));
        System.out.println(df.format(LocalDateTime.now()) + " request seq:" + String.valueOf(request.getMessageID()) + " content length:" + content.length);
        ChannelResponse response = service.sendChannelMessageForVerifyTopic(request);
        System.out.println(df.format(LocalDateTime.now()) + "response seq:" + String.valueOf(response.getMessageID()) + ", ErrorCode:" + response.getErrorCode() + ", Content:" + response.getContent());
        if (response.getErrorCode() != 0) {
            System.out.println("Error message" + response.getErrorMessage());
        }
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ChannelRequest(org.fisco.bcos.channel.dto.ChannelRequest) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Service(org.fisco.bcos.channel.client.Service) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 7 with ChannelResponse

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

the class ChannelResponseCallback2 method onTimeout.

public final void onTimeout() {
    // logger.error("send message timeout:{}", message.getSeq());
    ChannelResponse response = new ChannelResponse();
    response.setErrorCode(ChannelMessageError.MESSAGE_TIMEOUT.getError());
    response.setMessageID(message.getSeq());
    response.setErrorMessage("send message timeout");
    response.setContent("");
    try {
        onResponseMessage(response);
    } catch (Exception e) {
        logger.error("timeout processing error:", e);
    }
    service.getSeq2Callback().remove(message.getSeq());
    timeout.cancel();
}
Also used : ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse)

Example 8 with ChannelResponse

use of org.fisco.bcos.channel.dto.ChannelResponse 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 9 with ChannelResponse

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

the class Service method signForAmop.

public void signForAmop(ChannelHandlerContext ctx, ChannelMessage2 message) throws IOException {
    SocketChannel socketChannel = (SocketChannel) ctx.channel();
    logger.info("sign ChannelResponse seq:{} msgtype:{} address:{} port:{}", message.getSeq(), message.getType(), socketChannel.remoteAddress().getAddress().getHostAddress(), socketChannel.remoteAddress().getPort());
    logger.info("sign request :{} length:{}", Arrays.toString(message.getData()), message.getLength());
    String content = topicVerify.parseDataFromPush(message.getLength(), message.getData());
    logger.info("content:{} content:{}", content, Arrays.toString(content.getBytes()));
    TopicVerifyReqProtocol topicVerifyProtocol = ObjectMapperFactory.getObjectMapper().readValue(content, TopicVerifyReqProtocol.class);
    String randValue = topicVerifyProtocol.getRandValue();
    String topic = topicVerifyProtocol.getTopic();
    logger.info("sign rand_value:{} sign topic:{}", randValue, topic);
    String signature = topicVerify.signatureForRandValue(topic, randValue);
    TopicVerifyRespProtocol topicVerifyRespProtocol = new TopicVerifyRespProtocol();
    topicVerifyRespProtocol.setSignature(signature);
    String jsonStr = ObjectMapperFactory.getObjectMapper().writeValueAsString(topicVerifyRespProtocol);
    logger.info("signature jsonStr result:{}", jsonStr);
    byte[] bytes = topicVerify.getByteBuffByString(message.getTopic(), jsonStr);
    ChannelResponse response = new ChannelResponse();
    response.setMessageID(message.getSeq());
    response.setErrorCode(0);
    response.setContent(bytes);
    sendResponseMessage2(response, ctx, message.getSeq(), message.getTopic());
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) TopicVerifyReqProtocol(org.fisco.bcos.channel.protocol.TopicVerifyReqProtocol) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) TopicVerifyRespProtocol(org.fisco.bcos.channel.protocol.TopicVerifyRespProtocol)

Example 10 with ChannelResponse

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

the class Service method sendChannelMessage2.

public ChannelResponse sendChannelMessage2(ChannelRequest request) {
    class Callback extends ChannelResponseCallback2 {

        public transient ChannelResponse channelResponse;

        public transient Semaphore semaphore = new Semaphore(1, true);

        Callback() {
            try {
                semaphore.acquire(1);
            } catch (InterruptedException e) {
                logger.error("error:", e);
                Thread.currentThread().interrupt();
            }
        }

        @Override
        public void onResponseMessage(ChannelResponse response) {
            channelResponse = response;
            logger.debug("response: {}", response.getContent());
            semaphore.release();
        }
    }
    ;
    request.setType((short) ChannelMessageType.AMOP_REQUEST.getType());
    Callback callback = new Callback();
    asyncSendChannelMessage2(request, callback);
    try {
        callback.semaphore.acquire(1);
    } catch (InterruptedException e) {
        logger.error("system error:", e);
        Thread.currentThread().interrupt();
    }
    return callback.channelResponse;
}
Also used : ConnectionCallback(org.fisco.bcos.channel.handler.ConnectionCallback) EventLogPushCallback(org.fisco.bcos.channel.event.filter.EventLogPushCallback) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) Semaphore(java.util.concurrent.Semaphore)

Aggregations

ChannelResponse (org.fisco.bcos.channel.dto.ChannelResponse)16 ChannelRequest (org.fisco.bcos.channel.dto.ChannelRequest)6 IOException (java.io.IOException)5 DateTimeFormatter (java.time.format.DateTimeFormatter)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 KeyStoreException (java.security.KeyStoreException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 NoSuchProviderException (java.security.NoSuchProviderException)4 CertificateException (java.security.cert.CertificateException)4 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)4 Service (org.fisco.bcos.channel.client.Service)4 TransactionException (org.fisco.bcos.web3j.protocol.exceptions.TransactionException)4 ApplicationContext (org.springframework.context.ApplicationContext)4 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)4 ByteBuf (io.netty.buffer.ByteBuf)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 SocketChannel (io.netty.channel.socket.SocketChannel)2 ChannelMessage2 (org.fisco.bcos.channel.dto.ChannelMessage2)2 EventLogPushCallback (org.fisco.bcos.channel.event.filter.EventLogPushCallback)2