Example usage for io.netty.channel ChannelFuture cause

List of usage examples for io.netty.channel ChannelFuture cause

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture cause.

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

From source file:com.alibaba.dubbo.remoting.transport.netty.NettyClient.java

License:Apache License

protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try {//w  w w  .j a v  a2 s  .co m
        boolean ret = future.awaitUninterruptibly(3000, TimeUnit.MILLISECONDS);

        if (ret && future.isSuccess()) {
            Channel newChannel = future.channel();
            try {
                // 
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel
                                    + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info(
                                    "Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.cause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.cause().getMessage(), future.cause());
        } else {
            throw new RemotingException(this,
                    "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress()
                            + " client-side timeout " + getConnectTimeout() + "ms (elapsed: "
                            + (System.currentTimeMillis() - start) + "ms) from netty client "
                            + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    } finally {
        if (!isConnected()) {
            //future.cancel(true);
        }
    }
}

From source file:com.alibaba.dubbo.remoting.transport.netty4.NettyChannel.java

License:Apache License

public void send(Object message, boolean sent) throws RemotingException {
    super.send(message, sent);

    boolean success = true;
    int timeout = 0;
    try {/*w ww  . j av a  2 s  .  c o m*/
        ChannelFuture future = channel.writeAndFlush(message);
        if (sent) {
            timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
            success = future.await(timeout);
        }
        Throwable cause = future.cause();
        if (cause != null) {
            throw cause;
        }
    } catch (Throwable e) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
                + ", cause: " + e.getMessage(), e);
    }

    if (!success) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
                + "in timeout(" + timeout + "ms) limit");
    }
}

From source file:com.alibaba.rocketmq.broker.client.net.Broker2Client.java

License:Apache License

/**
 * BrokerProducer?Oneway//from  www  .  j  ava 2  s  . c  o m
 */
public void checkProducerTransactionState(//
        final Channel channel, //
        final CheckTransactionStateRequestHeader requestHeader, //
        final SelectMapedBufferResult selectMapedBufferResult//
) {
    RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHECK_TRANSACTION_STATE,
            requestHeader);
    request.markOnewayRPC();

    try {
        FileRegion fileRegion = new OneMessageTransfer(request.encodeHeader(selectMapedBufferResult.getSize()),
                selectMapedBufferResult);
        channel.writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                selectMapedBufferResult.release();
                if (!future.isSuccess()) {
                    log.error("invokeProducer failed,", future.cause());
                }
            }
        });
    } catch (Throwable e) {
        log.error("invokeProducer exception", e);
        selectMapedBufferResult.release();
    }
}

From source file:com.alibaba.rocketmq.broker.processor.PullMessageProcessor.java

License:Apache License

public void excuteRequestWhenWakeup(final Channel channel, final RemotingCommand request)
        throws RemotingCommandException {
    Runnable run = new Runnable() {
        @Override//from   ww w  . j  a v  a  2 s.c  om
        public void run() {
            try {
                final RemotingCommand response = PullMessageProcessor.this.processRequest(channel, request,
                        false);

                if (response != null) {
                    response.setOpaque(request.getOpaque());
                    response.markResponseType();
                    try {
                        channel.writeAndFlush(response).addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (!future.isSuccess()) {
                                    log.error(
                                            "processRequestWrapper response to "
                                                    + future.channel().remoteAddress() + " failed",
                                            future.cause());
                                    log.error(request.toString());
                                    log.error(response.toString());
                                }
                            }
                        });
                    } catch (Throwable e) {
                        log.error("processRequestWrapper process request over, but response failed", e);
                        log.error(request.toString());
                        log.error(response.toString());
                    }
                }
            } catch (RemotingCommandException e1) {
                log.error("excuteRequestWhenWakeup run", e1);
            }
        }
    };

    this.brokerController.getPullMessageExecutor().submit(run);
}

From source file:com.alibaba.rocketmq.broker.processor.PullMessageProcessor.java

License:Apache License

