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:be.yildizgames.module.network.netty.client.ClientNetty.java

License:MIT License

@Override
public void connectImpl(final String address, final int port) {
    LOGGER.info("Connecting to server {}:{}", address, port);
    ChannelFuture future = this.bootstrap.connect(new InetSocketAddress(address, port));
    if (!future.awaitUninterruptibly().isSuccess()) {
        this.connectionFailed();
        this.bootstrap.config().group().shutdownGracefully();
    } else {//from www  .j  av a  2s . co  m
        this.channel = future.channel();
        this.connectionComplete();
    }
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java

License:Apache License

public NettyClientServerCommunicationSystemClientSide(int clientId, ClientViewController controller) {
    super();// w w w . j  a  v a2s. c om

    this.clientId = clientId;
    this.workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    try {

        this.secretKeyFactory = TOMUtil.getSecretFactory();

        this.controller = controller;

        /* Tulio Ribeiro */
        privKey = controller.getStaticConf().getPrivateKey();

        this.listener = new SyncListener();
        this.rl = new ReentrantReadWriteLock();

        int[] currV = controller.getCurrentViewProcesses();

        for (int i = 0; i < currV.length; i++) {
            int replicaId = currV[i];
            try {

                ChannelFuture future = connectToReplica(replicaId, secretKeyFactory);

                logger.debug("ClientID {}, connecting to replica {}, at address: {}", clientId, replicaId,
                        controller.getRemoteAddress(replicaId));

                future.awaitUninterruptibly();

                if (!future.isSuccess()) {
                    logger.error("Impossible to connect to " + replicaId);
                }

            } catch (java.lang.NullPointerException ex) {
                // What is this??? This is not possible!!!
                logger.debug("Should fix the problem, and I think it has no other implications :-), "
                        + "but we must make the servers store the view in a different place.");
            } catch (Exception ex) {
                logger.error("Failed to initialize MAC engine", ex);
            }
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("Failed to initialize secret key factory", ex);
    }
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java

License:Apache License

@Override
public void updateConnections() {
    int[] currV = controller.getCurrentViewProcesses();
    try {//  www . ja  va  2 s.co  m
        // open connections with new servers
        for (int i = 0; i < currV.length; i++) {

            int replicaId = currV[i];

            rl.readLock().lock();
            if (sessionClientToReplica.get(replicaId) == null) {
                rl.readLock().unlock();
                rl.writeLock().lock();
                try {
                    ChannelFuture future = connectToReplica(replicaId, secretKeyFactory);
                    logger.debug("ClientID {}, updating connection to replica {}, at address: {}", clientId,
                            replicaId, controller.getRemoteAddress(replicaId));

                    future.awaitUninterruptibly();

                    if (!future.isSuccess()) {
                        logger.error("Impossible to connect to " + replicaId);
                    }

                } catch (InvalidKeyException | InvalidKeySpecException ex) {
                    logger.error("Failed to initialize MAC engine", ex);
                }
                rl.writeLock().unlock();
            } else {
                rl.readLock().unlock();
            }
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("Failed to initialzie secret key factory", ex);
    }
}

From source file:com.addthis.meshy.MeshyClient.java

License:Apache License

/**
 * client/*w  w w  .j  a  v a  2  s  .c  om*/
 */
public MeshyClient(InetSocketAddress address) throws IOException {
    super();
    /* block session creation until connection is fully established */
    try {
        clientInitGate.acquire();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    ChannelFuture clientConnect = connect(address);
    clientConnect.awaitUninterruptibly();
    if (!clientConnect.isSuccess()) {
        close();
        throw new IOException("connection fail to " + address);
    }
    clientChannelCloseFuture = clientConnect.channel().closeFuture();
    /* re-acquire after connection comes up, which releases the lock */
    try {
        clientInitGate.acquire();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    if (log.isDebugEnabled()) {
        log.debug("client [{}] connected to {}", getUUID(), address);
    }
}

From source file:com.addthis.meshy.MeshyServer.java

License:Apache License

/**
 * blocking call.  used by main() command-line forced peering
 *///from  w w w . ja  v  a2s . co  m
public void connectPeer(InetSocketAddress address) {
    ChannelFuture future = connectToPeer(null, address);
    if (future == null) {
        log.info("{} peer connect returned null future to {}", MeshyServer.this, address);
        return;
    }
    /* wait for connection to complete */
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        log.warn("{} peer connect fail to {}", MeshyServer.this, address);
    }
}

From source file:com.baidu.jprotobuf.pbrpc.transport.ChannelPoolObjectFactory.java

License:Apache License

@Override
public PooledObject<Connection> wrap(Connection obj) {
    Connection connection = fetchConnection();

    InetSocketAddress address;//from w ww .j  av  a2 s.  co m
    if (host == null) {
        address = new InetSocketAddress(port);
    } else {
        address = new InetSocketAddress(host, port);
    }
    ChannelFuture future = this.rpcClient.connect(address);

    // Wait until the connection is made successfully.
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        LOGGER.log(Level.SEVERE, "failed to get result from stp", future.cause());
    } else {
        connection.setIsConnected(true);
    }

    future.addListener(new RpcChannelFutureListener(connection));
    connection.setFuture(future);

    return new DefaultPooledObject<Connection>(connection);
}

From source file:com.buildria.mocking.stub.StubHttpServer.java

License:Open Source License

@Override
public StubHttpServer start() {
    Stopwatch sw = createStarted();/*from w  ww  .j ava  2  s  .  co  m*/
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                // CHECKSTYLE:OFF
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // CHECKSTYLE:ON
                    // int maxInitialLineLength, int maxHeaderSize, int maxChunkSize
                    ch.pipeline().addLast("decoder",
                            new HttpRequestDecoder(MAX_INITIALLINE_LENGH, MAX_HEADERS_SIZE, MAX_CHUNK_SIZE));
                    ch.pipeline().addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH));
                    ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                    ch.pipeline().addLast("deflater", new HttpContentCompressor());
                    if (config.isLogging()) {
                        ch.pipeline().addLast("logging", new LoggingHandler(StubHttpServer.class));
                    }
                    ch.pipeline().addLast("handler", new Handler());
                }
            }).option(ChannelOption.SO_BACKLOG, SO_BACKLOG).childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    int port = config.getPort();
    ChannelFuture f;
    try {
        f = b.bind(port).sync();
    } catch (InterruptedException ex) {
        throw new MockingException(ex);
    }
    f.awaitUninterruptibly();
    sw.stop();
    LOG.debug("### StubHttpServer(port:{}) started. It took {}", port, sw);
    return this;
}

