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.apache.qpid.jms.transports.netty.NettySslTransport.java

License:Apache License

@Override
protected void handleConnected(final Channel channel) throws Exception {
    SslHandler sslHandler = channel.pipeline().get(SslHandler.class);

    Future<Channel> channelFuture = sslHandler.handshakeFuture();
    channelFuture.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override//from w  ww. j a  v a2s .  c o m
        public void operationComplete(Future<Channel> future) throws Exception {
            if (future.isSuccess()) {
                LOG.trace("SSL Handshake has completed: {}", channel);
                connectionEstablished(channel);
            } else {
                LOG.trace("SSL Handshake has failed: {}", channel);
                connectionFailed(IOExceptionSupport.create(future.cause()));
            }
        }
    });
}

From source file:org.apache.spark.sql.hive.thriftserver.rsc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *///from   w w  w .  j  a  v a 2s .  c  o  m
public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port,
        final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:org.artJava.chat.SecureChatServerHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {//

    //       System.out.println("channelactive!");

    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ////from ww w .j  a  va  2 s  .  c  o m
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName()
                            + " secure chat service!\n");
                    ctx.writeAndFlush("Your session is protected by "
                            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                            + " cipher suite.\n");

                    channels.add(ctx.channel());
                }
            });
}

From source file:org.asynchttpclient.providers.netty.request.NettyConnectListener.java

License:Apache License

public void onFutureSuccess(final Channel channel) throws ConnectException {
    Channels.setDefaultAttribute(channel, future);
    final HostnameVerifier hostnameVerifier = config.getHostnameVerifier();
    final SslHandler sslHandler = Channels.getSslHandler(channel);
    if (hostnameVerifier != null && sslHandler != null) {
        final String host = future.getURI().getHost();
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            @Override//from   w w w .j ava  2s  . c om
            public void operationComplete(Future<? super Channel> handshakeFuture) throws Exception {
                if (handshakeFuture.isSuccess()) {
                    Channel channel = (Channel) handshakeFuture.getNow();
                    SSLEngine engine = sslHandler.engine();
                    SSLSession session = engine.getSession();

                    LOGGER.debug("onFutureSuccess: session = {}, id = {}, isValid = {}, host = {}",
                            session.toString(), Base64.encode(session.getId()), session.isValid(), host);
                    if (!hostnameVerifier.verify(host, session)) {
                        ConnectException exception = new ConnectException("HostnameVerifier exception");
                        future.abort(exception);
                        throw exception;
                    } else {
                        requestSender.writeRequest(future, channel);
                    }
                }
            }
        });
    } else {
        requestSender.writeRequest(future, channel);
    }
}

From source file:org.asynchttpclient.providers.netty4.request.NettyConnectListener.java

License:Open Source License

private void onFutureSuccess(final Channel channel) throws ConnectException {
    Channels.setAttribute(channel, future);
    final HostnameVerifier hostnameVerifier = config.getHostnameVerifier();
    final SslHandler sslHandler = ChannelManager.getSslHandler(channel.pipeline());
    if (hostnameVerifier != null && sslHandler != null) {
        final String host = future.getUri().getHost();
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            @Override//ww  w .  j ava2s .  c  o m
            public void operationComplete(Future<? super Channel> handshakeFuture) throws Exception {
                if (handshakeFuture.isSuccess()) {
                    Channel channel = (Channel) handshakeFuture.getNow();
                    SSLEngine engine = sslHandler.engine();
                    SSLSession session = engine.getSession();

                    LOGGER.debug("onFutureSuccess: session = {}, id = {}, isValid = {}, host = {}",
                            session.toString(), Base64.encode(session.getId()), session.isValid(), host);
                    if (hostnameVerifier.verify(host, session)) {
                        final AsyncHandler<T> asyncHandler = future.getAsyncHandler();
                        if (asyncHandler instanceof AsyncHandlerExtensions)
                            AsyncHandlerExtensions.class.cast(asyncHandler).onSslHandshakeCompleted();

                        writeRequest(channel);
                    } else {
                        onFutureFailure(channel, new ConnectException("HostnameVerifier exception"));
                    }
                } else {
                    onFutureFailure(channel, handshakeFuture.cause());
                }
            }
        });
    } else {
        writeRequest(channel);
    }
}

