org.fisco.bcos.channel.dto.ChannelResponse Java Examples

The following examples show how to use org.fisco.bcos.channel.dto.ChannelResponse. 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: AMOPSubscription.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Override
public void onPush(ChannelPush push) {
    if (!this.subTopics.containsKey(push.getTopic())) {
        log.error("unknown topic on channel, {} -> {}", push.getTopic(), this.subTopics.keySet());
        push.sendResponse(toChannelResponse(ErrorCode.UNKNOWN_ERROR));
        return;
    }
    IConsumer.ConsumerListener consumerListener = this.subTopics.get(push.getTopic());

    WeEvent event;
    try {
        event = JsonHelper.json2Object(push.getContent2(), WeEvent.class);
    } catch (BrokerException e) {
        log.error("invalid WeEvent on channel", e);
        push.sendResponse(toChannelResponse(e));
        return;
    }

    log.info("received WeEvent on channel, {}", event);
    ChannelResponse channelResponse = toChannelResponse(ErrorCode.SUCCESS);

    consumerListener.onEvent(event.getTopic(), event);
    push.sendResponse(channelResponse);
}
 
Example #2
Source File: ChannelResponseCallback2.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #3
Source File: ChannelResponseCallback2.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public final void onResponse(ChannelResponse response) {
    if (response.getErrorCode() == ChannelMessageError.NODES_UNREACHABLE.getError()) {
        logger.error("Local node error,try the next local nodec");

        retrySendMessage(); // 1表示客户端错误
    } else {
        try {
            onResponseMessage(response);
        } catch (Exception e) {
            logger.error("response package processing error:", e);
        }

        if (message.getSeq() != null) {
            service.getSeq2Callback().remove(message.getSeq());
        }

        if (timeout != null) {
            timeout.cancel();
        }
    }
}
 
Example #4
Source File: AMOPChannel.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public FileChunksMeta createReceiverFileContext(FileChunksMeta fileChunksMeta) throws BrokerException {
    log.info("send AMOP message to create receiver file context");
    FileEvent fileEvent = new FileEvent(FileEvent.EventType.FileChannelStart, fileChunksMeta.getFileId());
    fileEvent.setFileChunksMeta(fileChunksMeta);
    ChannelResponse rsp = this.sendEvent(fileChunksMeta.getTopic(), fileEvent);
    if (rsp.getErrorCode() == ErrorCode.SUCCESS.getCode()) {
        log.info("create remote file context success");
        if (!this.senderTopics.contains(fileChunksMeta.getTopic())) {
            this.senderTopics.add(fileChunksMeta.getTopic());
        }

        return JsonHelper.json2Object(rsp.getContentByteArray(), FileChunksMeta.class);
    }

    log.error("create remote file context failed");
    throw toBrokerException(rsp);
}
 
Example #5
Source File: Service.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #6
Source File: AMOPChannel.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public ChannelResponse sendEvent(String topic, FileEvent fileEvent) throws BrokerException {
    if (this.subTopics.contains(topic) || this.subVerifyTopics.containsKey(topic)) {
        log.error("this is already receiver side for topic: {}", topic);
        throw new BrokerException(ErrorCode.FILE_SENDER_RECEIVER_CONFLICT);
    }

    byte[] json = JsonHelper.object2JsonBytes(fileEvent);
    ChannelRequest channelRequest = new ChannelRequest();
    channelRequest.setToTopic(topic);
    channelRequest.setMessageID(this.service.newSeq());
    channelRequest.setTimeout(this.service.getConnectSeconds() * 1000);
    channelRequest.setContent(json);

    log.info("send channel request, topic: {} {} id: {}", channelRequest.getToTopic(), fileEvent.getEventType(), channelRequest.getMessageID());
    ChannelResponse rsp;
    StopWatch sw = StopWatch.createStarted();
    if (this.senderVerifyTopics.containsKey(topic)) {
        log.info("over verified AMOP channel");
        rsp = this.service.sendChannelMessageForVerifyTopic(channelRequest);
    } else {
        rsp = this.service.sendChannelMessage2(channelRequest);
    }
    sw.stop();
    log.info("receive channel response, id: {} result: {}-{} cost: {}", rsp.getMessageID(), rsp.getErrorCode(), rsp.getErrorMessage(), sw.getTime());
    return rsp;
}
 
