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

boolean awaitUninterruptibly(long timeout, TimeUnit unit);

Source Link

Document

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

Usage

From source file:io.dyn.net.tcp.TcpClient.java

License:Apache License

@SuppressWarnings({ "unchecked" })
@Override//w  w  w  . j  av a2s.  co  m
public T start() {
    if (!started.get()) {
        on(Lifecycle.STOP, new CompletionHandler() {
            @Override
            protected void complete() {
                if (channelFuture.awaitUninterruptibly(15, TimeUnit.SECONDS)) {
                    channelFuture.getChannel().close();
                }
                started.set(false);
            }
        });
        bootstrap.setOption("child.keepAlive", keepAlive);
        bootstrap.setOption("child.receiveBufferSize", Buffer.SMALL_BUFFER_SIZE);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                final ChannelPipeline pipeline = Channels.pipeline();
                TcpClient.this.configurePipeline(pipeline);
                return pipeline;
            }
        });

        try {
            channelFuture = bootstrap.connect(new InetSocketAddress(InetAddress.getByName(host), port));
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        started.set(true);
                        event(Lifecycle.START);
                    } else {
                        Throwable t = channelFuture.getCause();
                        event(Events.classToEventExpression(t.getClass()), t);
                    }
                }
            });
        } catch (UnknownHostException e) {
            event(Events.classToEventExpression(e.getClass()), e);
        }
    }
    return (T) this;
}

From source file:net.petercashel.nettyCore.client.clientCore.java

License:Apache License

/**
 * Initializes a Client Connection//  w w w  . j  a v a2s  .  co m
 * 
 * @param addr
 *            - String address to connect to
 * @param port
 *            - int Port number to connect to
 * @throws Exception
 */
public static void initializeConnection(final String addr, final int port) throws Exception {
    _host = addr;
    _port = port;
    PacketRegistry.setupRegistry();
    PacketRegistry.Side = side;
    if (UseSSL)
        SSLContextProvider.SetupSSL();

    group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast("readTimeoutHandler", new ReadTimeoutHandler(300));
                if (UseSSL && !SSLContextProvider.selfSigned)
                    p.addLast("ssl", getClientSSLHandler(addr, port));
                if (UseSSL && SSLContextProvider.selfSigned)
                    p.addLast("ssl", SSLContextProvider.getSelfClient().newHandler(ch.alloc(), addr, port));
                p.addLast("InboundOutboundClientHandler", new ClientConnectionHander());
            }
        });

        // Make the connection attempt.
        ChannelFuture f = b.connect(addr, port).sync();
        f.awaitUninterruptibly(2000, TimeUnit.MILLISECONDS);

        if (!f.isSuccess())
            throw new RuntimeException("Failed to connect");
        // if a wait option was selected and the connect did not fail,
        // the Date can now be sent.
        System.out.println("Client Core Connected!");
        connection = f.channel();
        connClosed = false;
        // Initiate the Ping->Pong->PingPong Packet test.
        PacketRegistry.pack(new PingPacket())
                .sendPacket(connection.pipeline().context("InboundOutboundClientHandler"));

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
        System.out.println("Connection Closed");
        connClosed = true;
    }
}

From source file:net.petercashel.nettyCore.clientUDS.clientCoreUDS.java

License:Apache License