From source file:com.dempe.lamp.client.ChannelPoolObjectFactory.java

License:Apache License

@Override
public PooledObject<Connection> wrap(Connection obj) {
    Connection connection = fetchConnection();
    ChannelFuture future = this.rpcClient.connect();
    // Wait until the connection is made successfully.
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        LOGGER.log(Level.SEVERE, "failed to get result from stp", future.cause());
    } else {/*from   ww  w.j a v a  2s.  c o m*/
        connection.setIsConnected(true);
    }
    connection.setFuture(future);

    return new DefaultPooledObject<Connection>(connection);
}

From source file:com.flysoloing.learning.network.netty.localecho.LocalEcho.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(PORT);

    EventLoopGroup serverGroup = new DefaultEventLoopGroup();
    EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK
    try {//w  w  w .jav  a 2 s.c  o  m
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class)
                .handler(new ChannelInitializer<LocalServerChannel>() {
                    @Override
                    public void initChannel(LocalServerChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                    }
                }).childHandler(new ChannelInitializer<LocalChannel>() {
                    @Override
                    public void initChannel(LocalChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
                    }
                });

        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });

        // Start the server.
        sb.bind(addr).sync();

        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();

        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}

From source file:com.github.lburgazzoli.quickfixj.transport.netty.NettyChannel.java

License:Apache License

/**
 *
 *///from w  ww. ja  va 2s. c  o m
@Override
public boolean disconnect() {
    if (m_channel != null) {
        m_channel.disconnect().awaitUninterruptibly(5000L);

        ChannelFuture future = m_channel.close();
        future.awaitUninterruptibly();

        return future.isSuccess();
    }

    return true;
}