List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
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. ja v a 2s .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/*from w ww .ja v a 2 s . c om*/ 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);//w w w . j a v a 2 s. c o m 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.Http2AlpnHandler.java
License:Apache License
@Override public void flush(final ChannelHandlerContext ctx) throws Exception { _alpnPromise.addListener(f -> {// www.ja v a 2 s . c om ChannelFuture future = (ChannelFuture) f; if (future.isSuccess()) { ctx.flush(); } }); }
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);//from www. j av a2s . com 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.Http2UpgradeHandler.java
License:Apache License
@Override public void flush(ChannelHandlerContext ctx) throws Exception { _upgradePromise.addListener(f -> { ChannelFuture future = (ChannelFuture) f; if (future.isSuccess()) { ctx.flush();//w ww .jav a2 s . c om } }); }
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 www .j a v a2s . co 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 w ww . j a v a 2 s . com*/ 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);/* w ww . j ava 2s . co 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.mobius.software.android.iotbroker.mqtt.net.ExceptionHandler.java
License:Open Source License
@Override public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {/* w w w .ja v a 2s . co m*/ ctx.connect(remoteAddress, localAddress, promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) Log.d("", "an error occured while connect"); } })); }