List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
From source file:com.linkedin.mitm.proxy.ProxyServer.java
License:Open Source License
/** * Stop proxy server//from w w w.ja va2 s . c o m * */ public void stop() { ChannelGroupFuture future = _allChannels.close().awaitUninterruptibly(); if (!future.isSuccess()) { final Iterator<ChannelFuture> iter = future.iterator(); while (iter.hasNext()) { final ChannelFuture cf = iter.next(); if (!cf.isSuccess()) { LOG.warn(String.format("Failed to close channel %s because %s", cf.channel(), cf.cause())); } } } _acceptorGroup.shutdownGracefully(); _upstreamWorkerGroup.shutdownGracefully(); _downstreamWorkerGroup.shutdownGracefully(); }
From source file:com.linkedin.r2.transport.http.client.ChannelPoolLifecycle.java
License:Apache License
@Override public void create(final Callback<Channel> channelCallback) { final long start = System.currentTimeMillis(); _bootstrap.connect(_remoteAddress).addListener(new ChannelFutureListener() { @Override// www . j a va 2 s . c o m public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { synchronized (_createTimeTracker) { _createTimeTracker.addValue(System.currentTimeMillis() - start); } Channel c = channelFuture.channel(); if (_tcpNoDelay) { c.config().setOption(ChannelOption.TCP_NODELAY, true); } _channelGroup.add(c); channelCallback.onSuccess(c); } else { channelCallback.onError(HttpNettyStreamClient.toException(channelFuture.cause())); } } }); }
From source file:com.linkedin.r2.transport.http.client.ChannelPoolLifecycle.java
License:Apache License
@Override public void destroy(final Channel channel, final boolean error, final Callback<Channel> channelCallback) { if (channel.isOpen()) { channel.close().addListener(new ChannelFutureListener() { @Override// w w w.j a v a2 s . co m public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { channelCallback.onSuccess(channelFuture.channel()); } else { channelCallback.onError(HttpNettyStreamClient.toException(channelFuture.cause())); } } }); } else { channelCallback.onSuccess(channel); } }
From source file:com.linkedin.r2.transport.http.client.Http2AlpnHandler.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!(msg instanceof RequestWithCallback)) { ctx.write(msg, promise);//from w w w. ja v a 2s . com return; } _alpnPromise.addListener(f -> { ChannelFuture future = (ChannelFuture) f; if (future.isSuccess()) { ctx.write(msg, promise); } else { // Releases the async pool handle @SuppressWarnings("unchecked") TimeoutAsyncPoolHandle<?> handle = ((RequestWithCallback<?, ?, TimeoutAsyncPoolHandle<?>>) msg) .handle(); handle.error().release(); // Invokes user specified callback with error TransportCallback<?> callback = ((RequestWithCallback) msg).callback(); callback.onResponse(TransportResponseImpl.error(future.cause())); } }); }
From source file:com.linkedin.r2.transport.http.client.Http2UpgradeHandler.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!(msg instanceof RequestWithCallback)) { ctx.write(msg, promise);/*w ww .j a v a 2s . c o m*/ return; } _upgradePromise.addListener(f -> { ChannelFuture future = (ChannelFuture) f; if (future.isSuccess()) { ctx.write(msg, promise); } else { // Releases the async pool handle @SuppressWarnings("unchecked") TimeoutAsyncPoolHandle<?> handle = ((RequestWithCallback<?, ?, TimeoutAsyncPoolHandle<?>>) msg) .handle(); handle.error().release(); // Invokes user specified callback with error TransportCallback<?> callback = ((RequestWithCallback) msg).callback(); callback.onResponse(TransportResponseImpl.error(future.cause())); } }); }
From source file:com.linkedin.r2.transport.http.client.RAPResponseDecoder.java
License:Apache License
@Override protected void channelRead0(final ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpResponse) { HttpResponse m = (HttpResponse) msg; _shouldCloseConnection = !HttpUtil.isKeepAlive(m); if (HttpUtil.is100ContinueExpected(m)) { ctx.writeAndFlush(CONTINUE).addListener(new ChannelFutureListener() { @Override/*from w ww . j a v a 2 s .c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } } }); } if (!m.decoderResult().isSuccess()) { ctx.fireExceptionCaught(m.decoderResult().cause()); return; } // remove chunked encoding. if (HttpUtil.isTransferEncodingChunked(m)) { HttpUtil.setTransferEncodingChunked(m, false); } Timeout<None> timeout = ctx.channel().attr(TIMEOUT_ATTR_KEY).getAndRemove(); if (timeout == null) { LOG.debug("dropped a response after channel inactive or exception had happened."); return; } final TimeoutBufferedWriter writer = new TimeoutBufferedWriter(ctx, _maxContentLength, BUFFER_HIGH_WATER_MARK, BUFFER_LOW_WATER_MARK, timeout); EntityStream entityStream = EntityStreams.newEntityStream(writer); _chunkedMessageWriter = writer; StreamResponseBuilder builder = new StreamResponseBuilder(); builder.setStatus(m.status().code()); for (Map.Entry<String, String> e : m.headers()) { String key = e.getKey(); String value = e.getValue(); if (key.equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) { builder.addCookie(value); } else { builder.unsafeAddHeaderValue(key, value); } } ctx.fireChannelRead(builder.build(entityStream)); } else if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; TimeoutBufferedWriter currentWriter = _chunkedMessageWriter; // Sanity check if (currentWriter == null) { throw new IllegalStateException("received " + HttpContent.class.getSimpleName() + " without " + HttpResponse.class.getSimpleName()); } if (!chunk.decoderResult().isSuccess()) { this.exceptionCaught(ctx, chunk.decoderResult().cause()); } currentWriter.processHttpChunk(chunk); if (chunk instanceof LastHttpContent) { _chunkedMessageWriter = null; if (_shouldCloseConnection) { ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_DESTROY_SIGNAL); } else { ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_RELEASE_SIGNAL); } } } else { // something must be wrong, but let's proceed so that // handler after us has a chance to process it. ctx.fireChannelRead(msg); } }
From source file:com.mastfrog.acteur.server.HttpObjectAggregator.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception { FullHttpMessage currentMessage = this.currentMessage; if (msg instanceof HttpMessage) { tooLongFrameFound = false;//from ww w . j a va2 s . c o m assert currentMessage == null; HttpMessage m = (HttpMessage) msg; // Handle the 'Expect: 100-continue' header if necessary. // TODO: Respond with 413 Request Entity Too Large // and discard the traffic or close the connection. // No need to notify the upstream handlers - just log. // If decoding a response, just throw an exception. if (is100ContinueExpected(m)) { ByteBuf buf = CONTINUE_LINE.duplicate(); buf.retain(); ctx.writeAndFlush(buf).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 DefaultFullHttpRequest(header.getProtocolVersion(), header.getMethod(), header.getUri(), Unpooled.compositeBuffer(maxCumulationBufferComponents)); } else if (msg instanceof HttpResponse) { HttpResponse header = (HttpResponse) msg; this.currentMessage = currentMessage = new DefaultFullHttpResponse(header.getProtocolVersion(), header.getStatus(), Unpooled.compositeBuffer(maxCumulationBufferComponents)); } else { throw new Error(); } currentMessage.headers().set(m.headers()); // 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.headers().add(trailer.trailingHeaders()); } // Set the 'Content-Length' header. currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(content.readableBytes())); // All done out.add(currentMessage); } } else { throw new Error(); } }
From source file:com.mastfrog.netty.http.client.HttpClient.java
License:Open Source License
private void submit(final URL url, HttpRequest rq, final AtomicBoolean cancelled, final ResponseFuture handle, final ResponseHandler<?> r, RequestInfo info, Duration timeout, boolean noAggregate) { if (info != null && info.isExpired()) { cancelled.set(true);//from w ww . j ava 2 s . c o m } if (cancelled.get()) { handle.event(new State.Cancelled()); return; } try { for (RequestInterceptor i : interceptors) { rq = i.intercept(rq); } final HttpRequest req = rq; Bootstrap bootstrap; if (url.getProtocol().isSecure()) { bootstrap = startSsl(url.getHostAndPort()); } else { bootstrap = start(url.getHostAndPort()); } if (!url.isValid()) { throw new IllegalArgumentException(url.getProblems() + ""); } TimeoutTimerTask tt = null; if (info == null) { info = new RequestInfo(url, req, cancelled, handle, r, timeout, tt, noAggregate); if (timeout != null) { tt = new TimeoutTimerTask(cancelled, handle, r, info); timer.schedule(tt, timeout.getMillis()); } info.timer = tt; } if (info.isExpired()) { handle.event(new State.Timeout(info.age())); return; } handle.event(new State.Connecting()); //XXX who is escaping this? req.setUri(req.getUri().replaceAll("%5f", "_")); ChannelFuture fut = bootstrap.connect(url.getHost().toString(), url.getPort().intValue()); if (tt != null) { fut.channel().closeFuture().addListener(tt); } fut.channel().attr(KEY).set(info); handle.setFuture(fut); if (!monitors.isEmpty()) { for (ActivityMonitor m : monitors) { m.onStartRequest(url); } fut.channel().closeFuture().addListener(new AdapterCloseNotifier(url)); } fut.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { Throwable cause = future.cause(); if (cause == null) { cause = new ConnectException(url.getHost().toString()); } handle.event(new State.Error(cause)); if (r != null) { r.onError(cause); } cancelled.set(true); } if (cancelled.get()) { future.cancel(true); if (future.channel().isOpen()) { future.channel().close(); } for (ActivityMonitor m : monitors) { m.onEndRequest(url); } return; } handle.event(new State.Connected(future.channel())); handle.event(new State.SendRequest(req)); future = future.channel().writeAndFlush(req); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (cancelled.get()) { future.cancel(true); future.channel().close(); } handle.event(new State.AwaitingResponse()); } }); } }); } catch (Exception ex) { Exceptions.chuck(ex); } }
From source file:com.mastfrog.scamper.Sender.java
License:Open Source License
/** * Send a message using the passed channel. * * @param channel The channel/*from ww w. j a v a2 s .c om*/ * @param message A future which will be notified when the message is * flushed to the socket * @param sctpChannel The ordinal of the sctp channel * @return a future that will be notified when the message write is * completed * @throws IOException if something goes wrong */ @SuppressWarnings("unchecked") public ChannelFuture send(Channel channel, final Message<?> message, int sctpChannel) throws IOException { Checks.notNull("channel", channel); Checks.notNull("message", message); Checks.nonNegative("sctpChannel", sctpChannel); ByteBufAllocator alloc = channel.alloc(); ByteBuf outbound = alloc.buffer(); if (message.body != null) { if (message.body instanceof ByteBuf) { outbound = (ByteBuf) message.body; } else { outbound = alloc.buffer(); try (ByteBufOutputStream out = new ByteBufOutputStream(outbound)) { mapper.writeValue(message.body, out); } } } ByteBuf encodedBuffer = encoder.encode(message.type, outbound, channel); NioSctpChannel ch = (NioSctpChannel) channel; if (!ch.isOpen()) { return ch.newFailedFuture(new ClosedChannelException()); } if (ch.association() == null) { return channel.newFailedFuture(new IOException("Association closed - client has disconnected")); } MessageInfo info = MessageInfo.createOutgoing(ch.association(), ch.remoteAddress(), sctpChannel); info.unordered(true); SctpMessage sctpMessage = new SctpMessage(info, encodedBuffer); logger.log(Level.FINE, "Send message to {0} type {1}", new Object[] { channel.remoteAddress(), message.type }); ChannelFuture result = channel.writeAndFlush(sctpMessage); if (logger.isLoggable(Level.FINER)) { result.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.cause() != null) { logger.log(Level.SEVERE, "Send to " + ch.remoteAddress() + " failed", future.cause()); } else { logger.log(Level.FINER, "Send completed to {0}", ch.remoteAddress()); } } }); } return result; }
From source file:com.mastfrog.scamper.Sender.java
License:Open Source License
/** * Send a message using the passed channel. * * @param address The address//from w ww .ja v a 2 s. c o m * @param message A future which will be notified when the message is * flushed to the socket * @param sctpChannel The ordinal of the sctp channel * @param l A ChannelFutureListener to be notified when the mesage is * flushed (remember to check <code>ChannelFuture.getCause()</code> to check * for failure) * @return a future that will be notified when the message write is * completed */ public ChannelFuture send(final Address address, final Message<?> message, final int sctpChannel, final ChannelFutureListener l) { Checks.notNull("address", address); Checks.notNull("message", message); Checks.nonNegative("sctpChannel", sctpChannel); logger.log(Level.FINE, "Send message to {0} on {1} type {1}", new Object[] { address, sctpChannel, message.type }); return associations.connect(address).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.cause() == null) { logger.log(Level.FINE, "Got back connection {0} for {1}", new Object[] { future.channel().remoteAddress(), address }); } ChannelFuture fut = send(future.channel(), message, sctpChannel); if (l != null) { fut.addListener(l); } } }); }