private RemotingCommand processRequest(final Channel channel, RemotingCommand request,
        boolean brokerAllowSuspend) throws RemotingCommandException {
    RemotingCommand response = RemotingCommand.createResponseCommand(PullMessageResponseHeader.class);
    final PullMessageResponseHeader responseHeader = (PullMessageResponseHeader) response.readCustomHeader();
    final PullMessageRequestHeader requestHeader = (PullMessageRequestHeader) request
            .decodeCommandCustomHeader(PullMessageRequestHeader.class);

    // sendfile?/* w  w w  . java2 s  . c  o  m*/
    response.setOpaque(request.getOpaque());
    if (log.isDebugEnabled()) {
        log.debug("receive PullMessage request command, " + request);
    }

    // Broker??
    if (!PermName.isReadable(this.brokerController.getBrokerConfig().getBrokerPermission())) {
        response.setCode(ResponseCode.NO_PERMISSION);
        response.setRemark("the broker[" + this.brokerController.getBrokerConfig().getBrokerIP1()
                + "] pulling message is forbidden");
        return response;
    }

    // ?
    SubscriptionGroupConfig subscriptionGroupConfig = this.brokerController.getSubscriptionGroupManager()
            .findSubscriptionGroupConfig(requestHeader.getConsumerGroup());
    if (null == subscriptionGroupConfig) {
        response.setCode(ResponseCode.SUBSCRIPTION_GROUP_NOT_EXIST);
        response.setRemark("subscription group not exist, " + requestHeader.getConsumerGroup() + " "
                + FAQUrl.suggestTodo(FAQUrl.SUBSCRIPTION_GROUP_NOT_EXIST));
        return response;
    }

    // ???
    if (!subscriptionGroupConfig.isConsumeEnable()) {
        response.setCode(ResponseCode.NO_PERMISSION);
        response.setRemark("subscription group no permission, " + requestHeader.getConsumerGroup());
        return response;
    }

    final boolean hasSuspendFlag = PullSysFlag.hasSuspendFlag(requestHeader.getSysFlag());
    final boolean hasCommitOffsetFlag = PullSysFlag.hasCommitOffsetFlag(requestHeader.getSysFlag());
    final boolean hasSubscriptionFlag = PullSysFlag.hasSubscriptionFlag(requestHeader.getSysFlag());

    final long suspendTimeoutMillisLong = hasSuspendFlag ? requestHeader.getSuspendTimeoutMillis() : 0;

    // topic?
    TopicConfig topicConfig = this.brokerController.getTopicConfigManager()
            .selectTopicConfig(requestHeader.getTopic());
    if (null == topicConfig) {
        log.error("the topic " + requestHeader.getTopic() + " not exist, consumer: "
                + RemotingHelper.parseChannelRemoteAddr(channel));
        response.setCode(ResponseCode.TOPIC_NOT_EXIST);
        response.setRemark("topic[" + requestHeader.getTopic() + "] not exist, apply first please!"
                + FAQUrl.suggestTodo(FAQUrl.APPLY_TOPIC_URL));
        return response;
    }

    // topic??
    if (!PermName.isReadable(topicConfig.getPerm())) {
        response.setCode(ResponseCode.NO_PERMISSION);
        response.setRemark("the topic[" + requestHeader.getTopic() + "] pulling message is forbidden");
        return response;
    }

    // 
    if (requestHeader.getQueueId() < 0 || requestHeader.getQueueId() >= topicConfig.getReadQueueNums()) {
        String errorInfo = "queueId[" + requestHeader.getQueueId() + "] is illagal,Topic :"
                + requestHeader.getTopic() + " topicConfig.readQueueNums: " + topicConfig.getReadQueueNums()
                + " consumer: " + channel.remoteAddress();
        log.warn(errorInfo);
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark(errorInfo);
        return response;
    }

    // ?
    SubscriptionData subscriptionData = null;
    if (hasSubscriptionFlag) {
        try {
            subscriptionData = FilterAPI.buildSubscriptionData(requestHeader.getConsumerGroup(),
                    requestHeader.getTopic(), requestHeader.getSubscription());
        } catch (Exception e) {
            log.warn("parse the consumer's subscription[{}] failed, group: {}", requestHeader.getSubscription(), //
                    requestHeader.getConsumerGroup());
            response.setCode(ResponseCode.SUBSCRIPTION_PARSE_FAILED);
            response.setRemark("parse the consumer's subscription failed");
            return response;
        }
    } else {
        ConsumerGroupInfo consumerGroupInfo = this.brokerController.getConsumerManager()
                .getConsumerGroupInfo(requestHeader.getConsumerGroup());
        if (null == consumerGroupInfo) {
            log.warn("the consumer's group info not exist, group: {}", requestHeader.getConsumerGroup());
            response.setCode(ResponseCode.SUBSCRIPTION_NOT_EXIST);
            response.setRemark("the consumer's group info not exist"
                    + FAQUrl.suggestTodo(FAQUrl.SAME_GROUP_DIFFERENT_TOPIC));
            return response;
        }

        if (!subscriptionGroupConfig.isConsumeBroadcastEnable() //
                && consumerGroupInfo.getMessageModel() == MessageModel.BROADCASTING) {
            response.setCode(ResponseCode.NO_PERMISSION);
            response.setRemark("the consumer group[" + requestHeader.getConsumerGroup()
                    + "] can not consume by broadcast way");
            return response;
        }

        subscriptionData = consumerGroupInfo.findSubscriptionData(requestHeader.getTopic());
        if (null == subscriptionData) {
            log.warn("the consumer's subscription not exist, group: {}", requestHeader.getConsumerGroup());
            response.setCode(ResponseCode.SUBSCRIPTION_NOT_EXIST);
            response.setRemark("the consumer's subscription not exist"
                    + FAQUrl.suggestTodo(FAQUrl.SAME_GROUP_DIFFERENT_TOPIC));
            return response;
        }

        // Broker?
        if (subscriptionData.getSubVersion() < requestHeader.getSubVersion()) {
            log.warn("the broker's subscription is not latest, group: {} {}", requestHeader.getConsumerGroup(),
                    subscriptionData.getSubString());
            response.setCode(ResponseCode.SUBSCRIPTION_NOT_LATEST);
            response.setRemark("the consumer's subscription not latest");
            return response;
        }
    }

    final GetMessageResult getMessageResult = this.brokerController.getMessageStore().getMessage(
            requestHeader.getConsumerGroup(), requestHeader.getTopic(), requestHeader.getQueueId(),
            requestHeader.getQueueOffset(), requestHeader.getMaxMsgNums(), subscriptionData);
    if (getMessageResult != null) {
        response.setRemark(getMessageResult.getStatus().name());
        responseHeader.setNextBeginOffset(getMessageResult.getNextBeginOffset());
        responseHeader.setMinOffset(getMessageResult.getMinOffset());
        responseHeader.setMaxOffset(getMessageResult.getMaxOffset());

        // ????
        if (getMessageResult.isSuggestPullingFromSlave()) {
            responseHeader.setSuggestWhichBrokerId(subscriptionGroupConfig.getWhichBrokerWhenConsumeSlowly());
        }
        // ???
        else {
            //responseHeader.setSuggestWhichBrokerId(subscriptionGroupConfig.getWhichBrokerWhenConsumeSlowly());
            responseHeader.setSuggestWhichBrokerId(subscriptionGroupConfig.getBrokerId());
        }

        switch (getMessageResult.getStatus()) {
        case FOUND:
            response.setCode(ResponseCode.SUCCESS);

            // ?????
            if (this.hasConsumeMessageHook()) {
                // hook
                ConsumeMessageContext context = new ConsumeMessageContext();
                context.setConsumerGroup(requestHeader.getConsumerGroup());
                context.setTopic(requestHeader.getTopic());
                context.setClientHost(RemotingHelper.parseChannelRemoteAddr(channel));
                context.setStoreHost(this.brokerController.getBrokerAddr());
                context.setQueueId(requestHeader.getQueueId());

                final SocketAddress storeHost = new InetSocketAddress(
                        brokerController.getBrokerConfig().getBrokerIP1(),
                        brokerController.getNettyServerConfig().getListenPort());
                Map<String, Long> messageIds = this.brokerController.getMessageStore().getMessageIds(
                        requestHeader.getTopic(), requestHeader.getQueueId(), requestHeader.getQueueOffset(),
                        requestHeader.getQueueOffset() + getMessageResult.getMessageCount(), storeHost);
                context.setMessageIds(messageIds);
                context.setBodyLength(
                        getMessageResult.getBufferTotalSize() / getMessageResult.getMessageCount());
                this.executeConsumeMessageHookBefore(context);
            }

            break;
        case MESSAGE_WAS_REMOVING:
            response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY);
            break;
        // ?Offset?0
        case NO_MATCHED_LOGIC_QUEUE:
        case NO_MESSAGE_IN_QUEUE:
            if (0 != requestHeader.getQueueOffset()) {
                response.setCode(ResponseCode.PULL_OFFSET_MOVED);

                // XXX: warn and notify me
                log.info(
                        "the broker store no queue data, fix the request offset {} to {}, Topic: {} QueueId: {} Consumer Group: {}", //
                        requestHeader.getQueueOffset(), //
                        getMessageResult.getNextBeginOffset(), //
                        requestHeader.getTopic(), //
                        requestHeader.getQueueId(), //
                        requestHeader.getConsumerGroup()//
                );
            } else {
                response.setCode(ResponseCode.PULL_NOT_FOUND);
            }
            break;
        case NO_MATCHED_MESSAGE:
            response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY);
            break;
        case OFFSET_FOUND_NULL:
            response.setCode(ResponseCode.PULL_NOT_FOUND);
            break;
        case OFFSET_OVERFLOW_BADLY:
            response.setCode(ResponseCode.PULL_OFFSET_MOVED);
            // XXX: warn and notify me
            log.info("the request offset: " + requestHeader.getQueueOffset()
                    + " over flow badly, broker max offset: " + getMessageResult.getMaxOffset() + ", consumer: "
                    + channel.remoteAddress());
            break;
        case OFFSET_OVERFLOW_ONE:
            response.setCode(ResponseCode.PULL_NOT_FOUND);
            break;
        case OFFSET_TOO_SMALL:
            response.setCode(ResponseCode.PULL_OFFSET_MOVED);
            // XXX: warn and notify me
            log.info("the request offset: " + requestHeader.getQueueOffset() + " too small, broker min offset: "
                    + getMessageResult.getMinOffset() + ", consumer: " + channel.remoteAddress());
            break;
        default:
            assert false;
            break;
        }

        switch (response.getCode()) {
        case ResponseCode.SUCCESS:
            // 
            this.brokerController.getBrokerStatsManager().incGroupGetNums(requestHeader.getConsumerGroup(),
                    requestHeader.getTopic(), getMessageResult.getMessageCount());

            this.brokerController.getBrokerStatsManager().incGroupGetSize(requestHeader.getConsumerGroup(),
                    requestHeader.getTopic(), getMessageResult.getBufferTotalSize());

            this.brokerController.getBrokerStatsManager().incBrokerGetNums(getMessageResult.getMessageCount());

            try {
                FileRegion fileRegion = new ManyMessageTransfer(
                        response.encodeHeader(getMessageResult.getBufferTotalSize()), getMessageResult);
                channel.writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        getMessageResult.release();
                        if (!future.isSuccess()) {
                            log.error("transfer many message by pagecache failed, " + channel.remoteAddress(),
                                    future.cause());
                        }
                    }
                });
            } catch (Throwable e) {
                log.error("", e);
                getMessageResult.release();
            }

            response = null;
            break;
        case ResponseCode.PULL_NOT_FOUND:
            // 
            if (brokerAllowSuspend && hasSuspendFlag) {
                long pollingTimeMills = suspendTimeoutMillisLong;
                if (!this.brokerController.getBrokerConfig().isLongPollingEnable()) {
                    pollingTimeMills = this.brokerController.getBrokerConfig().getShortPollingTimeMills();
                }

                PullRequest pullRequest = new PullRequest(request, channel, pollingTimeMills,
                        this.brokerController.getMessageStore().now(), requestHeader.getQueueOffset());
                this.brokerController.getPullRequestHoldService().suspendPullRequest(requestHeader.getTopic(),
                        requestHeader.getQueueId(), pullRequest);
                response = null;
                break;
            }

            // ?Consumer
        case ResponseCode.PULL_RETRY_IMMEDIATELY:
            break;
        case ResponseCode.PULL_OFFSET_MOVED:
            if (this.brokerController.getMessageStoreConfig().getBrokerRole() != BrokerRole.SLAVE
                    || this.brokerController.getBrokerConfig().isOffsetCheckInSlave()) {
                MessageQueue mq = new MessageQueue();
                mq.setTopic(requestHeader.getTopic());
                mq.setQueueId(requestHeader.getQueueId());
                mq.setBrokerName(this.brokerController.getBrokerConfig().getBrokerName());

                OffsetMovedEvent event = new OffsetMovedEvent();
                event.setConsumerGroup(requestHeader.getConsumerGroup());
                event.setMessageQueue(mq);
                event.setOffsetRequest(requestHeader.getQueueOffset());
                event.setOffsetNew(getMessageResult.getNextBeginOffset());
                this.generateOffsetMovedEvent(event);
            } else {
                responseHeader.setSuggestWhichBrokerId(subscriptionGroupConfig.getBrokerId());
                response.setCode(ResponseCode.PULL_RETRY_IMMEDIATELY);
            }

            log.warn("PULL_OFFSET_MOVED:topic={}, groupId={}, clientId={}, offset={}, suggestBrokerId={}",
                    requestHeader.getTopic(), requestHeader.getConsumerGroup(), requestHeader.getQueueOffset(),
                    responseHeader.getSuggestWhichBrokerId());
            break;
        default:
            assert false;
        }
    } else {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("store getMessage return null");
    }

    // Consumer
    boolean storeOffsetEnable = brokerAllowSuspend; // 
    storeOffsetEnable = storeOffsetEnable && hasCommitOffsetFlag; // Consumer?
    storeOffsetEnable = storeOffsetEnable // ?Master?offset
            && this.brokerController.getMessageStoreConfig().getBrokerRole() != BrokerRole.SLAVE;
    if (storeOffsetEnable) {
        this.brokerController.getConsumerOffsetManager().commitOffset(requestHeader.getConsumerGroup(),
                requestHeader.getTopic(), requestHeader.getQueueId(), requestHeader.getCommitOffset());
    }

    return response;
}

