List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
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/*from w w w . j a v a 2s.c o m*/ 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()); } } }); }
From source file:com.king.platform.net.http.netty.request.InputStreamHttpBody.java
License:Apache License
@Override public ChannelFuture writeContent(ChannelHandlerContext ctx) throws IOException { final InputStream is = inputStream; Channel channel = ctx.channel(); ChannelFuture channelFuture = channel.write(new ChunkedStream(inputStream), channel.newProgressivePromise()); channelFuture.addListener(new ChannelFutureListener() { @Override/* w ww.java 2s . c o m*/ public void operationComplete(ChannelFuture future) throws Exception { is.close(); } }); return channelFuture; }
From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java
License:Open Source License
protected void sendFile(final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, SyncFile syncFile) throws Exception { Path path = Paths.get(syncFile.getFilePathName()); if (Files.notExists(path)) { _syncTrafficShapingHandler.decrementConnectionsCount(); if (_logger.isTraceEnabled()) { Channel channel = channelHandlerContext.channel(); _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path); }//from w ww. j a v a2 s . c o m _sendError(channelHandlerContext, NOT_FOUND); return; } if (_logger.isDebugEnabled()) { Channel channel = channelHandlerContext.channel(); _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path); } long modifiedTime = syncFile.getModifiedTime(); long previousModifiedTime = syncFile.getPreviousModifiedTime(); if (OSDetector.isApple()) { modifiedTime = modifiedTime / 1000 * 1000; previousModifiedTime = previousModifiedTime / 1000 * 1000; } FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS); long currentTime = currentFileTime.toMillis(); if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) { _syncTrafficShapingHandler.decrementConnectionsCount(); Channel channel = channelHandlerContext.channel(); _logger.error( "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}", channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime); _sendError(channelHandlerContext, NOT_FOUND); return; } HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK); long size = Files.size(path); HttpUtil.setContentLength(httpResponse, size); HttpHeaders httpHeaders = httpResponse.headers(); MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap(); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName())); if (HttpUtil.isKeepAlive(fullHttpRequest)) { httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } channelHandlerContext.write(httpResponse); SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime); ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpChunkedInput(syncChunkedFile), channelHandlerContext.newProgressivePromise()); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { _syncTrafficShapingHandler.decrementConnectionsCount(); if (channelFuture.isSuccess()) { return; } Throwable exception = channelFuture.cause(); Channel channel = channelHandlerContext.channel(); _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception); channelHandlerContext.close(); } }); if (!HttpUtil.isKeepAlive(fullHttpRequest)) { channelFuture.addListener(ChannelFutureListener.CLOSE); } }
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//from w w w . jav a 2 s. c om 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// www.ja v a 2 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.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 va 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.look.netty.demo.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception { if (message instanceof Socks4CommandRequest) { final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override/* w ww . j av a 2 s.co m*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse( Socks5CommandStatus.SUCCESS, request.dstAddrType())); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:com.magnet.yak.load.XMPPHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) { // (1) String s = "<stream:stream to=\"54.148.43.16\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">\"\r\n"; final ByteBuf str = ctx.alloc().buffer(s.getBytes().length); // (2) str.writeBytes(s.getBytes());/*w w w. ja va 2s. c o m*/ LOGGER.trace("channelActive : {}"); final ChannelFuture f = ctx.writeAndFlush(str); f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture arg0) throws Exception { LOGGER.trace("operationComplete : {}"); } }); /*final ChannelFuture f = ctx.writeAndFlush(time); // (3) f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture arg0) throws Exception { } }); */// (4) }
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 w w . j a va 2 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 ww w . j av a 2s. c om } 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); } }