Example usage for io.netty.util.concurrent Future awaitUninterruptibly

List of usage examples for io.netty.util.concurrent Future awaitUninterruptibly

Introduction

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

Prototype

boolean awaitUninterruptibly(long timeoutMillis);

Source Link

Document

Waits for this future to be completed within the specified time limit without interruption.

Usage

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }/*  w  ww  .ja v a  2s  .  co m*/

    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()),
                        ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }

    ActiveMQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination);

    ChannelFuture future;
    //port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }

    future.awaitUninterruptibly();

    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }

        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                //get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                URI uri = new URI("http", null, host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                        uri.getRawPath());
                request.headers().set(HttpHeaders.Names.HOST, host);
                request.headers().set(HttpHeaders.Names.UPGRADE, ACTIVEMQ_REMOTING);
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);

                final String endpoint = ConfigurationHelper.getStringProperty(
                        TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }

                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);

                ActiveMQClientLogger.LOGGER.debugf("Sending HTTP request %s", request);

                // Send the HTTP request.
                ch.writeAndFlush(request);

                if (!httpUpgradeHandler.awaitHandshake()) {
                    return null;
                }
            } catch (URISyntaxException e) {
                ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
            channelHandler.active = true;
        }

        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener,
                !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, protocolManager.getName());
        return conn;
    } else {
        Throwable t = future.cause();

        if (t != null && !(t instanceof ConnectException)) {
            ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }

        return null;
    }
}

From source file:org.apache.activemq.transport.netty.NettyTcpTransport.java

License:Apache License

@Override
public void connect() throws IOException {

    if (listener == null) {
        throw new IllegalStateException("A transport listener must be set before connection attempts.");
    }//from  w w  w. jav a 2  s  .c o m

    final SslHandler sslHandler;
    if (isSSL()) {
        try {
            sslHandler = NettyTransportSupport.createSslHandler(getRemoteLocation(), getSslOptions());
        } catch (Exception ex) {
            // TODO: can we stop it throwing Exception?
            throw IOExceptionSupport.create(ex);
        }
    } else {
        sslHandler = null;
    }

    group = new NioEventLoopGroup(1);

    bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel connectedChannel) throws Exception {
            configureChannel(connectedChannel, sslHandler);
        }
    });

    configureNetty(bootstrap, getTransportOptions());

    ChannelFuture future = bootstrap.connect(getRemoteHost(), getRemotePort());
    future.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                handleException(future.channel(), IOExceptionSupport.create(future.cause()));
            }
        }
    });

    try {
        connectLatch.await();
    } catch (InterruptedException ex) {
        LOG.debug("Transport connection was interrupted.");
        Thread.interrupted();
        failureCause = IOExceptionSupport.create(ex);
    }

    if (failureCause != null) {
        // Close out any Netty resources now as they are no longer needed.
        if (channel != null) {
            channel.close().syncUninterruptibly();
            channel = null;
        }
        if (group != null) {
            Future<?> fut = group.shutdownGracefully(0, SHUTDOWN_TIMEOUT, TimeUnit.MILLISECONDS);
            if (!fut.awaitUninterruptibly(2 * SHUTDOWN_TIMEOUT)) {
                LOG.trace("Channel group shutdown failed to complete in allotted time");
            }
            group = null;
        }

        throw failureCause;
    } else {
        // Connected, allow any held async error to fire now and close the transport.
        channel.eventLoop().execute(new Runnable() {

            @Override
            public void run() {
                if (failureCause != null) {
                    channel.pipeline().fireExceptionCaught(failureCause);
                }
            }
        });
    }
}

From source file:org.apache.activemq.transport.netty.NettyTcpTransport.java

License:Apache License