Example #7
Source File: DBHandler.java    From amdb-proxy with Apache License 2.0 6 votes vote down vote up
@Override
public void onPush(ChannelPush push) {
	Integer resultCode = 0;
	
	String resultData = "";
	
	try {
		resultData = dbService.process(push.getContent());
	} catch (Exception e) {
		resultCode = -1;
		logger.error("Process request error", e);
	}
	
	//construct back to the package
	ChannelResponse response = new ChannelResponse();
	response.setMessageID(push.getMessageID());
	response.setErrorCode(resultCode);
	response.setErrorMessage("");
	response.setContent(resultData);
	
	logger.debug("Send response: {}", response.getContent());
	
	push.sendResponse(response);
}
 
Example #8
Source File: FileTransportService.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public void sendChunkData(String topic, String groupId, String fileId, int chunkIndex, byte[] data) throws BrokerException {
    // check file context exist
    FileChunksMeta fileChunksMeta = this.getSenderFileChunksMeta(topic, groupId, fileId);

    log.info("send chunk data via AMOP channel, {}#{}", fileId, chunkIndex);

    FileEvent fileEvent = new FileEvent(FileEvent.EventType.FileChannelData, fileId);
    fileEvent.setChunkIndex(chunkIndex);
    fileEvent.setChunkData(data);

    //AMOPChannel channel = this.getChannel(groupId);
    ChannelResponse rsp = channel.sendEvent(topic, fileEvent);
    if (rsp.getErrorCode() == ErrorCode.SUCCESS.getCode()) {
        log.info("sender chunk data to remote success");
        // local cached chunkStatus is not consistency, but show in stats and log only
        fileChunksMeta.getChunkStatus().set(chunkIndex);
    } else {
        BrokerException e = AMOPChannel.toBrokerException(rsp);
        log.error("sender chunk data to remote failed", e);
        throw e;
    }
}
 
Example #9
Source File: DBHandlerTest.java    From amdb-proxy with Apache License 2.0 5 votes vote down vote up
public void sendResponse(ChannelResponse response) {
	if(ex) {
		assertEquals(response.getErrorCode(), new Integer(-1));
	}
	else {
		assertEquals(response.getErrorCode(), new Integer(0));
		assertEquals(response.getContent(), "test result");
	}
}
 
Example #10
Source File: PushCallback2.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public void onPush(ChannelPush push) {
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    logger.debug("push:" + push.getContent());
    System.out.println(df.format(LocalDateTime.now()) + "server:push:" + push.getContent());

    ChannelResponse response = new ChannelResponse();
    response.setContent("receive request seq:" + String.valueOf(push.getMessageID()));
    response.setErrorCode(0);

    push.sendResponse(response);
}
 
Example #11
Source File: Service.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #12
Source File: Service.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public void onReceiveRegisterEventResponse(ChannelHandlerContext ctx, ChannelMessage2 message) {

        ChannelResponseCallback2 callback =
                (ChannelResponseCallback2) seq2Callback.get(message.getSeq());
        String seq = message.getSeq();
        String content = new String(message.getData());
        if (callback == null) {
            logger.warn(
                    " register event filter response cannot find callback, seq: {}, content: {}",
                    seq,
                    content);
            return;
        }

        seq2Callback.remove(seq);

        ChannelResponse response = new ChannelResponse();

        response.setCtx(ctx);
        response.setErrorCode(message.getResult());
        response.setMessageID(message.getSeq());
        if (message.getData() != null) {
            response.setContent(message.getData());
        }

        callback.onResponse(response);

        logger.info(" register event filter response, seq: {}, content: {} ", seq, content);
    }
 
Example #13
Source File: FiscoBcos2.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public CompletableFuture<SendResult> sendAMOP(String topicName, String content) {
    ChannelRequest channelRequest = new ChannelRequest();
    channelRequest.setToTopic(topicName);
    channelRequest.setMessageID(this.service.newSeq());
    channelRequest.setTimeout(this.service.getConnectSeconds() * 1000);
    channelRequest.setContent(content);

    log.info("send amop request, topic: {} content length: {} id: {}", topicName, content.length(), channelRequest.getMessageID());

    StopWatch sw = StopWatch.createStarted();
    CompletableFuture<SendResult> future = new CompletableFuture<>();
    this.service.asyncSendChannelMessage2(channelRequest, new ChannelResponseCallback2() {
        @Override
        public void onResponseMessage(ChannelResponse response) {
            sw.stop();
            log.info("receive amop response, id: {} result: {}-{} cost: {}", response.getMessageID(), response.getErrorCode(), response.getErrorMessage(), sw.getTime());

            SendResult sendResult = new SendResult();
            sendResult.setTopic(topicName);
            sendResult.setEventId(response.getMessageID());

            if (response.getErrorCode() == 0) {
                sendResult.setStatus(SendResult.SendResultStatus.SUCCESS);
            } else {
                sendResult.setStatus(SendResult.SendResultStatus.ERROR);
            }
            future.complete(sendResult);
        }
    });
    return future;
}
 
Example #14
Source File: AMOPChannel.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static ChannelResponse toChannelResponse(ErrorCode errorCode, byte[] content) {
    ChannelResponse reply = new ChannelResponse();
    reply.setErrorCode(errorCode.getCode());
    reply.setErrorMessage(errorCode.getCodeDesc());
    reply.setContent(content);
    return reply;
}
 
Example #15
Source File: AMOPChannel.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public boolean isFileExist(FileChunksMeta fileChunksMeta) throws BrokerException {
    log.info("send AMOP message to Check file existence");
    FileEvent fileEvent = new FileEvent(FileEvent.EventType.FileChannelExist, fileChunksMeta.getFileId());
    fileEvent.setFileChunksMeta(fileChunksMeta);
    ChannelResponse rsp = this.sendEvent(fileChunksMeta.getTopic(), fileEvent);
    if (rsp.getErrorCode() == ErrorCode.SUCCESS.getCode()) {
        log.info("Check file existence success");
        return JsonHelper.json2Object(rsp.getContentByteArray(), Boolean.class);
    }

    log.error("Check file existence failed");
    throw toBrokerException(rsp);
}
 
Example #16
Source File: AMOPChannel.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public FileChunksMeta getReceiverFileContext(String topic, String fileId) throws BrokerException {
    log.info("send AMOP message to get receiver file context");
    ChannelResponse rsp = this.sendEvent(topic, new FileEvent(FileEvent.EventType.FileChannelStatus, fileId));
    if (rsp.getErrorCode() == ErrorCode.SUCCESS.getCode()) {
        log.info("receive file context is ready, go");
        return JsonHelper.json2Object(rsp.getContentByteArray(), FileChunksMeta.class);
    }

    log.error("receive file context is not exist");
    throw toBrokerException(rsp);
}
 
Example #17
Source File: AMOPChannel.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public FileChunksMeta cleanUpReceiverFileContext(String topic, String fileId) throws BrokerException {
    log.info("send AMOP message to clean up receiver file context");

    FileEvent fileEvent = new FileEvent(FileEvent.EventType.FileChannelEnd, fileId);
    ChannelResponse rsp = this.sendEvent(topic, fileEvent);
    if (rsp.getErrorCode() == ErrorCode.SUCCESS.getCode()) {
        log.info("clean up receiver file context success");
        return JsonHelper.json2Object(rsp.getContentByteArray(), FileChunksMeta.class);
    } else {
        log.error("clean up remote file context failed");
        throw toBrokerException(rsp);
    }
}
 
Example #18
Source File: AMOPChannel.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static BrokerException toBrokerException(ChannelResponse reply) {
    if (reply.getErrorCode() < 100000) {
        return new BrokerException(reply.getErrorCode(), reply.getErrorMessage());
    } else {
        return new BrokerException(reply.getErrorCode(), ErrorCode.getDescByCode(reply.getErrorCode()));
    }

}
 
Example #19
Source File: AMOPSubscription.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static ChannelResponse toChannelResponse(ErrorCode errorCode, byte[] content) {
    ChannelResponse reply = new ChannelResponse();
    reply.setErrorCode(errorCode.getCode());
    reply.setErrorMessage(errorCode.getCodeDesc());
    reply.setContent(content);
    return reply;
}
 