public static void initializeConnection(File socket) throws Exception {
    PacketRegistry.setupRegistry();//w  w  w  .  j  a v a2 s . co  m
    PacketRegistry.Side = side;

    group = new EpollEventLoopGroup();
    try {
        Bootstrap b = new BootstrapFactory<Bootstrap>() {
            @Override
            public Bootstrap newInstance() {
                return new Bootstrap().group(group).channel(EpollDomainSocketChannel.class)
                        .handler(new ChannelInitializer<EpollDomainSocketChannel>() {
                            @Override
                            protected void initChannel(EpollDomainSocketChannel ch) throws Exception {
                                ChannelPipeline p = ch.pipeline();
                                p.addLast("InboundOutboundClientHandler", new ClientUDSConnectionHander());
                            }
                        });
            }
        }.newInstance();

        // Make the connection attempt.
        ChannelFuture f = b.connect(newSocketAddress(socket)).sync();
        f.awaitUninterruptibly(2000, TimeUnit.MILLISECONDS);

        if (!f.isSuccess())
            throw new RuntimeException("Failed to connect");
        // if a wait option was selected and the connect did not fail,
        // the Date can now be sent.
        System.out.println("Client UDS Connected!");
        connection = f.channel();
        connClosed = false;

        // Send GetHistoryPacket
        PacketRegistry.pack(new GetHistoryPacket()).sendPacket(connection);

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
        System.out.println("Connection Closed");
        connClosed = true;
    }
}

From source file:org.apache.dubbo.remoting.transport.netty4.NettyClient.java

License:Apache License

@Override
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try {/*  w  ww  .  j a  v  a  2  s .  co  m*/
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), MILLISECONDS);

        if (ret && future.isSuccess()) {
            Channel newChannel = future.channel();
            try {
                // Close old channel
                // copy reference
                Channel oldChannel = NettyClient.this.channel;
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel
                                    + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info(
                                    "Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.cause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.cause().getMessage(), future.cause());
        } else {
            throw new RemotingException(this,
                    "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress()
                            + " client-side timeout " + getConnectTimeout() + "ms (elapsed: "
                            + (System.currentTimeMillis() - start) + "ms) from netty client "
                            + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    } finally {
        // just add new valid channel to NettyChannel's cache
        if (!isConnected()) {
            //future.cancel(true);
        }
    }
}

From source file:org.ballerinalang.test.util.http2.HTTP2ResponseHandler.java

License:Open Source License

/**
 * Provide asynchronous response to HTTP2 request.
 *
 * @param streamId StreamID/*from   ww  w  .  j  a  va2 s.c o  m*/
 * @return Response string
 */
public FullHttpResponse getResponse(int streamId) {

    FullHttpResponse message = streamIdResponseMap.get(streamId);
    if (message != null) {
        return message;
    } else {
        Entry<ChannelFuture, ChannelPromise> channelFutureChannelPromiseEntry = streamIdPromiseMap
                .get(streamId);
        if (channelFutureChannelPromiseEntry != null) {
            ChannelFuture writeFuture = channelFutureChannelPromiseEntry.getKey();
            if (!writeFuture.awaitUninterruptibly(TestConstant.HTTP2_RESPONSE_TIME_OUT,
                    TestConstant.HTTP2_RESPONSE_TIME_UNIT)) {
                streamIdPromiseMap.remove(streamId);
                throw new IllegalStateException("Timed out waiting to write for stream id " + streamId);
            }
            if (!writeFuture.isSuccess()) {
                streamIdPromiseMap.remove(streamId);
                throw new RuntimeException(writeFuture.cause());
            }
            ChannelPromise promise = channelFutureChannelPromiseEntry.getValue();
            if (!promise.awaitUninterruptibly(TestConstant.HTTP2_RESPONSE_TIME_OUT,
                    TestConstant.HTTP2_RESPONSE_TIME_UNIT)) {
                streamIdPromiseMap.remove(streamId);
                throw new IllegalStateException("Timed out waiting for response on stream id " + streamId);
            }
            if (!promise.isSuccess()) {
                streamIdPromiseMap.remove(streamId);
                throw new RuntimeException(promise.cause());
            }
        }
    }
    return streamIdResponseMap.get(streamId);
}

From source file:org.freeswitch.esl.client.inbound.Client.java

License:Apache License

/**
 * Attempt to establish an authenticated connection to the nominated FreeSWITCH ESL server socket.
 * This call will block, waiting for an authentication handshake to occur, or timeout after the
 * supplied number of seconds./*  ww w.j  av  a  2 s. c  om*/
 *
 * @param clientAddress  a SocketAddress representing the endpoint to connect to
 * @param password       server event socket is expecting (set in event_socket_conf.xml)
 * @param timeoutSeconds number of seconds to wait for the server socket before aborting
 */
public void connect(SocketAddress clientAddress, String password, int timeoutSeconds)
        throws InboundConnectionFailure {
    // If already connected, disconnect first
    if (canSend()) {
        close();
    }

    log.info("Connecting to {} ...", clientAddress);

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    // Configure this client
    Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true);

    // Add ESL handler and factory
    InboundClientHandler handler = new InboundClientHandler(password, protocolListener);
    bootstrap.handler(new InboundChannelInitializer(handler));

    // Attempt connection
    ChannelFuture future = bootstrap.connect(clientAddress);

    // Wait till attempt succeeds, fails or timeouts
    if (!future.awaitUninterruptibly(timeoutSeconds, TimeUnit.SECONDS)) {
        throw new InboundConnectionFailure("Timeout connecting to " + clientAddress);
    }
    // Did not timeout
    final Channel channel = future.channel();
    // But may have failed anyway
    if (!future.isSuccess()) {
        log.warn("Failed to connect to [{}]", clientAddress, future.cause());

        workerGroup.shutdownGracefully();

        throw new InboundConnectionFailure("Could not connect to " + clientAddress, future.cause());
    }

    log.info("Connected to {}", clientAddress);

    //  Wait for the authentication handshake to call back
    while (!authenticatorResponded.get()) {
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            // ignore
        }
    }

    this.clientContext = Optional.of(new Context(channel, handler));

    if (!authenticated) {
        throw new InboundConnectionFailure("Authentication failed: " + authenticationResponse.getReplyText());
    }

    log.info("Authenticated");
}

