Example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener

List of usage examples for io.netty.util.concurrent GenericFutureListener GenericFutureListener

Introduction

In this page you can find the example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener.

Prototype

GenericFutureListener

Source Link

Usage

From source file:org.stem.client.old.StorageNodeClient.java

License:Apache License

private GenericFutureListener futureListener() {
    return new GenericFutureListener() {

        @Override//from ww w .  j  a  v a 2 s . com
        public void operationComplete(Future future) throws Exception {

        }
    };
}

From source file:org.teiid.transport.SSLAwareChannelHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    ChannelListener listener = this.listenerFactory.createChannelListener(new ObjectChannelImpl(ctx.channel()));
    this.listeners.put(ctx.channel(), listener);
    maxChannels = Math.max(maxChannels, this.listeners.size());
    SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
    if (sslHandler != null) {
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<DefaultPromise<Channel>>() {
            @Override// w w w .  ja v  a  2s.  c  o m
            public void operationComplete(DefaultPromise<Channel> future) throws Exception {
                onConnection(ctx.channel());

            }
        });
    } else {
        onConnection(ctx.channel());
    }
}

From source file:org.vertx.java.core.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.
        VertxEventLoopGroup pool = new VertxEventLoopGroup();
        pool.addWorker(actualCtx.getEventLoop());
        bootstrap = new Bootstrap();
        bootstrap.group(pool);//from ww  w  .j a v a 2s  .c  o m
        bootstrap.channel(NioSocketChannel.class);
        tcpHelper.checkSSL(vertx);

        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (tcpHelper.isSSL()) {
                    SSLEngine engine = tcpHelper.getSSLContext().createSSLEngine(host, port);
                    if (tcpHelper.isVerifyHost()) {
                        SSLParameters sslParameters = engine.getSSLParameters();
                        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                        engine.setSSLParameters(sslParameters);
                    }
                    engine.setUseClientMode(true); //We are on the client side of the connection
                    pipeline.addLast("ssl", new SslHandler(engine));
                }

                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:org.vertx.java.core.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(vertx);// ww w  . j  a  va 2 s .  co 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(vertx, 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 VertxNetHandler(vertx, 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
                            vertx.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:org.vertx.java.core.net.impl.DefaultNetSocket.java

License:Open Source License

@Override
public NetSocket ssl(final Handler<Void> handler) {
    SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
    if (sslHandler == null) {
        sslHandler = helper.createSslHandler(vertx, client);
        channel.pipeline().addFirst(sslHandler);
    }//from   ww w.  j  a va  2 s .  com
    sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {
            if (context.isOnCorrectWorker(channel.eventLoop())) {
                if (future.isSuccess()) {
                    try {
                        vertx.setContext(context);
                        handler.handle(null);
                    } catch (Throwable t) {
                        context.reportException(t);
                    }
                } else {
                    context.reportException(future.cause());
                }

            } else {
                context.execute(new Runnable() {
                    public void run() {
                        if (future.isSuccess()) {
                            handler.handle(null);
                        } else {
                            context.reportException(future.cause());
                        }
                    }
                });
            }
        }
    });
    return this;
}

From source file:org.vertx.java.core.net.impl.VertxEventLoopGroup.java

License:Open Source License

@Override
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
    if (gracefulShutdown.compareAndSet(false, true)) {
        final AtomicInteger counter = new AtomicInteger(workers.size());
        for (EventLoopHolder holder : workers) {
            holder.worker.shutdownGracefully().addListener(new GenericFutureListener() {
                @Override//  www.j a  va 2  s . c  om
                public void operationComplete(Future future) throws Exception {
                    if (counter.decrementAndGet() == 0) {
                        terminationFuture.setSuccess(null);
                    }
                }
            });
        }
    }
    return terminationFuture;
}

From source file:org.waarp.common.crypto.ssl.WaarpSslUtility.java

License:Open Source License