@Override
public void close() throws IOException {
    if (closed.compareAndSet(false, true)) {
        connected.set(false);// w  ww  .  j  a va 2  s .c om
        try {
            if (channel != null) {
                channel.close().syncUninterruptibly();
            }
        } finally {
            if (group != null) {
                Future<?> fut = group.shutdownGracefully(0, SHUTDOWN_TIMEOUT, TimeUnit.MILLISECONDS);
                if (!fut.awaitUninterruptibly(2 * SHUTDOWN_TIMEOUT)) {
                    LOG.trace("Channel group shutdown failed to complete in allotted time");
                }
            }
        }
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.server.StandbyServer.java

License:Apache License

private void start(boolean wait) {
    if (running)/*from w w  w .j  a v  a  2  s. com*/
        return;

    this.handler.state = STATUS_STARTING;

    final Thread close = new Thread() {
        @Override
        public void run() {
            try {
                running = true;
                handler.state = STATUS_RUNNING;
                channelFuture.sync().channel().closeFuture().sync();
            } catch (InterruptedException e) {
                StandbyServer.this.stop();
            }
        }
    };
    final ChannelFutureListener bindListener = new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                close.start();
            } else {
                log.error("Server failed to start on port " + port + ", will be canceled", future.cause());
                future.channel().close();
                new Thread() {
                    @Override
                    public void run() {
                        close();
                    }
                }.start();
            }
        }
    };
    Future<?> startup = bossGroup.submit(new Runnable() {
        @Override
        public void run() {
            //netty 4.0.20 has a race condition issue with
            //asynchronous channel registration. As a workaround
            //we bind asynchronously from the boss event group to make
            //the channel registration synchronous.
            //Note that now this method will return immediately.
            channelFuture = b.bind(port);
            channelFuture.addListener(bindListener);
        }
    });
    if (!startup.awaitUninterruptibly(10000)) {
        log.error("Server failed to start within 10 seconds and will be canceled");
        startup.cancel(true);
    } else if (wait) {
        try {
            close.join();
        } catch (InterruptedException ignored) {
        }
    }
}

From source file:org.apache.qpid.jms.transports.netty.NettyTcpTransport.java

License:Apache License

@Override
public void connect(SSLContext sslContextOverride) throws IOException {

    if (listener == null) {
        throw new IllegalStateException("A transport listener must be set before connection attempts.");
    }/*from   w ww.j a  va 2  s.co  m*/

    final SslHandler sslHandler;
    if (isSecure()) {
        try {
            TransportSslOptions sslOptions = getSslOptions();
            sslOptions.setSslContextOverride(sslContextOverride);

            sslHandler = TransportSupport.createSslHandler(getRemoteLocation(), sslOptions);
        } catch (Exception ex) {
            // TODO: can we stop it throwing Exception?
            throw IOExceptionSupport.create(ex);
        }
    } else {
        sslHandler = null;
    }

    group = new NioEventLoopGroup(1);

    bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel connectedChannel) throws Exception {
            configureChannel(connectedChannel, sslHandler);
        }
    });

    configureNetty(bootstrap, getTransportOptions());

    ChannelFuture future = bootstrap.connect(getRemoteHost(), getRemotePort());
    future.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                handleException(future.channel(), IOExceptionSupport.create(future.cause()));
            }
        }
    });

    try {
        connectLatch.await();
    } catch (InterruptedException ex) {
        LOG.debug("Transport connection was interrupted.");
        Thread.interrupted();
        failureCause = IOExceptionSupport.create(ex);
    }

    if (failureCause != null) {
        // Close out any Netty resources now as they are no longer needed.
        if (channel != null) {
            channel.close().syncUninterruptibly();
            channel = null;
        }
        if (group != null) {
            Future<?> fut = group.shutdownGracefully(0, SHUTDOWN_TIMEOUT, TimeUnit.MILLISECONDS);
            if (!fut.awaitUninterruptibly(2 * SHUTDOWN_TIMEOUT)) {
                LOG.trace("Channel group shutdown failed to complete in allotted time");
            }
            group = null;
        }

        throw failureCause;
    } else {
        // Connected, allow any held async error to fire now and close the transport.
        channel.eventLoop().execute(new Runnable() {

            @Override
            public void run() {
                if (failureCause != null) {
                    channel.pipeline().fireExceptionCaught(failureCause);
                }
            }
        });
    }
}

From source file:org.hornetq.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }//from  www  .  j a  v a  2  s  . c  om

    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()),
                        ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }

    HornetQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination);

    ChannelFuture future;
    //port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }

    future.awaitUninterruptibly();

    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    HornetQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }

        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                //get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                URI uri = new URI("http", null, host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                        uri.getRawPath());
                request.headers().set(HttpHeaders.Names.HOST, host);
                request.headers().set(HttpHeaders.Names.UPGRADE, HORNETQ_REMOTING);
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);

                final String endpoint = ConfigurationHelper.getStringProperty(
                        TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }

                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_HORNETQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);

                HornetQClientLogger.LOGGER.debugf("Sending HTTP request %s", request);

                // Send the HTTP request.
                ch.writeAndFlush(request);

                if (!httpUpgradeHandler.awaitHandshake()) {
                    return null;
                }
            } catch (URISyntaxException e) {
                HornetQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
            channelHandler.active = true;
        }

        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener,
                !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, HornetQClient.DEFAULT_CORE_PROTOCOL);
        return conn;
    } else {
        Throwable t = future.cause();

        if (t != null && !(t instanceof ConnectException)) {
            HornetQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }

        return null;
    }
}