List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:io.jsync.datagram.impl.DefaultDatagramSocket.java
License:Open Source License
@SuppressWarnings("unchecked") final void addListener(ChannelFuture future, Handler<AsyncResult<DatagramSocket>> handler) { if (handler != null) { future.addListener(new DatagramChannelFutureListener<>(this, handler, async, context)); }/*from w w w . j a va 2 s .c o m*/ }
From source file:io.jsync.datagram.impl.DefaultDatagramSocket.java
License:Open Source License
@Override public void close(final Handler<AsyncResult<Void>> handler) { // make sure everything is flushed out on close endReadAndFlush();/*from w w w . j a v a 2 s. c o m*/ ChannelFuture future = channel.close(); if (handler != null) { future.addListener(new DatagramChannelFutureListener<>(null, handler, async, context)); } }
From source file:io.jsync.http.impl.DefaultHttpClient.java
License:Open Source License
void internalConnect(final Handler<ClientConnection> connectHandler, final Handler<Throwable> connectErrorHandler) { if (bootstrap == null) { // Share the event loop thread to also serve the HttpClient's network traffic. AsyncEventLoopGroup pool = new AsyncEventLoopGroup(); pool.addWorker(actualCtx.getEventLoop()); bootstrap = new Bootstrap(); bootstrap.group(pool);//from w w w .j a v a 2 s.com bootstrap.channel(NioSocketChannel.class); tcpHelper.checkSSL(async); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (tcpHelper.isSSL()) { pipeline.addLast("ssl", tcpHelper.createSslHandler(async, true, host, port)); } pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false)); if (tryUseCompression) { pipeline.addLast("inflater", new HttpContentDecompressor(true)); } pipeline.addLast("handler", new ClientHandler()); } }); } tcpHelper.applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) throws Exception { final Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (tcpHelper.isSSL()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { if (future.isSuccess()) { connected(ch, connectHandler); } else { connectionFailed(ch, connectErrorHandler, new SSLHandshakeException("Failed to create SSL connection")); } } }); } else { connected(ch, connectHandler); } } else { connectionFailed(ch, connectErrorHandler, channelFuture.cause()); } } }); }
From source file:io.jsync.net.impl.ConnectionBase.java
License:Open Source License
protected void addFuture(final Handler<AsyncResult<Void>> doneHandler, final ChannelFuture future) { if (future != null) { future.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture channelFuture) throws Exception { if (doneHandler != null) { context.execute(new Runnable() { public void run() { if (channelFuture.isSuccess()) { doneHandler.handle(new DefaultFutureResult<>((Void) null)); } else { doneHandler.handle(new DefaultFutureResult<Void>(channelFuture.cause())); }/*from w w w . j ava 2 s . c om*/ } }); } else if (!channelFuture.isSuccess()) { handleException(channelFuture.cause()); } } }); } }
From source file:io.jsync.net.impl.ConnectionBase.java
License:Open Source License
protected ChannelFuture sendFile(File file) { final RandomAccessFile raf; try {// w ww . ja v a 2 s. c om raf = new RandomAccessFile(file, "r"); long fileLength = file.length(); // Write the content. ChannelFuture writeFuture; if (!supportsFileRegion()) { // Cannot use zero-copy writeFuture = write(new ChunkedFile(raf, 0, fileLength, 8192)); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength); writeFuture = write(region); } writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { raf.close(); } }); return writeFuture; } catch (IOException e) { handleException(e); return null; } }
From source file:io.jsync.net.impl.DefaultNetClient.java
License:Open Source License
private void connect(final int port, final String host, final Handler<AsyncResult<NetSocket>> connectHandler, final int remainingAttempts) { if (bootstrap == null) { tcpHelper.checkSSL(async);/*www .ja v a2 s . c o m*/ bootstrap = new Bootstrap(); bootstrap.group(actualCtx.getEventLoop()); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (tcpHelper.isSSL()) { SslHandler sslHandler = tcpHelper.createSslHandler(async, true); pipeline.addLast("ssl", sslHandler); } if (tcpHelper.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 } pipeline.addLast("handler", new AsyncNetHandler(async, socketMap)); } }); configurable = false; } tcpHelper.applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) throws Exception { final Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (tcpHelper.isSSL()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { if (future.isSuccess()) { connected(ch, connectHandler); } else { failed(ch, future.cause(), connectHandler); } } }); } else { connected(ch, connectHandler); } } else { if (remainingAttempts > 0 || remainingAttempts == -1) { actualCtx.execute(ch.eventLoop(), new Runnable() { public void run() { log.debug("Failed to create connection. Will retry in " + reconnectInterval + " milliseconds"); //Set a timer to retry connection async.setTimer(reconnectInterval, new Handler<Long>() { public void handle(Long timerID) { connect(port, host, connectHandler, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1); } }); } }); } else { failed(ch, channelFuture.cause(), connectHandler); } } } }); }
From source file:io.jsync.net.impl.DefaultNetSocket.java
License:Open Source License
@Override public NetSocket sendFile(String filename, final Handler<AsyncResult<Void>> resultHandler) { File f = new File(PathAdjuster.adjust(async, filename)); if (f.isDirectory()) { throw new IllegalArgumentException("filename must point to a file and not to a directory"); }/*from www. ja va 2s . c o m*/ ChannelFuture future = super.sendFile(f); if (resultHandler != null) { future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { final AsyncResult<Void> res; if (future.isSuccess()) { res = new DefaultFutureResult<>((Void) null); } else { res = new DefaultFutureResult<>(future.cause()); } async.runOnContext(new Handler<Void>() { @Override public void handle(Void v) { resultHandler.handle(res); } }); } }); } return this; }
From source file:io.lettuce.core.AbstractRedisClient.java
License:Apache License
private void initializeChannelAsync0(ConnectionBuilder connectionBuilder, CompletableFuture<Channel> channelReadyFuture, SocketAddress redisAddress) { logger.debug("Connecting to Redis at {}", redisAddress); Bootstrap redisBootstrap = connectionBuilder.bootstrap(); RedisChannelInitializer initializer = connectionBuilder.build(); redisBootstrap.handler(initializer); clientResources.nettyCustomizer().afterBootstrapInitialized(redisBootstrap); CompletableFuture<Boolean> initFuture = initializer.channelInitialized(); ChannelFuture connectFuture = redisBootstrap.connect(redisAddress); channelReadyFuture.whenComplete((c, t) -> { if (t instanceof CancellationException) { connectFuture.cancel(true);//from www .j a v a 2 s . co m initFuture.cancel(true); } }); connectFuture.addListener(future -> { if (!future.isSuccess()) { logger.debug("Connecting to Redis at {}: {}", redisAddress, future.cause()); connectionBuilder.endpoint().initialState(); channelReadyFuture.completeExceptionally(future.cause()); return; } initFuture.whenComplete((success, throwable) -> { if (throwable == null) { logger.debug("Connecting to Redis at {}: Success", redisAddress); RedisChannelHandler<?, ?> connection = connectionBuilder.connection(); connection.registerCloseables(closeableResources, connection); channelReadyFuture.complete(connectFuture.channel()); return; } logger.debug("Connecting to Redis at {}, initialization: {}", redisAddress, throwable); connectionBuilder.endpoint().initialState(); Throwable failure; if (throwable instanceof RedisConnectionException) { failure = throwable; } else if (throwable instanceof TimeoutException) { failure = new RedisConnectionException( "Could not initialize channel within " + connectionBuilder.getTimeout(), throwable); } else { failure = throwable; } channelReadyFuture.completeExceptionally(failure); }); }); }
From source file:io.lettuce.core.internal.Futures.java
License:Apache License
/** * Adapt Netty's {@link ChannelFuture} emitting a {@link Void} result into a {@link CompletableFuture}. * * @param future//from w ww . j ava 2 s . c o m * @return the {@link CompletableFuture}. */ public static void adapt(ChannelFuture future, CompletableFuture<Void> target) { future.addListener(f -> { if (f.isSuccess()) { target.complete(null); } else { target.completeExceptionally(f.cause()); } }); if (future.isSuccess()) { target.complete(null); } else if (future.isCancelled()) { target.cancel(false); } else if (future.isDone() && !future.isSuccess()) { target.completeExceptionally(future.cause()); } }
From source file:io.lettuce.core.protocol.DefaultEndpoint.java
License:Apache License
private void writeToChannelAndFlush(RedisCommand<?, ?, ?> command) { QUEUE_SIZE.incrementAndGet(this); ChannelFuture channelFuture = channelWriteAndFlush(command); if (reliability == Reliability.AT_MOST_ONCE) { // cancel on exceptions and remove from queue, because there is no housekeeping channelFuture.addListener(AtMostOnceWriteListener.newInstance(this, command)); }/*from ww w. j a v a 2s . co m*/ if (reliability == Reliability.AT_LEAST_ONCE) { // commands are ok to stay within the queue, reconnect will retrigger them channelFuture.addListener(RetryListener.newInstance(this, command)); } }