/**
 * Add a SslHandler in a pipeline when the channel is already active
 * // w w w. jav  a 2  s. c om
 * @param future
 *            might be null, condition to start to add the handler to the pipeline
 * @param pipeline
 * @param sslHandler
 * @param listener
 *            action once the handshake is done
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void addSslHandler(ChannelFuture future, final ChannelPipeline pipeline,
        final ChannelHandler sslHandler,
        final GenericFutureListener<? extends Future<? super Channel>> listener) {
    if (future == null) {
        logger.debug("Add SslHandler: " + pipeline.channel());
        pipeline.addFirst("SSL", sslHandler);
        ((SslHandler) sslHandler).handshakeFuture().addListener(listener);
    } else {
        future.addListener(new GenericFutureListener() {
            public void operationComplete(Future future) throws Exception {
                logger.debug("Add SslHandler: " + pipeline.channel());
                pipeline.addFirst("SSL", sslHandler);
                ((SslHandler) sslHandler).handshakeFuture().addListener(listener);
            }
        });
    }
    logger.debug("Checked Ssl Handler to be added: " + pipeline.channel());
}

From source file:org.waarp.common.crypto.ssl.WaarpSslUtility.java

License:Open Source License

/**
 * Remove the SslHandler (if any) cleanly
 * //from   w  ww  . ja  v a  2  s .c  o  m
 * @param future
 *            if not null, wait for this future to be done to removed the sslhandler
 * @param channel
 * @param close
 *            True to close the channel, else to only remove it
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void removingSslHandler(ChannelFuture future, final Channel channel, final boolean close) {
    if (channel.isActive()) {
        channel.config().setAutoRead(true);
        ChannelHandler handler = channel.pipeline().first();
        if (handler instanceof SslHandler) {
            final SslHandler sslHandler = (SslHandler) handler;
            if (future != null) {
                future.addListener(new GenericFutureListener() {
                    public void operationComplete(Future future) throws Exception {
                        logger.debug("Found SslHandler and wait for Ssl.close()");
                        sslHandler.close().addListener(new GenericFutureListener<Future<? super Void>>() {
                            public void operationComplete(Future<? super Void> future) throws Exception {
                                logger.debug("Ssl closed");
                                if (!close) {
                                    channel.pipeline().remove(sslHandler);
                                } else {
                                    channel.close();
                                }
                            }
                        });
                    }
                });
            } else {
                logger.debug("Found SslHandler and wait for Ssl.close() : " + channel);
                sslHandler.close().addListener(new GenericFutureListener<Future<? super Void>>() {
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        logger.debug("Ssl closed: " + channel);
                        if (!close) {
                            channel.pipeline().remove(sslHandler);
                        } else {
                            channel.close();
                        }
                    }
                });
            }
        } else {
            channel.close();
        }
    }
}

From source file:org.waarp.ftp.core.control.NetworkHandler.java

License:Open Source License

/**
 * Execute one command and write the following answer
 *///from ww w.  java 2  s  .  c  o  m
