Example usage for io.netty.channel ChannelFuture awaitUninterruptibly

List of usage examples for io.netty.channel ChannelFuture awaitUninterruptibly

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture awaitUninterruptibly.

Prototype

@Override
    ChannelFuture awaitUninterruptibly();

Source Link

Usage

From source file:gash.router.server.queue.WorkOutboundAppWorker.java

License:Apache License

@Override
public void run() {
    Channel conn = sq.channel;/*from   ww  w. j a v a2  s  .  co m*/
    if (conn == null || !conn.isOpen()) {
        PerChannelWorkQueue.logger.error("connection missing, no outboundWork communication");
        return;
    }

    while (true) {
        if (!forever && sq.outbound.size() == 0)
            break;

        try {
            // block until a message is enqueued
            GeneratedMessage msg = sq.outbound.take();
            if (conn.isWritable()) {
                boolean rtn = false;
                if (sq.channel != null && sq.channel.isOpen() && sq.channel.isWritable()) {

                    ChannelFuture cf = sq.channel.writeAndFlush((Work.WorkRequest) msg);

                    logger.info("Server--sending -- work-- response");
                    // blocks on write - use listener to be async
                    cf.awaitUninterruptibly();
                    logger.debug("Written to channel");
                    rtn = cf.isSuccess();
                    if (!rtn) {
                        logger.error("Sending failed " + rtn + "{Reason:" + cf.cause() + "}");
                        sq.outbound.putFirst(msg);
                    } else
                        logger.info("Message Sent");
                }

            } else
                sq.outbound.putFirst(msg);
        } catch (InterruptedException ie) {
            break;
        } catch (Exception e) {
            logger.error("Unexpected communcation failure", e);
            break;
        }
    }

    if (!forever) {
        logger.debug("connection queue closing");
    }
}

From source file:io.horizondb.client.DefaultMsgChannel.java

License:Apache License

/**
  * {@inheritDoc}//from  w w w.  j a v a 2  s .co m
  */
@Override
public void sendRequest(Msg<?> request) {

    this.queue.clear();

    ChannelFuture future = this.channel.writeAndFlush(request);
    future.awaitUninterruptibly();

    if (!future.isSuccess()) {

        throw new HorizonDBException("", future.cause());
    }
}

From source file:object.client.ext.ObjectClient.java

private Channel connect() {
    try {/*from w  w  w.  j av a 2s  . co m*/
        //System.out.println("[connectioState] " + connectioState.name());
        //System.out.println("Try to Connect on : " + remotehost + ":" + port);
        CompletableFuture<Channel> futureResult = new CompletableFuture<>();
        ChannelFuture future = bootstrap.connect(remotehost, port);
        future.addListener((ChannelFutureListener) (ChannelFuture future1) -> {
            if (future1.isSuccess()) {
                futureResult.complete(future1.channel());
            } else {
                futureResult.completeExceptionally(new TryConnectException(remotehost, port));
            }
        });
        future.awaitUninterruptibly();
        return futureResult.join();
    } catch (Exception ex) {
        return null;
    }
}

From source file:org.acmsl.katas.antlr4netty.InterpreterServer.java

License:Open Source License

/**
 * Wraps given {@link ChannelFuture} to ensure the event loops
 * shut down gracefully.//w  w  w  . j a va 2  s  .co m
 * @param target the original channel future.
 * @param bossGroup the boss group.
 * @param workerGroup the worker group.
 * @return the wrapped future.
 */