From source file:com.alibaba.rocketmq.broker.processor.QueryMessageProcessor.java

License:Apache License

public RemotingCommand queryMessage(ChannelHandlerContext ctx, RemotingCommand request)
        throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(QueryMessageResponseHeader.class);
    final QueryMessageResponseHeader responseHeader = (QueryMessageResponseHeader) response.readCustomHeader();
    final QueryMessageRequestHeader requestHeader = (QueryMessageRequestHeader) request
            .decodeCommandCustomHeader(QueryMessageRequestHeader.class);

    // sendfile?//from w  w  w.ja  v a2 s .  c o m
    response.setOpaque(request.getOpaque());

    final QueryMessageResult queryMessageResult = this.brokerController.getMessageStore().queryMessage(
            requestHeader.getTopic(), requestHeader.getKey(), requestHeader.getMaxNum(),
            requestHeader.getBeginTimestamp(), requestHeader.getEndTimestamp());
    assert queryMessageResult != null;

    responseHeader.setIndexLastUpdatePhyoffset(queryMessageResult.getIndexLastUpdatePhyoffset());
    responseHeader.setIndexLastUpdateTimestamp(queryMessageResult.getIndexLastUpdateTimestamp());

    // ?
    if (queryMessageResult.getBufferTotalSize() > 0) {
        response.setCode(ResponseCode.SUCCESS);
        response.setRemark(null);

        try {
            FileRegion fileRegion = new QueryMessageTransfer(
                    response.encodeHeader(queryMessageResult.getBufferTotalSize()), queryMessageResult);
            ctx.channel().writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    queryMessageResult.release();
                    if (!future.isSuccess()) {
                        log.error("transfer query message by pagecache failed, ", future.cause());
                    }
                }
            });
        } catch (Throwable e) {
            log.error("", e);
            queryMessageResult.release();
        }

        return null;
    }

    response.setCode(ResponseCode.QUERY_NOT_FOUND);
    response.setRemark("can not find message, maybe time range not correct");
    return response;
}