Example #20
Source File: Service.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public void checkSignForAmop(
        String topic,
        String randValue,
        String nodeid,
        ChannelHandlerContext ctx,
        ChannelResponse response)
        throws IOException {

    if (response.getErrorCode() != 0) {
        logger.error(
                "get signature failed :{}:{}",
                response.getErrorCode(),
                response.getErrorMessage());
        return;
    }
    logger.info(
            "check signature:{} length:{}",
            Arrays.toString(response.getContentByteArray()),
            response.getContentByteArray().length);
    String content =
            topicVerify.parseDataFromPush(
                    response.getContentByteArray().length, response.getContentByteArray());
    logger.info("content:{} content:{}", content, Arrays.toString(content.getBytes()));
    TopicVerifyRespProtocol topicVerifyRespProtocol =
            ObjectMapperFactory.getObjectMapper()
                    .readValue(content, TopicVerifyRespProtocol.class);
    String signature = topicVerifyRespProtocol.getSignature();
    logger.info("signature:{} ", signature);
    int checkResult = topicVerify.checkSignatureValidate(topic, signature, randValue);

    SdkRequestNodeUpdateTopicStatus sdkRequestNodeUpdateTopicStatus =
            new SdkRequestNodeUpdateTopicStatus();
    sdkRequestNodeUpdateTopicStatus.setCheckResult(checkResult);
    sdkRequestNodeUpdateTopicStatus.setNodeId(nodeid);
    sdkRequestNodeUpdateTopicStatus.setTopic(topic);
    String jsonStr =
            ObjectMapperFactory.getObjectMapper()
                    .writeValueAsString(sdkRequestNodeUpdateTopicStatus);
    logger.info("check signature result:{}", jsonStr);
    ChannelRequest request = new ChannelRequest();
    request.setMessageID(newSeq());
    request.setToTopic(topic);
    request.setTimeout(5000);
    request.setContent(jsonStr.getBytes());
    sendCheckResultToNode(
            request, ctx, (short) ChannelMessageType.UPDATE_TOPIICSTATUS.getType());
}
 
Example #21
Source File: Channel2Client.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length < parameterNum) {
        System.out.println("param: target topic total number of request");
        return;
    }
    String topic = args[0];
    Integer count = Integer.parseInt(args[1]);

    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("===================================================================");

    ChannelRequest request = new ChannelRequest();
    for (Integer i = 0; i < count; ++i) {
        Thread.sleep(2000);
        request.setToTopic(topic);
        request.setMessageID(service.newSeq());
        request.setTimeout(5000);

        String content = "request seq:" + request.getMessageID();

        request.setContent(content.getBytes());

        System.out.println(
                df.format(LocalDateTime.now())
                        + " request seq:"
                        + request.getMessageID()
                        + ", Content:"
                        + request.getContent()
                        + " content:"
                        + Arrays.toString(request.getContentByteArray()));

        ChannelResponse response = service.sendChannelMessage2(request);

        System.out.println(
                df.format(LocalDateTime.now())
                        + "response seq:"
                        + response.getMessageID()
                        + ", ErrorCode:"
                        + response.getErrorCode()
                        + ", Content:"
                        + response.getContent());
    }
}
 
Example #22
Source File: Channel2ClientBin.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
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 = 1;

    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.sendChannelMessage2(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());
        }
    }
}
 
Example #23
Source File: AMOPSubscription.java    From WeEvent with Apache License 2.0 4 votes vote down vote up
private static ChannelResponse toChannelResponse(ErrorCode errorCode) {
    return toChannelResponse(errorCode, "".getBytes());
}
 
Example #24
Source File: Channel2ClientNeedVerify.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length < parameterNum) {
        System.out.println("param: target topic total number of request");
        return;
    }
    String topic = args[0];
    Integer count = Integer.parseInt(args[1]);

    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("===================================================================");

    ChannelRequest request = new ChannelRequest();
    for (Integer i = 0; i < count; ++i) {
        Thread.sleep(2000);

        request.setToTopic(topic);
        request.setMessageID(service.newSeq());
        request.setTimeout(5000);

        String content = "request seq:" + request.getMessageID();

        request.setContent(content.getBytes());

        System.out.println(
                df.format(LocalDateTime.now())
                        + " request seq:"
                        + request.getMessageID()
                        + ", Content:"
                        + request.getContent()
                        + " content:"
                        + Arrays.toString(request.getContentByteArray()));

        ChannelResponse response = service.sendChannelMessageForVerifyTopic(request);

        System.out.println(
                df.format(LocalDateTime.now())
                        + "response seq:"
                        + response.getMessageID()
                        + ", ErrorCode:"
                        + response.getErrorCode()
                        + ", Content:"
                        + response.getContent());
    }
}
 
Example #25
Source File: Channel2ClientBinNeedVerify.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
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());
        }
    }
}
 