From source file:org.eclipse.californium.elements.tcp.TcpClientConnector.java

License:Open Source License

@Override
public void send(final RawData msg) {
    if (msg == null) {
        throw new NullPointerException("Message must not be null");
    }//from  www. jav  a2  s .c  o  m
    if (msg.isMulticast()) {
        LOGGER.warn("TcpConnector drops {} bytes to multicast {}:{}", msg.getSize(), msg.getAddress(),
                msg.getPort());
        msg.onError(new MulticastNotSupportedException("TCP doesn't support multicast!"));
        return;
    }
    if (workerGroup == null) {
        msg.onError(new IllegalStateException("TCP client connector not running!"));
        return;
    }
    InetSocketAddress addressKey = msg.getInetSocketAddress();
    final boolean connected = poolMap.contains(addressKey);
    final EndpointContextMatcher endpointMatcher = getEndpointContextMatcher();
    /* check, if a new connection should be established */
    if (endpointMatcher != null && !connected && !endpointMatcher.isToBeSent(msg.getEndpointContext(), null)) {
        LOGGER.warn("TcpConnector drops {} bytes to new {}:{}", msg.getSize(), msg.getAddress(), msg.getPort());
        msg.onError(new EndpointMismatchException("no connection"));
        return;
    }
    if (!connected) {
        msg.onConnecting();
    }
    final ChannelPool channelPool = poolMap.get(addressKey);
    Future<Channel> acquire = channelPool.acquire();
    acquire.addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(Future<Channel> future) throws Exception {
            Throwable cause = null;
            if (future.isSuccess()) {
                Channel channel = future.getNow();
                try {
                    send(channel, endpointMatcher, msg);
                } catch (Throwable t) {
                    cause = t;
                } finally {
                    try {
                        channelPool.release(channel);
                    } catch (RejectedExecutionException e) {
                        LOGGER.debug("{}", e.getMessage());
                    }
                }
            } else if (future.isCancelled()) {
                cause = new CancellationException();
            } else {
                cause = future.cause();
            }
            if (cause != null) {
                if (cause instanceof ConnectTimeoutException) {
                    LOGGER.warn("{}", cause.getMessage());
                } else if (cause instanceof CancellationException) {
                    LOGGER.debug("{}", cause.getMessage());
                } else {
                    LOGGER.warn("Unable to open connection to {}", msg.getAddress(), future.cause());
                }
                msg.onError(future.cause());
            }
        }
    });
}

From source file:org.eclipse.californium.elements.tcp.TcpClientConnector.java

License:Open Source License

/**
 * Send message with acquired channel./*from  ww w .j  a v  a2s  . c  om*/
 * 
 * Intended to be overridden, if message sending should be delayed to
 * complete a TLS handshake.
 * 
 * @param channel acquired channel
 * @param endpointMatcher endpoint matcher
 * @param msg message to be send
 */
protected void send(final Channel channel, final EndpointContextMatcher endpointMatcher, final RawData msg) {
    EndpointContext context = contextUtil.buildEndpointContext(channel);
    /*
     * check, if the message should be sent with the established connection
     */
    if (endpointMatcher != null && !endpointMatcher.isToBeSent(msg.getEndpointContext(), context)) {
        LOGGER.warn("TcpConnector drops {} bytes to {}:{}", msg.getSize(), msg.getAddress(), msg.getPort());
        msg.onError(new EndpointMismatchException());
        return;
    }
    msg.onContextEstablished(context);
    ChannelFuture channelFuture = channel.writeAndFlush(Unpooled.wrappedBuffer(msg.getBytes()));
    channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                msg.onSent();
            } else if (future.isCancelled()) {
                msg.onError(new CancellationException());
            } else {
                LOGGER.warn("TcpConnector drops {} bytes to {}:{} caused by", msg.getSize(), msg.getAddress(),
                        msg.getPort(), future.cause());
                msg.onError(future.cause());
            }
        }
    });
}

