List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
From source file:cn.jpush.api.common.connection.HttpResponseHandler.java
License:Apache License
/** * Wait (sequentially) for a time duration for each anticipated response * * @param timeout Value of time to wait for each response * @param unit Units associated with {@code timeout} * @see HttpResponseHandler#put(int, ChannelFuture, ChannelPromise) *//*from w w w .j a v a 2s. c om*/ public void awaitResponses(long timeout, TimeUnit unit) { Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet() .iterator(); while (itr.hasNext()) { Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next(); ChannelFuture writeFuture = entry.getValue().getKey(); if (!writeFuture.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey()); } if (!writeFuture.isSuccess()) { throw new RuntimeException(writeFuture.cause()); } ChannelPromise promise = entry.getValue().getValue(); if (!promise.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey()); } if (!promise.isSuccess()) { throw new RuntimeException(promise.cause()); } System.out.println("---Stream id: " + entry.getKey() + " received---"); System.out.println("---Stream id: " + promise.toString()); itr.remove(); } }
From source file:cn.wantedonline.puppy.httpserver.component.HttpObjectAggregator.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception { AggregatedFullHttpMessage currentMessage = this.currentMessage; if (msg instanceof HttpMessage) { tooLongFrameFound = false;//from w ww . j av a 2 s . c om assert currentMessage == null; HttpMessage m = (HttpMessage) msg; // Handle the 'Expect: 100-continue' header if necessary. if (is100ContinueExpected(m)) { if (HttpHeaders.getContentLength(m, 0) > maxContentLength) { tooLongFrameFound = true; final ChannelFuture future = ctx.writeAndFlush(EXPECTATION_FAILED.duplicate().retain()); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } } }); if (closeOnExpectationFailed) { future.addListener(ChannelFutureListener.CLOSE); } ctx.pipeline().fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE); return; } ctx.writeAndFlush(CONTINUE.duplicate().retain()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } } }); } if (!m.getDecoderResult().isSuccess()) { removeTransferEncodingChunked(m); out.add(toFullMessage(m)); this.currentMessage = null; return; } if (msg instanceof HttpRequest) { HttpRequest header = (HttpRequest) msg; this.currentMessage = currentMessage = new AggregatedFullHttpRequest(header, ctx.alloc().compositeBuffer(maxCumulationBufferComponents), null); } else if (msg instanceof HttpResponse) { HttpResponse header = (HttpResponse) msg; this.currentMessage = currentMessage = new AggregatedFullHttpResponse(header, Unpooled.compositeBuffer(maxCumulationBufferComponents), null); } else { throw new Error(); } // A streamed message - initialize the cumulative buffer, and wait for incoming chunks. removeTransferEncodingChunked(currentMessage); } else if (msg instanceof HttpContent) { if (tooLongFrameFound) { if (msg instanceof LastHttpContent) { this.currentMessage = null; } // already detect the too long frame so just discard the content return; } assert currentMessage != null; // Merge the received chunk into the content of the current message. HttpContent chunk = (HttpContent) msg; CompositeByteBuf content = (CompositeByteBuf) currentMessage.content(); if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) { tooLongFrameFound = true; // release current message to prevent leaks currentMessage.release(); this.currentMessage = null; throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes."); } // Append the content of the chunk if (chunk.content().isReadable()) { chunk.retain(); content.addComponent(chunk.content()); content.writerIndex(content.writerIndex() + chunk.content().readableBytes()); } final boolean last; if (!chunk.getDecoderResult().isSuccess()) { currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause())); last = true; } else { last = chunk instanceof LastHttpContent; } if (last) { this.currentMessage = null; // Merge trailing headers into the message. if (chunk instanceof LastHttpContent) { LastHttpContent trailer = (LastHttpContent) chunk; currentMessage.setTrailingHeaders(trailer.trailingHeaders()); } else { currentMessage.setTrailingHeaders(new DefaultHttpHeaders()); } // Set the 'Content-Length' header. If one isn't already set. // This is important as HEAD responses will use a 'Content-Length' header which // does not match the actual body, but the number of bytes that would be // transmitted if a GET would have been used. // // See rfc2616 14.13 Content-Length if (!isContentLengthSet(currentMessage)) { currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(content.readableBytes())); } // All done out.add(currentMessage); } } else { throw new Error(); } }
From source file:code.google.nfs.rpc.netty.client.NettyClient.java
License:Apache License
public void sendRequest(final RequestWrapper wrapper, final int timeout) throws Exception { final long beginTime = System.currentTimeMillis(); final Client self = this; ChannelFuture writeFuture = cf.channel().writeAndFlush(wrapper); // use listener to avoid wait for write & thread context switch writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { return; }/*from www . j a v a 2 s . c o m*/ String errorMsg = ""; // write timeout if (System.currentTimeMillis() - beginTime >= timeout) { errorMsg = "write to send buffer consume too long time(" + (System.currentTimeMillis() - beginTime) + "),request id is:" + wrapper.getId(); } if (future.isCancelled()) { errorMsg = "Send request to " + cf.channel().toString() + " cancelled by user,request id is:" + wrapper.getId(); } if (!future.isSuccess()) { if (cf.channel().isOpen()) { // maybe some exception,so close the channel cf.channel().close(); } else { NettyClientFactory.getInstance().removeClient(key, self); } errorMsg = "Send request to " + cf.channel().toString() + " error" + future.cause(); } LOGGER.error(errorMsg); ResponseWrapper response = new ResponseWrapper(wrapper.getId(), wrapper.getCodecType(), wrapper.getProtocolType()); response.setException(new Exception(errorMsg)); self.putResponse(response); } }); }
From source file:code.google.nfs.rpc.netty.client.NettyClientFactory.java
License:Apache License
protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key) throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.TCP_NODELAY, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true"))) .option(ChannelOption.SO_REUSEADDR, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true"))); if (connectTimeout < 1000) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); } else {/* www . j a v a 2 s . c om*/ bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); } final NettyClientHandler handler = new NettyClientHandler(this, key); bootstrap.handler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("decoder", new NettyProtocolDecoder()); pipeline.addLast("encoder", new NettyProtocolEncoder()); pipeline.addLast("handler", handler); } }); ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort)).sync(); future.awaitUninterruptibly(connectTimeout); if (!future.isDone()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!"); } if (future.isCancelled()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); } if (!future.isSuccess()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); } NettyClient client = new NettyClient(future, key, connectTimeout); handler.setClient(client); return client; }
From source file:code.google.nfs.rpc.netty4.client.Netty4Client.java
License:Apache License
public void sendRequest(final RequestWrapper wrapper, final int timeout) throws Exception { final long beginTime = System.currentTimeMillis(); final Client self = this; ChannelFuture writeFuture = cf.channel().writeAndFlush(wrapper); // use listener to avoid wait for write & thread context switch writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { return; }/* w ww. j a v a 2 s.com*/ String errorMsg = ""; // write timeout if (System.currentTimeMillis() - beginTime >= timeout) { errorMsg = "write to send buffer consume too long time(" + (System.currentTimeMillis() - beginTime) + "),request id is:" + wrapper.getId(); } if (future.isCancelled()) { errorMsg = "Send request to " + cf.channel().toString() + " cancelled by user,request id is:" + wrapper.getId(); } if (!future.isSuccess()) { if (cf.channel().isActive()) { // maybe some exception,so close the channel cf.channel().close(); } else { Netty4ClientFactory.getInstance().removeClient(key, self); } errorMsg = "Send request to " + cf.channel().toString() + " error" + future.cause(); } LOGGER.error(errorMsg); ResponseWrapper response = new ResponseWrapper(wrapper.getId(), wrapper.getCodecType(), wrapper.getProtocolType()); response.setException(new Exception(errorMsg)); self.putResponse(response); } }); }
From source file:code.google.nfs.rpc.netty4.client.Netty4ClientFactory.java
License:Apache License
protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key) throws Exception { final Netty4ClientHandler handler = new Netty4ClientHandler(this, key); EventLoopGroup group = new NioEventLoopGroup(1); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true"))) .option(ChannelOption.SO_REUSEADDR, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true"))) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout < 1000 ? 1000 : connectTimeout) .handler(new ChannelInitializer<SocketChannel>() { @Override/*from www .j a va 2s . co m*/ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder()); ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder()); ch.pipeline().addLast("handler", handler); } }); ChannelFuture future = b.connect(targetIP, targetPort); future.awaitUninterruptibly(connectTimeout); if (!future.isDone()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!"); } if (future.isCancelled()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!"); } if (!future.isSuccess()) { LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause()); } Netty4Client client = new Netty4Client(future, key, connectTimeout); handler.setClient(client); return client; }
From source file:com.addthis.hydra.query.aggregate.MeshSourceAggregator.java
License:Apache License
@Override public void operationComplete(ChannelFuture future) throws Exception { // make sure this auto-recurring task doesn't go on forever if (stragglerTaskFuture != null) { stragglerTaskFuture.cancel(true); }// www .ja v a 2s. c o m if (!future.isSuccess()) { stopSources(future.cause().getMessage()); meshQueryMaster.handleError(query); consumer.sourceError(promoteHackForThrowables(future.cause())); } else { safelyRemoveSelfFromPipeline(future); stopSources("query is complete"); consumer.sendComplete(); } }
From source file:com.addthis.hydra.query.loadbalance.NextQueryTask.java
License:Apache License
private static void safelyHandleQueryFailure(ChannelFuture future) { try {// ww w . j a v a 2s . c o m ChannelPipeline pipeline = future.channel().pipeline(); ChannelHandlerContext lastContext = cleanPipelineAndGetLastContext(pipeline); if (lastContext != null) { sendDetailedError(lastContext, future.cause()); } else { logAndFormatErrorDetail(future.cause()); } } catch (Throwable error) { log.warn("unexpected error while trying to report to user; closing channel", error); safelyTryChannelClose(future); } }
From source file:com.addthis.meshy.AggregateChannelFuture.java
License:Apache License
/** the promises collection should not be mutated after construction */ AggregateChannelFuture(Collection<ChannelFuture> futures, EventExecutor executor) { super(executor); this.futures = futures; this.complete = new AtomicInteger(0); this.aggregatingListener = future -> { if (!future.isSuccess()) { anyCause = future.cause(); }/* ww w.j ava 2s . co m*/ if (complete.incrementAndGet() == futures.size()) { if (anyCause == null) { super.setSuccess(null); } else { super.setFailure(anyCause); } } }; for (ChannelFuture future : futures) { future.addListener(aggregatingListener); } }
From source file:com.alibaba.dubbo.remoting.transport.netty.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 {// www . jav a 2 s. com ChannelFuture future = channel.writeAndFlush(message); if (sent) { timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); success = future.await(timeout); } future.sync(); 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"); } }