Example #26
Source File: ChannelResponseCallback2.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public void retrySendMessage() {
    Integer errorCode = 0;
    try {
        // 选取客户端节点
        logger.debug("Number of local nodes:{}", fromConnectionInfos.size());

        setFromConnection(null);
        if (fromConnectionInfos.size() > 0) {
            Random random = new SecureRandom();
            Integer index = random.nextInt(fromConnectionInfos.size());

            logger.debug("selected index: {}, peer: {}", index, fromConnectionInfos.get(index));

            setFromConnection(fromConnectionInfos.get(index));

            fromConnectionInfos.remove(fromConnectionInfos.get(index));
        }

        if (getFromConnection() == null) {
            // 所有节点已尝试,无法再重试了
            logger.error("Failed to send message,all retry failed");

            errorCode = ChannelMessageError.NODES_UNREACHABLE.getError();
            throw new Exception(" Failed to send message,all retry failed ");
        }

        ChannelHandlerContext ctx =
                fromChannelConnections.getNetworkConnectionByHost(
                        getFromConnection().getHost(), getFromConnection().getPort());

        if (ctx != null && ChannelHandlerContextHelper.isChannelAvailable(ctx)) {
            ByteBuf out = ctx.alloc().buffer();
            message.writeHeader(out);
            message.writeExtra(out);

            ctx.writeAndFlush(out);

            logger.debug(
                    "send message to  {}:{} success ",
                    fromConnection.getHost(),
                    fromConnection.getPort());
        } else {
            logger.debug("sending node unavailable");

            retrySendMessage();
        }
    } catch (Exception e) {
        logger.error("send message exception {}", e);

        ChannelResponse response = new ChannelResponse();
        response.setErrorCode(errorCode);
        response.setErrorMessage(e.getMessage());

        try {
            onResponseMessage(response);
        } catch (Exception ee) {
            logger.error("onResponseMessage error:{}", ee);
        }

        // 彻底失败后,删掉这个seq
        if (message.getSeq() != null) {
            service.getSeq2Callback().remove(message.getSeq());
        }

        if (timeout != null) {
            timeout.cancel();
        }

        return;
    }
}
 
Example #27
Source File: AMOPSubscription.java    From WeEvent with Apache License 2.0 4 votes vote down vote up
private static ChannelResponse toChannelResponse(BrokerException e) {
    ChannelResponse reply = new ChannelResponse();
    reply.setErrorCode(e.getCode());
    reply.setContent(e.getMessage());
    return reply;
}
 
Example #28
Source File: Service.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public void checkTopicVerify(ChannelHandlerContext ctx, TopicVerifyMessage message)
        throws IOException {
    SocketChannel socketChannel = (SocketChannel) ctx.channel();

    logger.info(
            "get rand value request ChannelResponse seq:{} msgtype:{} address:{} port:{}",
            message.getSeq(),
            message.getType(),
            socketChannel.remoteAddress().getAddress().getHostAddress(),
            socketChannel.remoteAddress().getPort());
    logger.info(
            "get rand value request :{} length:{}",
            Arrays.toString(message.getData()),
            message.getLength());

    sendResponse2Node(ctx, message);

    String content = new String(message.getData());
    logger.info("content:{} content:{}", content, Arrays.toString(content.getBytes()));

    NodeRequestSdkVerifyTopic nodeRequestSdkVerifyTopic =
            ObjectMapperFactory.getObjectMapper()
                    .readValue(content, NodeRequestSdkVerifyTopic.class);
    String topic = nodeRequestSdkVerifyTopic.getTopic();
    String topicForCert = nodeRequestSdkVerifyTopic.getTopicForCert();
    String nodeid = nodeRequestSdkVerifyTopic.getNodeId();
    logger.info("topic:{} topicForCert:{} nodeid:{}", topic, topicForCert, nodeid);

    ChannelRequest request = new ChannelRequest();
    request.setToTopic(topicForCert);
    request.setMessageID(newSeq());
    request.setTimeout(5000);
    request.setType((short) ChannelMessageType.AMOP_REQUEST.getType());

    String randValue = UUID.randomUUID().toString().replaceAll("-", "");
    TopicVerifyReqProtocol topicVerifyProtocol = new TopicVerifyReqProtocol();
    topicVerifyProtocol.setRandValue(randValue);
    topicVerifyProtocol.setTopic(topic);
    String jsonStr =
            ObjectMapperFactory.getObjectMapper().writeValueAsString(topicVerifyProtocol);
    logger.info(
            "generate rand value jsonStr:{} topic:{} messageid:{}",
            jsonStr,
            request.getToTopic(),
            message.getSeq());
    byte[] bytes = topicVerify.getByteBuffByString(request.getToTopic(), jsonStr);
    request.setContent(bytes);
    asyncSendChannelMessage2(
            request,
            new ChannelResponseCallback2() {
                @Override
                public void onResponseMessage(ChannelResponse response) {
                    logger.info("get response messageid:{}", response.getMessageID());
                    try {
                        checkSignForAmop(
                                topic, String.valueOf(randValue), nodeid, ctx, response);
                    } catch (IOException e) {
                        logger.error("check sign for amop failed:{}", e);
                    }
                }
            });
}
 