From source file:com.alibaba.rocketmq.broker.processor.QueryMessageProcessor.java

License:Apache License

public RemotingCommand viewMessageById(ChannelHandlerContext ctx, RemotingCommand request)
        throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final ViewMessageRequestHeader requestHeader = (ViewMessageRequestHeader) request
            .decodeCommandCustomHeader(ViewMessageRequestHeader.class);

    // sendfile?/* w  ww .  j a va2s . com*/
    response.setOpaque(request.getOpaque());

    final SelectMapedBufferResult selectMapedBufferResult = this.brokerController.getMessageStore()
            .selectOneMessageByOffset(requestHeader.getOffset());
    if (selectMapedBufferResult != null) {
        response.setCode(ResponseCode.SUCCESS);
        response.setRemark(null);

        try {
            FileRegion fileRegion = new OneMessageTransfer(
                    response.encodeHeader(selectMapedBufferResult.getSize()), selectMapedBufferResult);
            ctx.channel().writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    selectMapedBufferResult.release();
                    if (!future.isSuccess()) {
                        log.error("transfer one message by pagecache failed, ", future.cause());
                    }
                }
            });
        } catch (Throwable e) {
            log.error("", e);
            selectMapedBufferResult.release();
        }

        return null;
    } else {
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark("can not find message by the offset, " + requestHeader.getOffset());
    }

    return response;
}