@NotNull
protected ChannelFuture wrap(@NotNull final ChannelFuture target, @NotNull final NioEventLoopGroup bossGroup,
        @NotNull final NioEventLoopGroup workerGroup) {
    return new ChannelFuture() {
        @Override
        public Channel channel() {
            return target.channel();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.addListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.addListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.removeListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.removeListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture sync() throws InterruptedException {
            ChannelFuture result = null;

            try {
                result = target.sync();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }

            return result;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture syncUninterruptibly() {
            return target.syncUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture await() throws InterruptedException {
            return target.await();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture awaitUninterruptibly() {
            return target.awaitUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isSuccess() {
            return target.isSuccess();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancellable() {
            return target.isCancellable();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Throwable cause() {
            return target.cause();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException {
            return target.await(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeoutMillis) throws InterruptedException {
            return target.await(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeout, @NotNull final TimeUnit unit) {
            return target.awaitUninterruptibly(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeoutMillis) {
            return target.awaitUninterruptibly(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void getNow() {
            return target.getNow();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean cancel(final boolean mayInterruptIfRunning) {
            return target.cancel(mayInterruptIfRunning);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancelled() {
            return target.isCancelled();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isDone() {
            return target.isDone();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get() throws InterruptedException, ExecutionException {
            return target.get();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get(final long timeout, @NotNull final TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return target.get(timeout, unit);
        }
    };
}

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 2 s .com*/

    // 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.artemis.tests.integration.stomp.util.AbstractStompClientConnection.java

License:Apache License

private ClientStompFrame sendFrameInternal(ClientStompFrame frame, boolean wicked)
        throws IOException, InterruptedException {
    ClientStompFrame response = null;//from  w w w  .j  av  a  2  s . c o  m
    IntegrationTestLogger.LOGGER.trace("Sending " + (wicked ? "*wicked* " : "") + "frame:\n" + frame);
    ByteBuffer buffer;
    if (wicked) {
        buffer = frame.toByteBufferWithExtra("\n");
    } else {
        buffer = frame.toByteBuffer();
    }

    ByteBuf buf = Unpooled.copiedBuffer(buffer);

    try {
        buf.retain();
        ChannelFuture future = transport.send(buf);
        if (future != null) {
            future.awaitUninterruptibly();
        }
    } finally {
        buf.release();
    }

    //now response
    if (frame.needsReply()) {
        response = receiveFrame();

        //filter out server ping
        while (response != null) {
            if (response.getCommand().equals(Stomp.Commands.STOMP)) {
                response = receiveFrame();
            } else {
                break;
            }
        }
    }

    IntegrationTestLogger.LOGGER.trace("Received:\n" + response);

    return response;
}

From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java

License:Apache License

private void closeInternal(boolean permanent, boolean wait) {
    Channel toClose = null;//from  w ww .  ja  va 2  s . c o  m
    synchronized (this) {
        if (permanent) {
            state = ConnectionState.CLOSED;
        } else if (state != ConnectionState.CLOSED) {
            state = ConnectionState.DISCONNECTED;
        }
        toClose = channel;
        channel = null;
        makeWritable();
    }
    if (toClose != null) {
        ChannelFuture cf = closeChannel(toClose);
        if (wait) {
            cf.awaitUninterruptibly();
        }
    }
}

From source file:org.apache.camel.component.netty4.NettyProducer.java

License:Apache License

protected ChannelFuture openConnection() throws Exception {
    ChannelFuture answer;//  ww  w . j ava2 s .c o m

    if (isTcp()) {
        // its okay to create a new bootstrap for each new channel
        Bootstrap clientBootstrap = new Bootstrap();
        clientBootstrap.channel(NioSocketChannel.class);
        clientBootstrap.group(getWorkerGroup());
        clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
        clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
        clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
        clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            clientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        clientBootstrap.handler(pipelineFactory);
        answer = clientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                    new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap });
        }
        return answer;
    } else {
        // its okay to create a new bootstrap for each new channel
        Bootstrap connectionlessClientBootstrap = new Bootstrap();
        connectionlessClientBootstrap.channel(NioDatagramChannel.class);
        connectionlessClientBootstrap.group(getWorkerGroup());
        connectionlessClientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                configuration.getConnectTimeout());
        connectionlessClientBootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
        connectionlessClientBootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
        connectionlessClientBootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        connectionlessClientBootstrap.handler(pipelineFactory);
        // bind and store channel so we can close it when stopping
        ChannelFuture channelFuture = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
        channelFuture.awaitUninterruptibly();
        Channel channel = channelFuture.channel();
        allChannels.add(channel);
        answer = connectionlessClientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}", new Object[] {
                    configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap });
        }
        return answer;
    }
}

From source file:org.apache.camel.component.netty4.SingleTCPNettyServerBootstrapFactory.java

License:Apache License

@Override
protected void doResume() throws Exception {
    if (channel != null) {
        LOG.debug("ServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
        ChannelFuture future = channel
                .bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        future.awaitUninterruptibly();
        if (!future.isSuccess()) {
            // if we cannot bind, the re-create channel
            allChannels.remove(channel);
            future = serverBootstrap/*from  ww w  . j  a  va2  s  .  co m*/
                    .bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
            future.awaitUninterruptibly();
            channel = future.channel();
            allChannels.add(channel);
        }
    }
}

From source file:org.apache.camel.component.netty4.SingleTCPNettyServerBootstrapFactory.java

License:Apache License

@Override
protected void doSuspend() throws Exception {
    if (channel != null) {
        LOG.debug("ServerBootstrap unbinding from {}:{}", configuration.getHost(), configuration.getPort());
        //TODO need to check if it's good way to unbinding the channel
        ChannelFuture future = channel.close();
        future.awaitUninterruptibly();
    }/*  ww w.ja v a 2  s . c  o  m*/
}