Example #29
Source File: Service.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
/** @param filter */
public void asyncSendRegisterEventLogFilterMessage(EventLogFilter filter) {

    ChannelRequest request = new ChannelRequest();
    request.setMessageID(newSeq());
    request.setToTopic("");
    request.setType((short) ChannelMessageType.CLIENT_REGISTER_EVENT_LOG.getType());

    EventLogRequestParams params =
            new EventLogRequestParams(
                    filter.generateNewParams(), String.valueOf(getGroupId()), newSeq());

    logger.info(
            " registerID: {}, filterID: {}, params: {}",
            filter.getRegisterID(),
            filter.getFilterID(),
            params);

    try {
        request.setContent(params.toJsonString());
    } catch (JsonProcessingException e1) {
        filter.getCallback()
                .onPushEventLog(EventLogFilterPushStatus.INVALID_PARAMS.getStatus(), null);
        eventLogFilterManager.removeFilter(filter.getRegisterID());
        return;
    }

    final String filterID = params.getFilterID();
    final String registerID = filter.getRegisterID();

    filter.setFilterID(filterID);
    final EventLogPushCallback callback0 = filter.getCallback();

    // register callback
    eventLogFilterManager.addCallback(params.getFilterID(), filter.getCallback());
    asyncSendChannelMessage2(
            request,
            new ChannelResponseCallback2() {
                @Override
                public void onResponseMessage(ChannelResponse response) {
                    logger.info(
                            " event filter callback response, registerID: {}, filterID: {}, seq: {}, error code: {},  content: {}",
                            registerID,
                            filterID,
                            response.getMessageID(),
                            response.getErrorCode(),
                            response.getContent());
                    try {
                        if (0 == response.getErrorCode()) {
                            // receive response successfully
                            EventLogFilterPushResponse resp =
                                    ObjectMapperFactory.getObjectMapper()
                                            .readValue(
                                                    response.getContent(),
                                                    EventLogFilterPushResponse.class);

                            if (resp.getResult() == 0) {
                                // node response ok, event log will be pushed soon
                                eventLogFilterManager.updateEventLogFilter(
                                        callback0.getFilter(),
                                        EventLogFilterStatus.EVENT_LOG_PUSHING,
                                        response.getCtx());
                            } else { // node response not ok, callback to client
                                callback0.onPushEventLog(resp.getResult(), null);
                                eventLogFilterManager.removeFilterAndCallback(
                                        registerID, filterID);
                            }
                        } else { // register request send failed, waiting to be re-sent
                            eventLogFilterManager.updateEventLogFilter(
                                    callback0.getFilter(),
                                    EventLogFilterStatus.WAITING_REQUEST,
                                    null);
                            // remove register callback
                            eventLogFilterManager.removeCallback(filterID);
                        }
                    } catch (Exception e) {
                        callback0.onPushEventLog(
                                EventLogFilterPushStatus.OTHER_ERROR.getStatus(), null);
                        eventLogFilterManager.removeFilterAndCallback(
                                filter.getRegisterID(), filterID);

                        logger.error(
                                " event filter response message exception, filterID: {}, registerID: {}, exception message: {}",
                                filterID,
                                registerID,
                                e.getMessage());
                    }
                }
            });
}
 
Example #30
Source File: Service.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public ChannelResponse sendChannelMessageForVerifyTopic(ChannelRequest request) {
    String toTopic = request.getToTopic();
    request.setToTopic(getNeedVerifyTopics(toTopic));
    return sendChannelMessage2(request);
}