From source file:com.alibaba.rocketmq.filtersrv.processor.DefaultRequestProcessor.java

License:Apache License

private void returnResponse(final String group, final String topic, ChannelHandlerContext ctx,
        final RemotingCommand response, final List<MessageExt> msgList) {
    if (null != msgList) {
        ByteBuffer[] msgBufferList = new ByteBuffer[msgList.size()];
        int bodyTotalSize = 0;
        for (int i = 0; i < msgList.size(); i++) {
            try {
                msgBufferList[i] = messageToByteBuffer(msgList.get(i));
                bodyTotalSize += msgBufferList[i].capacity();
            } catch (Exception e) {
                log.error("messageToByteBuffer UnsupportedEncodingException", e);
            }//ww  w  .  j  a  va2  s .c  om
        }

        ByteBuffer body = ByteBuffer.allocate(bodyTotalSize);
        for (ByteBuffer bb : msgBufferList) {
            bb.flip();
            body.put(bb);
        }

        response.setBody(body.array());

        // 
        this.filtersrvController.getFilterServerStatsManager().incGroupGetNums(group, topic, msgList.size());

        this.filtersrvController.getFilterServerStatsManager().incGroupGetSize(group, topic, bodyTotalSize);
    }

    try {
        ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    log.error("FilterServer response to " + future.channel().remoteAddress() + " failed",
                            future.cause());
                    log.error(response.toString());
                }
            }
        });
    } catch (Throwable e) {
        log.error("FilterServer process request over, but response failed", e);
        log.error(response.toString());
    }
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis)
        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    try {// w  w w.  java  2 s.  c om
        final ResponseFuture responseFuture = new ResponseFuture(request.getOpaque(), timeoutMillis, null,
                null);
        this.responseTable.put(request.getOpaque(), responseFuture);
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(request.getOpaque());
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                plog.warn("send a request command to channel <" + channel.remoteAddress() + "> failed.");
                plog.warn(request.toString());
            }
        });

        RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            if (responseFuture.isSendRequestOK()) {
                throw new RemotingTimeoutException(RemotingHelper.parseChannelRemoteAddr(channel),
                        timeoutMillis, responseFuture.getCause());
            } else {
                throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(request.getOpaque());
    }
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingClient.java