From source file:org.infinispan.rest.http2.HttpResponseHandler.java

License:Apache License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
 */// w w  w  . jav  a 2  s. c o  m
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        itr.remove();
    }
}

From source file:org.wso2.carbon.transport.http.netty.util.client.http2.HTTP2ResponseHandler.java

License:Open Source License

/**
 * Provide asynchronous response to HTTP2 request
 *
 * @param streamId StreamID//  w  w  w .  j ava2 s.  c o m
 * @return Response string
 */
public String getResponse(int streamId) {

    String message = streamIdResponseMap.get(streamId);
    if (message != null) {
        return message;
    } else {
        Entry<ChannelFuture, ChannelPromise> channelFutureChannelPromiseEntry = streamIdPromiseMap
                .get(streamId);
        if (channelFutureChannelPromiseEntry != null) {
            ChannelFuture writeFuture = channelFutureChannelPromiseEntry.getKey();
            if (!writeFuture.awaitUninterruptibly(TestUtil.HTTP2_RESPONSE_TIME_OUT,
                    TestUtil.HTTP2_RESPONSE_TIME_UNIT)) {
                streamIdPromiseMap.remove(streamId);
                throw new IllegalStateException("Timed out waiting to write for stream id " + streamId);
            }
            if (!writeFuture.isSuccess()) {
                streamIdPromiseMap.remove(streamId);
                throw new RuntimeException(writeFuture.cause());
            }
            ChannelPromise promise = channelFutureChannelPromiseEntry.getValue();
            if (!promise.awaitUninterruptibly(TestUtil.HTTP2_RESPONSE_TIME_OUT,
                    TestUtil.HTTP2_RESPONSE_TIME_UNIT)) {
                streamIdPromiseMap.remove(streamId);
                throw new IllegalStateException("Timed out waiting for response on stream id " + streamId);
            }
            if (!promise.isSuccess()) {
                streamIdPromiseMap.remove(streamId);
                throw new RuntimeException(promise.cause());
            }
        }
    }
    return streamIdResponseMap.get(streamId);
}

From source file:org.wso2.esb.integration.common.utils.clients.http2client.HttpResponseHandler.java

License:Open Source License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
 *///  w ww. j a  va2 s .c  o  m
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        log.debug("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }
}