List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:com.hxr.javatone.concurrency.netty.official.proxy.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); outboundChannel = f.channel();/*ww w .ja v a 2 s . c om*/ f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
From source file:com.ibasco.agql.core.transport.NettyTransport.java
License:Open Source License
/** * <p>A method to send data over the transport. Since the current netty version does not yet support {@link * CompletableFuture}, we need to convert the returned {@link ChannelFuture} to it's {@link CompletableFuture} * version.</p>/*from ww w . j a v a 2 s . c om*/ * * @param channel * The underlying {@link Channel} to be used for data transport. * @param data * An instance of {@link AbstractMessage} that will be sent through the transport * @param flushImmediately * True if transport should immediately flush the message after send. * * @return A {@link CompletableFuture} with return type of {@link Channel} (The channel used for the transport) */ private CompletableFuture<Void> writeToChannel(Channel channel, Msg data, boolean flushImmediately) { final CompletableFuture<Void> writeResultFuture = new CompletableFuture<>(); log.debug("Writing data '{}' to channel : {}", data, channel); final ChannelFuture writeFuture = (flushImmediately) ? channel.writeAndFlush(data) : channel.write(data); writeFuture.addListener((ChannelFuture future) -> { try { if (future.isSuccess()) writeResultFuture.complete(null); else writeResultFuture.completeExceptionally(future.cause()); } finally { cleanupChannel(future.channel()); } }); return writeResultFuture; }
From source file:com.ibasco.agql.core.transport.tcp.NettyBasicTcpTransport.java
License:Open Source License
@Override public CompletableFuture<Channel> getChannel(M address) { final CompletableFuture<Channel> channelFuture = new CompletableFuture<>(); ChannelFuture f = getBootstrap().connect(address.recipient()); //Acquire from pool and listen for completion f.addListener((ChannelFuture future) -> { if (future.isSuccess()) { channelFuture.complete(future.channel()); } else {/*from ww w .ja v a 2 s .com*/ channelFuture.completeExceptionally(future.cause()); } }); return channelFuture; }
From source file:com.ibasco.agql.core.transport.udp.NettyBasicUdpTransport.java
License:Open Source License
@Override public CompletableFuture<Channel> getChannel(M message) { final CompletableFuture<Channel> cf = new CompletableFuture<>(); //lazy initialization if (channel == null || !channel.isOpen()) { bind(0).addListener((ChannelFuture future) -> { if (future.isSuccess()) { channel = (NioDatagramChannel) future.channel(); channel.closeFuture()/*from w ww. j a va2s . c om*/ .addListener((ChannelFuture f) -> log.debug( "CHANNEL CLOSED: {}, Is Open: {}, For Address: {}, Cause: {}", f.channel().id(), f.channel().isOpen(), message.recipient(), f.cause())); cf.complete(channel); } else { channel = null; cf.completeExceptionally(future.cause()); } }); } else { cf.complete(channel); } return cf; }
From source file:com.ict.dtube.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.getCustomHeader(); final PullMessageRequestHeader requestHeader = (PullMessageRequestHeader) request .decodeCommandCustomHeader(PullMessageRequestHeader.class); // sendfile?//from w w w. j a va 2 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.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.getBrokerId()); } switch (getMessageResult.getStatus()) { case FOUND: response.setCode(ResponseCode.SUCCESS); 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) { PullRequest pullRequest = new PullRequest(request, channel, suspendTimeoutMillisLong, 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: 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); 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.ict.dtube.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.getCustomHeader(); final QueryMessageRequestHeader requestHeader = (QueryMessageRequestHeader) request .decodeCommandCustomHeader(QueryMessageRequestHeader.class); // sendfile?/* w w w . j av a 2 s.c om*/ 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.jt.flash.proxy.handler.ProxyFrontendHandler.java
License:Apache License
private void processRequest(final ChannelHandlerContext ctx, final Object msg, final Channel inboundChannel, String host, final int port) { Bootstrap b = buildBackendBootstrap(ctx, inboundChannel, port); ChannelFuture f = b.connect(host, port); outboundChannel = f.channel();//from w w w . jav a2 s .c o m f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { log.info("connect ok, write {}", msg); outboundChannel.writeAndFlush(msg); /* .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { ctx.channel().read(); } else { future.channel().close(); } } });*/ } else { log.warn("connect fail"); inboundChannel.close(); } } }); }
From source file:com.king.platform.net.http.netty.ChannelManager.java
License:Apache License
private void sendOnNewChannel(final HttpRequestContext httpRequestContext, final RequestEventBus requestEventBus) { final ServerInfo serverInfo = httpRequestContext.getServerInfo(); ChannelFuture channelFuture = connect(serverInfo); channelFuture.addListener(new ChannelFutureListener() { @Override// w w w .j a v a2s.c om public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { requestEventBus.triggerEvent(Event.CREATED_CONNECTION, serverInfo); requestEventBus.triggerEvent(Event.onConnected); Channel channel = future.channel(); channel.attr(ServerInfo.ATTRIBUTE_KEY).set(serverInfo); logger.trace("Opened a new channel {}, for request {}", channel, httpRequestContext); sendOnChannel(channel, httpRequestContext, requestEventBus); } else { logger.trace("Failed to opened a new channel for request {}", httpRequestContext); Throwable cause = future.cause(); requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, cause); } } }); }
From source file:com.king.platform.net.http.netty.request.HttpClientRequestHandler.java
License:Apache License
private void writeHeaders(ChannelHandlerContext ctx, final HttpRequestContext httpRequestContext, HttpRequest httpRequest, final RequestEventBus requestEventBus) { httpRequestContext.getTimeRecorder().startWriteHeaders(); ChannelFuture channelFuture = ctx.write(httpRequest); channelFuture.addListener(new ChannelFutureListener() { @Override/*from ww w. j a v a 2s. c om*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { logger.trace("Wrote headers operation completed, future: {}", future); requestEventBus.triggerEvent(Event.onWroteHeaders); requestEventBus.triggerEvent(Event.TOUCH); httpRequestContext.getTimeRecorder().completedWriteHeaders(); } else { requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause()); } } }); }
From source file:com.king.platform.net.http.netty.request.HttpClientRequestHandler.java
License:Apache License
private void writeLastHttpContent(ChannelHandlerContext ctx, final HttpRequestContext httpRequestContext, final RequestEventBus requestEventBus) { ChannelFuture future = ctx.writeAndFlush(new DefaultLastHttpContent()); future.addListener(new ChannelFutureListener() { @Override/* w w w . j a v a 2 s .c om*/ public void operationComplete(ChannelFuture future) throws Exception { logger.trace("writeLastHttpContent operation completed, future: {}", future); if (future.isSuccess()) { requestEventBus.triggerEvent(Event.onWroteContentCompleted); requestEventBus.triggerEvent(Event.TOUCH); httpRequestContext.getTimeRecorder().completedWriteLastBody(); } else { requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause()); } } }); }