License:Apache License

private Channel createChannel(final String addr) throws InterruptedException {
    ChannelWrapper cw = this.channelTables.get(addr);
    if (cw != null && cw.isOK()) {
        return cw.getChannel();
    }//from   ww  w. jav  a 2 s .c  om

    // ????
    if (this.lockChannelTables.tryLock(LockTimeoutMillis, TimeUnit.MILLISECONDS)) {
        try {
            boolean createNewConnection = false;
            cw = this.channelTables.get(addr);
            if (cw != null) {
                // channel
                if (cw.isOK()) {
                    return cw.getChannel();
                }
                // ?
                else if (!cw.getChannelFuture().isDone()) {
                    createNewConnection = false;
                }
                // ??
                else {
                    this.channelTables.remove(addr);
                    createNewConnection = true;
                }
            }
            // ChannelWrapper?
            else {
                createNewConnection = true;
            }

            if (createNewConnection) {
                ChannelFuture channelFuture = this.bootstrap.connect(RemotingHelper.string2SocketAddress(addr));
                log.info("createChannel: begin to connect remote host[{}] asynchronously", addr);
                cw = new ChannelWrapper(channelFuture);
                this.channelTables.put(addr, cw);
            }
        } catch (Exception e) {
            log.error("createChannel: create channel exception", e);
        } finally {
            this.lockChannelTables.unlock();
        }
    } else {
        log.warn("createChannel: try to lock channel table, but timeout, {}ms", LockTimeoutMillis);
    }

    if (cw != null) {
        ChannelFuture channelFuture = cw.getChannelFuture();
        if (channelFuture.awaitUninterruptibly(this.nettyClientConfig.getConnectTimeoutMillis())) {
            if (cw.isOK()) {
                log.info("createChannel: connect remote host[{}] success, {}", addr, channelFuture.toString());
                return cw.getChannel();
            } else {
                if (log.isDebugEnabled())
                    log.debug("createChannel: connect remote host[" + addr + "] failed, "
                            + channelFuture.toString(), channelFuture.cause());
                else
                    log.warn("createChannel: connect remote host[" + addr + "] failed, "
                            + channelFuture.toString());
            }
        } else {
            log.warn("createChannel: connect remote host[{}] timeout {}ms, {}", addr,
                    this.nettyClientConfig.getConnectTimeoutMillis(), channelFuture.toString());
        }
    }

    return null;
}