List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:io.advantageous.conekt.http.impl.HttpClientImpl.java
License:Open Source License
private void internalConnect(ContextImpl clientContext, int port, String host, Handler<ClientConnection> connectHandler, Handler<Throwable> connectErrorHandler, ConnectionLifeCycleListener listener) { ContextImpl context;/*from www .j a v a2 s .c o m*/ if (clientContext == null) { // Embedded context = vertx.getOrCreateContext(); } else { context = clientContext; } Bootstrap bootstrap = new Bootstrap(); bootstrap.group(context.nettyEventLoop()); bootstrap.channelFactory(new VertxNioSocketChannelFactory()); sslHelper.validate(vertx); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (options.isSsl()) { pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, true, host, port)); } pipeline.addLast("codec", new HttpClientCodec(4096, 8192, options.getMaxChunkSize(), false, false)); if (options.isTryUseCompression()) { pipeline.addLast("inflater", new HttpContentDecompressor(true)); } if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout())); } pipeline.addLast("handler", new ClientHandler(vertx, context)); } }); applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener((ChannelFuture channelFuture) -> { Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (options.isSsl()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(fut2 -> { if (fut2.isSuccess()) { connected(context, port, host, ch, connectHandler, connectErrorHandler, listener); } else { SSLHandshakeException sslException = new SSLHandshakeException( "Failed to create SSL connection"); Optional.ofNullable(fut2.cause()).ifPresent(sslException::initCause); connectionFailed(context, ch, connectErrorHandler, sslException, listener); } }); } else { connected(context, port, host, ch, connectHandler, connectErrorHandler, listener); } } else { connectionFailed(context, ch, connectErrorHandler, channelFuture.cause(), listener); } }); }
From source file:io.advantageous.conekt.net.impl.ConnectionBase.java
License:Open Source License
protected void addFuture(final Handler<AsyncResult<Void>> completionHandler, final ChannelFuture future) { if (future != null) { future.addListener(channelFuture -> context.executeFromIO(() -> { if (completionHandler != null) { if (channelFuture.isSuccess()) { completionHandler.handle(Future.succeededFuture()); } else { completionHandler.handle(Future.failedFuture(channelFuture.cause())); }/*from w ww . j a v a2s. c o m*/ } else if (!channelFuture.isSuccess()) { handleException(channelFuture.cause()); } })); } }
From source file:io.advantageous.conekt.net.impl.ConnectionBase.java
License:Open Source License
protected ChannelFuture sendFile(RandomAccessFile raf, long offset, long length) throws IOException { // Write the content. ChannelFuture writeFuture; if (!supportsFileRegion()) { // Cannot use zero-copy writeFuture = writeToChannel(new ChunkedFile(raf, offset, length, 8192)); } else {/* w w w.j ava 2 s. c o m*/ // No encryption - use zero-copy. FileRegion region = new DefaultFileRegion(raf.getChannel(), offset, length); writeFuture = writeToChannel(region); } if (writeFuture != null) { writeFuture.addListener(fut -> raf.close()); } else { raf.close(); } return writeFuture; }
From source file:io.advantageous.conekt.net.impl.NetClientImpl.java
License:Open Source License
private void connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler, int remainingAttempts) { Objects.requireNonNull(host, "No null host accepted"); Objects.requireNonNull(connectHandler, "No null connectHandler accepted"); ContextImpl context = vertx.getOrCreateContext(); sslHelper.validate(vertx);/*from w ww . j a v a2s. c om*/ Bootstrap bootstrap = new Bootstrap(); bootstrap.group(context.nettyEventLoop()); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (sslHelper.isSSL()) { SslHandler sslHandler = sslHelper.createSslHandler(vertx, true); pipeline.addLast("ssl", sslHandler); } if (sslHelper.isSSL()) { // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used. pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support } if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout())); } pipeline.addLast("handler", new ConektNetHandler(socketMap)); } }); applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener((ChannelFuture channelFuture) -> { Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (sslHelper.isSSL()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(future2 -> { if (future2.isSuccess()) { connected(context, ch, connectHandler); } else { failed(context, ch, future2.cause(), connectHandler); } }); } else { connected(context, ch, connectHandler); } } else { if (remainingAttempts > 0 || remainingAttempts == -1) { context.executeFromIO(() -> { log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds"); //Set a timer to retry connection vertx.setTimer(options.getReconnectInterval(), tid -> connect(port, host, connectHandler, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1)); }); } else { failed(context, ch, channelFuture.cause(), connectHandler); } } }); }
From source file:io.advantageous.conekt.net.impl.NetSocketImpl.java
License:Open Source License
@Override public NetSocket sendFile(String filename, long offset, long length, final Handler<AsyncResult<Void>> resultHandler) { File f = vertx.resolveFile(filename); if (f.isDirectory()) { throw new IllegalArgumentException("filename must point to a file and not to a directory"); }/* w ww . j av a 2s .c o m*/ RandomAccessFile raf = null; try { raf = new RandomAccessFile(f, "r"); ChannelFuture future = super.sendFile(raf, Math.min(offset, f.length()), Math.min(length, f.length() - offset)); if (resultHandler != null) { future.addListener(fut -> { final AsyncResult<Void> res; if (future.isSuccess()) { res = Future.succeededFuture(); } else { res = Future.failedFuture(future.cause()); } vertx.runOnContext(v -> resultHandler.handle(res)); }); } } catch (IOException e) { try { if (raf != null) { raf.close(); } } catch (IOException ignore) { } if (resultHandler != null) { vertx.runOnContext(v -> resultHandler.handle(Future.failedFuture(e))); } else { log.error("Failed to send file", e); } } return this; }
From source file:io.airlift.drift.transport.netty.client.InvocationResponseFuture.java
License:Apache License
private synchronized void tryInvocation(Channel channel) { // is request already canceled if (isCancelled()) { connectionManager.returnConnection(channel); return;//from www. j av a2 s .com } try { invocationFuture = new ThriftRequest(request.getMethod(), request.getParameters(), request.getHeaders()); Futures.addCallback(invocationFuture, new FutureCallback<Object>() { @Override public void onSuccess(Object result) { try { connectionManager.returnConnection(channel); set(result); } catch (Throwable t) { fatalError(t); } } @Override public void onFailure(Throwable t) { try { connectionManager.returnConnection(channel); } finally { fatalError(t); } } }, directExecutor()); ChannelFuture sendFuture = channel.writeAndFlush(invocationFuture); sendFuture.addListener(channelFuture -> { try { if (!channelFuture.isSuccess()) { fatalError(channelFuture.cause()); } } catch (Throwable t) { fatalError(t); } }); } catch (Throwable t) { try { connectionManager.returnConnection(channel); } finally { fatalError(t); } } }
From source file:io.airlift.drift.transport.netty.client.ThriftClientHandler.java
License:Apache License
private void sendMessage(ChannelHandlerContext context, ThriftRequest thriftRequest, ChannelPromise promise) throws Exception { // todo ONEWAY_SEQUENCE_ID is a header protocol thing... make sure this works with framed and unframed int sequenceId = thriftRequest.isOneway() ? ONEWAY_SEQUENCE_ID : this.sequenceId.incrementAndGet(); RequestHandler requestHandler = new RequestHandler(thriftRequest, sequenceId); // register timeout requestHandler.registerRequestTimeout(context.executor()); // write request ByteBuf requestBuffer = requestHandler.encodeRequest(context.alloc()); // register request if we are expecting a response if (!thriftRequest.isOneway()) { if (pendingRequests.putIfAbsent(sequenceId, requestHandler) != null) { requestHandler.onChannelError( new TTransportException("Another request with the same sequenceId is already in progress")); requestBuffer.release();//from w w w. jav a2 s . c o m return; } } // if this connection is failed, immediately fail the request TException channelError = this.channelError.get(); if (channelError != null) { thriftRequest.failed(channelError); requestBuffer.release(); return; } try { ThriftFrame thriftFrame = new ThriftFrame(sequenceId, requestBuffer, thriftRequest.getHeaders(), transport, protocol, true); ChannelFuture sendFuture = context.write(thriftFrame, promise); sendFuture.addListener(future -> messageSent(context, sendFuture, requestHandler)); } catch (Throwable t) { onError(context, t, Optional.of(requestHandler)); requestBuffer.release(); } }
From source file:io.airlift.drift.transport.netty.ThriftClientHandler.java
License:Apache License
private void sendMessage(ChannelHandlerContext context, ThriftRequest thriftRequest, ChannelPromise promise) throws Exception { // todo ONEWAY_SEQUENCE_ID is a header protocol thing... make sure this works with framed and unframed int sequenceId = thriftRequest.isOneway() ? ONEWAY_SEQUENCE_ID : this.sequenceId.incrementAndGet(); RequestHandler requestHandler = new RequestHandler(thriftRequest, sequenceId); // register timeout requestHandler.registerRequestTimeout(context.executor()); // write request ByteBuf requestBuffer = requestHandler.encodeRequest(context.alloc()); // register request if we are expecting a response if (!thriftRequest.isOneway()) { if (pendingRequests.putIfAbsent(sequenceId, requestHandler) != null) { requestHandler.onChannelError( new TTransportException("Another request with the same sequenceId is already in progress")); }//from w w w. java 2 s.co m } try { ChannelFuture sendFuture = context.write(requestBuffer, promise); sendFuture.addListener(future -> messageSent(context, sendFuture, requestHandler)); } catch (Throwable t) { onError(context, t); } }
From source file:io.aos.netty5.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);//from w ww.ja v a 2 s .co m return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaderUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaderUtil.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); } else { sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println(future.channel() + " Transfer progress: " + progress); } else { System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " Transfer complete."); } }); // Write the end marker ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Decide whether to close the connection or not. if (!HttpHeaderUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.aos.netty5.http.upload.HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);/* ww w . j a v a 2 s. c o m*/ // Decide whether to close the connection or not. boolean close = request.headers().contains(CONNECTION, HttpHeaders.Values.CLOSE, true) || request.protocolVersion().equals(HttpVersion.HTTP_1_0) && !request.headers().contains(CONNECTION, HttpHeaders.Values.KEEP_ALIVE, true); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().set(CONTENT_LENGTH, buf.readableBytes()); } Set<Cookie> cookies; String value = request.headers().get(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }