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 timeoutMillis);

Source Link

Document

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

Usage

From source file:code.google.nfs.rpc.netty.client.NettyClientFactory.java

License:Apache License

protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key)
        throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .option(ChannelOption.SO_REUSEADDR,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")));
    if (connectTimeout < 1000) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    } else {/*from   w ww.  j a  v  a2 s  .c  om*/
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    }
    final NettyClientHandler handler = new NettyClientHandler(this, key);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("decoder", new NettyProtocolDecoder());
            pipeline.addLast("encoder", new NettyProtocolEncoder());
            pipeline.addLast("handler", handler);
        }

    });
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort)).sync();
    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    NettyClient client = new NettyClient(future, key, connectTimeout);
    handler.setClient(client);
    return client;
}

From source file:code.google.nfs.rpc.netty4.client.Netty4ClientFactory.java

License:Apache License

protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key)
        throws Exception {
    final Netty4ClientHandler handler = new Netty4ClientHandler(this, key);

    EventLoopGroup group = new NioEventLoopGroup(1);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
            .option(ChannelOption.SO_REUSEADDR,
                    Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout < 1000 ? 1000 : connectTimeout)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override// www.  j a  va 2s  .  c  o m
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder());
                    ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder());
                    ch.pipeline().addLast("handler", handler);
                }
            });

    ChannelFuture future = b.connect(targetIP, targetPort);

    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    Netty4Client client = new Netty4Client(future, key, connectTimeout);
    handler.setClient(client);
    return client;
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingClient.java

License:Apache License

private Channel createChannel(final String addr) throws InterruptedException {
    ChannelWrapper cw = this.channelTables.get(addr);
    if (cw != null && cw.isOK()) {
        return cw.getChannel();
    }//from  ww w.  ja va 2  s.co m

    // ????
    if (this.lockChannelTables.tryLock(LockTimeoutMillis, TimeUnit.MILLISECONDS)) {
        try {
            boolean createNewConnection = false;
            cw = this.channelTables.get(addr);
            if (cw != null) {
                // channel
                if (cw.isOK()) {
                    return cw.getChannel();
                }
                // ?
                else if (!cw.getChannelFuture().isDone()) {
                    createNewConnection = false;
                }
                // ??
                else {
                    this.channelTables.remove(addr);
                    createNewConnection = true;
                }
            }
            // ChannelWrapper?
            else {
                createNewConnection = true;
            }

            if (createNewConnection) {
                ChannelFuture channelFuture = this.bootstrap.connect(RemotingHelper.string2SocketAddress(addr));
                log.info("createChannel: begin to connect remote host[{}] asynchronously", addr);
                cw = new ChannelWrapper(channelFuture);
                this.channelTables.put(addr, cw);
            }
        } catch (Exception e) {
            log.error("createChannel: create channel exception", e);
        } finally {
            this.lockChannelTables.unlock();
        }
    } else {
        log.warn("createChannel: try to lock channel table, but timeout, {}ms", LockTimeoutMillis);
    }

    if (cw != null) {
        ChannelFuture channelFuture = cw.getChannelFuture();
        if (channelFuture.awaitUninterruptibly(this.nettyClientConfig.getConnectTimeoutMillis())) {
            if (cw.isOK()) {
                log.info("createChannel: connect remote host[{}] success, {}", addr, channelFuture.toString());
                return cw.getChannel();
            } else {
                if (log.isDebugEnabled())
                    log.debug("createChannel: connect remote host[" + addr + "] failed, "
                            + channelFuture.toString(), channelFuture.cause());
                else
                    log.warn("createChannel: connect remote host[" + addr + "] failed, "
                            + channelFuture.toString());
            }
        } else {
            log.warn("createChannel: connect remote host[{}] timeout {}ms, {}", addr,
                    this.nettyClientConfig.getConnectTimeoutMillis(), channelFuture.toString());
        }
    }

    return null;
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyUDPClient.java

License:Apache License

private Channel createChannel(final String addr) throws InterruptedException {
    ChannelWrapper cw = this.channelTables.get(addr);
    if (cw != null && cw.isOK()) {
        return cw.getChannel();
    }//from  w w w .  j  a v a  2  s  .c  o m

    // ????
    if (this.lockChannelTables.tryLock(LockTimeoutMillis, TimeUnit.MILLISECONDS)) {
        try {
            boolean createNewConnection = false;
            cw = this.channelTables.get(addr);
            if (cw != null) {
                // channel
                if (cw.isOK()) {
                    return cw.getChannel();
                }
                // ?
                else if (!cw.getChannelFuture().isDone()) {
                    createNewConnection = false;
                }
                // ??
                else {
                    this.channelTables.remove(addr);
                    createNewConnection = true;
                }
            }
            // ChannelWrapper?
            else {
                createNewConnection = true;
            }

            if (createNewConnection) {
                ChannelFuture channelFuture = this.bootstrap.connect(RemotingHelper.string2SocketAddress(addr));
                log.info("createChannel: begin to connect remote host[{}] asynchronously", addr);
                cw = new ChannelWrapper(channelFuture);
                this.channelTables.put(addr, cw);
            }
        } catch (Exception e) {
            log.error("createChannel: create channel exception", e);
        } finally {
            this.lockChannelTables.unlock();
        }
    } else {
        log.warn("createChannel: try to lock channel table, but timeout, {}ms", LockTimeoutMillis);
    }

    if (cw != null) {
        ChannelFuture channelFuture = cw.getChannelFuture();
        if (channelFuture.awaitUninterruptibly(this.nettyClientConfig.getConnectTimeoutMillis())) {
            if (cw.isOK()) {
                log.info("createChannel: connect remote host[{}] success, {}", addr, channelFuture.toString());
                return cw.getChannel();
            } else {
                log.warn("createChannel: connect remote host[" + addr + "] failed, " + channelFuture.toString(),
                        channelFuture.cause());
            }
        } else {
            log.warn("createChannel: connect remote host[{}] timeout {}ms, {}", addr,
                    this.nettyClientConfig.getConnectTimeoutMillis(), channelFuture.toString());
        }
    }

    return null;
}

From source file:com.ebay.jetstream.http.netty.client.HttpClient.java

License:MIT License

private HttpSessionChannelContext activateHttpSession(URI uri) throws UnknownHostException {

    ChannelFuture cf = null;
    try {/*from  w w  w  . j a v a2s  .c om*/
        cf = m_bootstrap.connect(new InetSocketAddress(InetAddress.getByName(uri.getHost()), uri.getPort()));

        if (!m_urlDropCounters.containsKey(uri.getHost()))
            m_urlDropCounters.put(uri.getHost(), new LongCounter());

    } catch (UnknownHostException e) {
        LOGGER.error("failed to connect to host" + e.getLocalizedMessage());
        throw e;
    }

    cf.awaitUninterruptibly((getConfig().getConnectionTimeoutInSecs() + 1) * 1000);

    if (!cf.channel().isActive()) {
        return null;
    }

    HttpSessionChannelContext sessionContext = new HttpSessionChannelContext();
    sessionContext.setChannel(cf.channel());
    sessionContext.channelConnected();
    sessionContext.setUri(uri.toString());
    sessionContext.getVirtualQueueMonitor().setMaxQueueBackLog(getConfig().getMaxNettyBacklog());
    sessionContext.setSessionDurationInSecs(getConfig().getMaxSessionDurationInSecs());
    return sessionContext;

}

From source file:com.ebay.jetstream.messaging.transport.netty.eventproducer.EventProducer.java

License:MIT License

/**
 * @param ecinfo/* ww  w . j  a v  a  2 s  .c  o  m*/
 * @throws Exception
 */
Channel activateEventConsumerSession(EventConsumerInfo ecinfo, boolean asyncConnect, int numConnections)
        throws Exception {

    if (asyncConnect) {

        createAsyncMultipleConnections(ecinfo, numConnections);

    } else {

        // now we create the configd number of connections

        // Start the client.
        ChannelFuture cf = m_bootstrap.connect(InetAddress.getByName(ecinfo.getAdvertisement().getHostName()),
                ecinfo.getAdvertisement().getListenTcpPort()); // (5)

        cf.awaitUninterruptibly((m_transportConfig.getConnectionTimeoutInSecs() + 1) * 1000);

        if (cf.isSuccess()) {
            ConsumerChannelContext ccc = new ConsumerChannelContext();
            ccc.setChannel(cf.channel());

            ecinfo.setChannelContext(cf.channel(), ccc);
            activateEventConsumer(ecinfo);
        }
    }

    return null;
}

From source file:com.farsunset.cim.sdk.android.CIMConnectorManager.java

License:Apache License

public void send(SentBody body) {

    boolean isSuccessed = false;

    String exceptionName = SessionClosedException.class.getSimpleName();

    if (isConnected()) {
        ChannelFuture future = channel.writeAndFlush(body);
        isSuccessed = future.awaitUninterruptibly(WRITE_TIMEOUT);
        if (!isSuccessed && future.cause() != null) {
            exceptionName = future.cause().getClass().getSimpleName();
        }/*  w  w w  . ja  v  a  2  s.c  o  m*/

    }

    if (!isSuccessed) {
        Intent intent = new Intent();
        intent.setAction(CIMConstant.IntentAction.ACTION_SENT_FAILED);
        intent.putExtra(Exception.class.getName(), exceptionName);
        intent.putExtra(SentBody.class.getName(), body);
        context.sendBroadcast(intent);
    } else {
        Intent intent = new Intent();
        intent.setAction(CIMConstant.IntentAction.ACTION_SENT_SUCCESSED);
        intent.putExtra(SentBody.class.getName(), (SentBody) body);
        context.sendBroadcast(intent);
    }

}

From source file:com.github.sparkfy.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException {
    logger.debug("Creating new connection to " + address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    final AtomicReference<TransportClient> clientRef = new AtomicReference<TransportClient>();
    final AtomicReference<Channel> channelRef = new AtomicReference<Channel>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override//from  w  w  w  . j a  va2s . c o m
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.awaitUninterruptibly(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.debug("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}

From source file:com.mpush.netty.connection.NettyConnection.java

License:Apache License

@Override
public ChannelFuture send(Packet packet, final ChannelFutureListener listener) {
    if (channel.isActive()) {

        ChannelFuture future = channel.writeAndFlush(packet.toFrame(channel)).addListener(this);

        if (listener != null) {
            future.addListener(listener);
        }//from  www  . ja va2 s. c o m

        if (channel.isWritable()) {
            return future;
        }

        //
        //return channel.newPromise().setFailure(new RuntimeException("send data too busy"));
        if (!future.channel().eventLoop().inEventLoop()) {
            future.awaitUninterruptibly(100);
        }
        return future;
    } else {
        /*if (listener != null) {
        channel.newPromise()
                .addListener(listener)
                .setFailure(new RuntimeException("connection is disconnected"));
        }*/
        return this.close();
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcClient.java

License:Apache License

private Channel createChannel(final String addr) throws InterruptedException {
    ChannelWrapper cw = this.channelTables.get(addr);
    if (cw != null && cw.isOK()) {
        return cw.getChannel();
    }/*from  w w w . ja v a 2  s  .com*/

    if (this.lockChannelTables.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
        try {
            boolean createNewConnection = false;
            cw = this.channelTables.get(addr);
            if (cw != null) {

                if (cw.isOK()) {
                    return cw.getChannel();
                }

                else if (!cw.getChannelFuture().isDone()) {
                    createNewConnection = false;
                }

                else {
                    this.channelTables.remove(addr);
                    createNewConnection = true;
                }
            }

            else {
                createNewConnection = true;
            }

            if (createNewConnection) {
                ChannelFuture channelFuture = this.bootstrap.connect(RpcHelper.string2SocketAddress(addr));
                LOGGER.info("createChannel: begin to connect remote host[{}] asynchronously", addr);
                cw = new ChannelWrapper(channelFuture);
                this.channelTables.put(addr, cw);
            }
        } catch (Exception e) {
            LOGGER.error("createChannel: create channel exception", e);
        } finally {
            this.lockChannelTables.unlock();
        }
    } else {
        LOGGER.warn("createChannel: try to lock channel table, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
    }

    if (cw != null) {
        ChannelFuture channelFuture = cw.getChannelFuture();
        if (channelFuture.awaitUninterruptibly(this.nettyClientConfig.getConnectTimeoutMillis())) {
            if (cw.isOK()) {
                LOGGER.info("createChannel: connect remote host[{}] success, {}", addr,
                        channelFuture.toString());
                return cw.getChannel();
            } else {
                LOGGER.warn(
                        "createChannel: connect remote host[" + addr + "] failed, " + channelFuture.toString(),
                        channelFuture.cause());
            }
        } else {
            LOGGER.warn("createChannel: connect remote host[{}] timeout {}ms, {}", addr,
                    this.nettyClientConfig.getConnectTimeoutMillis(), channelFuture.toString());
        }
    }

    return null;
}