private void messageRunAnswer(final ChannelHandlerContext ctx) {
    boolean error = false;
    logger.debug("Code: " + session.getCurrentCommand().getCode());
    try {
        businessHandler.beforeRunCommand();
        AbstractCommand command = session.getCurrentCommand();
        logger.debug("Run {}", command.getCommand());
        command.exec();
        businessHandler.afterRunCommandOk();
    } catch (CommandAbstractException e) {
        logger.debug("Command in error", e);
        error = true;
        session.setReplyCode(e);
        businessHandler.afterRunCommandKo(e);
    }
    logger.debug("Code: " + session.getCurrentCommand().getCode() + " [" + session.getReplyCode() + "]");
    if (error) {
        if (session.getCurrentCommand().getCode() != FtpCommandCode.INTERNALSHUTDOWN) {
            writeFinalAnswer(ctx);
        }
        // In error so Check that Data is closed
        if (session.getDataConn().isActive()) {
            logger.debug("Closing DataChannel while command is in error");
            try {
                session.getDataConn().getCurrentDataChannel().close();
            } catch (FtpNoConnectionException e) {
                // ignore
            }
        }
        return;
    }
    if (session.getCurrentCommand().getCode() == FtpCommandCode.AUTH
            || session.getCurrentCommand().getCode() == FtpCommandCode.CCC) {
        controlChannel.config().setAutoRead(false);
        ChannelFuture future = writeIntermediateAnswer(ctx);
        session.setCurrentCommandFinished();
        if (session.getCurrentCommand().getCode() == FtpCommandCode.AUTH) {
            logger.debug("SSL to be added to pipeline");
            ChannelHandler sslHandler = ctx.pipeline().first();
            if (sslHandler instanceof SslHandler) {
                logger.debug("Already got a SslHandler");
            } else {
                logger.debug("Add Explicitely SSL support to Command");
                // add the SSL support
                sslHandler = FtpsInitializer.waarpSslContextFactory.initInitializer(true,
                        FtpsInitializer.waarpSslContextFactory.needClientAuthentication());
                session.prepareSsl();
                WaarpSslUtility.addSslHandler(future, ctx.pipeline(), sslHandler,
                        new GenericFutureListener<Future<? super Channel>>() {
                            public void operationComplete(Future<? super Channel> future) throws Exception {
                                logger.debug("Handshake: " + future.isSuccess() + ":"
                                        + ((Channel) future.get()).toString(), future.cause());
                                if (!future.isSuccess()) {
                                    String error2 = future.cause() != null ? future.cause().getMessage()
                                            : "During Handshake";
                                    logger.error("Cannot finalize Ssl Command channel " + error2);
                                    callForSnmp("SSL Connection Error", error2);
                                    session.setSsl(false);
                                    ctx.close();
                                } else {
                                    logger.debug("End of initialization of SSL and command channel: "
                                            + ctx.channel());
                                    session.setSsl(true);
                                }
                            }
                        });
            }
        } else if (session.getCurrentCommand().getCode() == FtpCommandCode.CCC) {
            logger.debug("SSL to be removed from pipeline");
            // remove the SSL support
            session.prepareSsl();
            WaarpSslUtility.removingSslHandler(future, controlChannel, false);
        }
    } else if (session.getCurrentCommand().getCode() != FtpCommandCode.INTERNALSHUTDOWN) {
        writeFinalAnswer(ctx);
    }
}

From source file:org.waarp.ftp.core.data.FtpTransferControl.java

License:Open Source License

/**
 * Run the command from an executor//from   w  w  w  .  j a  v a  2 s.co m
 */
private void runExecutor() {
    final WaarpFuture toFinish = commandFinishing;
    endOfCommand = new WaarpFuture(true);
    final WaarpFuture toCommand = endOfCommand;
    try {
        session.getDataConn().getCurrentDataChannel().closeFuture()
                .addListener(new GenericFutureListener<Future<? super Void>>() {
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        if (!toFinish.isDone() || !toCommand.isDone()) {
                            logger.debug("Schedule to finish command: " + session + ":" + toFinish.isDone()
                                    + ":" + toCommand.isDone());
                            scheduleService.schedule(new Runnable() {
                                public void run() {
                                    if (!toFinish.isDone() || !toCommand.isDone()) {
                                        logger.warn("Will try to finish command: " + session
                                                + " CommandFinishing:" + toFinish.isDone() + " EndOfCommand:"
                                                + toCommand.isDone());
                                        toFinish.cancel();
                                    }
                                }
                            }, FtpConfiguration.DATATIMEOUTCON * 2, TimeUnit.MILLISECONDS);
                        }
                    }
                });
    } catch (FtpNoConnectionException e1) {
        //e1.printStackTrace();
    }
    // Run the command
    if (executorService == null) {
        executorService = Executors.newSingleThreadExecutor();
    }
    executorService.execute(new FtpTransferExecutor(session, executingCommand));
    try {
        commandFinishing.await();
        if (commandFinishing.isFailed()) {
            endOfCommand.cancel();
        }
    } catch (InterruptedException e) {
    }
}