From source file:org.eclipse.californium.elements.tcp.TcpServerConnector.java

License:Open Source License

@Override
public void send(final RawData msg) {
    if (msg == null) {
        throw new NullPointerException("Message must not be null");
    }//from w  w  w  . j  a v  a  2 s . c  o m
    if (msg.isMulticast()) {
        LOGGER.warn("TcpConnector drops {} bytes to multicast {}:{}", msg.getSize(), msg.getAddress(),
                msg.getPort());
        msg.onError(new MulticastNotSupportedException("TCP doesn't support multicast!"));
        return;
    }
    if (bossGroup == null) {
        msg.onError(new IllegalStateException("TCP server connector not running!"));
        return;
    }
    Channel channel = activeChannels.get(msg.getInetSocketAddress());
    if (channel == null) {
        // TODO: Is it worth allowing opening a new connection when in server mode?
        LOGGER.debug("Attempting to send message to an address without an active connection {}",
                msg.getAddress());
        msg.onError(new EndpointUnconnectedException());
        return;
    }
    EndpointContext context = contextUtil.buildEndpointContext(channel);
    final EndpointContextMatcher endpointMatcher = getEndpointContextMatcher();
    /* check, if the message should be sent with the established connection */
    if (null != endpointMatcher && !endpointMatcher.isToBeSent(msg.getEndpointContext(), context)) {
        LOGGER.warn("TcpConnector drops {} bytes to {}:{}", msg.getSize(), msg.getAddress(), msg.getPort());
        msg.onError(new EndpointMismatchException());
        return;
    }

    msg.onContextEstablished(context);
    ChannelFuture channelFuture = channel.writeAndFlush(Unpooled.wrappedBuffer(msg.getBytes()));
    channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                msg.onSent();
            } else if (future.isCancelled()) {
                msg.onError(new CancellationException());
            } else {
                msg.onError(future.cause());
            }
        }
    });
}

From source file:org.eclipse.californium.elements.tcp.TlsClientConnector.java

License:Open Source License

/**
 * {@inheritDoc}/*from ww w. j  a  v  a 2 s . c o m*/
 * 
 * Delay message sending after TLS handshake is completed.
 */
@Override
protected void send(final Channel channel, final EndpointContextMatcher endpointMatcher, final RawData msg) {
    final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
    if (sslHandler == null) {
        msg.onError(new IllegalStateException("Missing SslHandler"));
    } else {
        /*
         * Trigger handshake.
         */
        Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
        handshakeFuture.addListener(new GenericFutureListener<Future<Channel>>() {

            @Override
            public void operationComplete(Future<Channel> future) throws Exception {
                if (future.isSuccess()) {
                    EndpointContext context = contextUtil.buildEndpointContext(channel);
                    if (context == null || context.get(TlsEndpointContext.KEY_SESSION_ID) == null) {
                        msg.onError(new IllegalStateException("Missing TlsEndpointContext " + context));
                        return;
                    }
                    /*
                     * Handshake succeeded! 
                     * Call super.send() to actually send the message.
                     */
                    TlsClientConnector.super.send(future.getNow(), endpointMatcher, msg);
                } else if (future.isCancelled()) {
                    msg.onError(new CancellationException());
                } else {
                    msg.onError(future.cause());
                }
            }
        });
    }
}

From source file:org.eclipse.moquette.spi.impl.ProtocolProcessor.java

License:Open Source License

/**
 * ?token/*w w  w. j  a va  2s .com*/
 *
 * @param session
 * @param name
 * @param pwd
 * @param clientID
 */
private void authAsync(final ServerChannel session, final String name, final String pwd,
        final String clientID) {
    //??token
    //username?token
    Future<Boolean> f = taskExecutors.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return m_authenticator.checkValid(name, pwd, clientID);
        }
    });

    f.addListener(new GenericFutureListener<Future<Boolean>>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            boolean pass = future.getNow();
            if (!pass) {
                authFail(session);
            }
        }
    });
}