Example usage for io.netty.channel ChannelFuture cause

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

Introduction

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

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

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 ww.j av  a2 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.andrewkroh.cisco.xmlservices.ChannelConnectListener.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    LOGGER.debug("connect() complete, status: " + future);

    if (responseFuture.isCancelled()) {
        future.channel().close();/*from w w  w .j a va 2 s  .c  o m*/
        return;
    }

    if (future.isSuccess()) {
        final Channel channel = future.channel();
        channel.attr(phoneAttributeKey).set(phone);
        channel.attr(responseFutureAttributeKey).set(responseFuture);

        // Timeout the task if it does not complete:
        eventLoopExecutor.schedule(new Runnable() {
            @Override
            public void run() {
                if (!responseFuture.isDone()) {
                    responseFuture.cancel(false);
                    channel.close();
                }
            }
        }, responseTimeoutMs, TimeUnit.MILLISECONDS);

        channel.writeAndFlush(httpRequest).addListener(new ChannelWriteFuture<T>(responseFuture));
    } else {
        responseFuture.setException(future.cause());
        future.channel().close();
    }
}

From source file:com.andrewkroh.cisco.xmlservices.ChannelWriteFuture.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    LOGGER.debug("write() complete, status: " + future);

    if (!future.isSuccess()) {
        responseFuture.setException(future.cause());
        future.channel().close();/*w w  w.  j  a  va 2s. c  o m*/
    }
}

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  w  w .j a v  a 2s  .  c o  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.barchart.netty.client.base.ConnectableBase.java

License:BSD License

@Override
public Observable<T> connect() {

    if (transport == null) {
        throw new IllegalArgumentException("Transport cannot be null");
    }//from  w  ww .jav  a  2s .  co m

    if (channelInitializer == null) {
        throw new IllegalArgumentException("Channel initializer cannot be null");
    }

    log.debug("Client connecting to " + transport.address().toString());
    changeState(Connectable.State.CONNECTING);

    final ChannelFuture future = bootstrap() //
            .group(group) //
            .handler(new ClientPipelineInitializer()) //
            .connect();

    channel = future.channel();

    final ReplaySubject<T> connectObs = ReplaySubject.create();

    future.addListener(new ChannelFutureListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {

            if (!future.isSuccess()) {
                changeState(Connectable.State.CONNECT_FAIL);
                connectObs.onError(future.cause());
            } else {
                connectObs.onNext((T) ConnectableBase.this);
                connectObs.onCompleted();
            }

        }

    });

    return connectObs;

}

From source file:com.basho.riak.client.core.ConnectionPool.java

License:Apache License

private Channel doGetConnection() throws ConnectionFailedException {
    ChannelWithIdleTime cwi;//from www  .j  a v  a  2s.c om
    while ((cwi = available.poll()) != null) {
        Channel channel = cwi.getChannel();
        // If the channel from available is closed, try again. This will result in
        // the caller always getting a connection or an exception. If closed
        // the channel is simply discarded so this also acts as a purge
        // for dead channels during a health check.
        if (channel.isOpen()) {
            return channel;
        }
    }

    ChannelFuture f = bootstrap.connect();
    // Any channels that don't connect will trigger a close operation as well
    f.channel().closeFuture().addListener(this);

    try {
        f.await();
    } catch (InterruptedException ex) {
        logger.info("Thread interrupted waiting for new connection to be made; {}", remoteAddress);
        Thread.currentThread().interrupt();
        throw new ConnectionFailedException(ex);
    }

    if (!f.isSuccess()) {
        logger.error("Connection attempt failed: {}:{}; {}", remoteAddress, port, f.cause());
        throw new ConnectionFailedException(f.cause());
    }

    return f.channel();

}

From source file:com.basho.riak.client.core.RiakNode.java

License:Apache License

private Channel doGetConnection() throws ConnectionFailedException {
    ChannelWithIdleTime cwi;//w w w. j a va  2  s  .c  o  m
    while ((cwi = available.poll()) != null) {
        Channel channel = cwi.getChannel();
        // If the channel from available is closed, try again. This will result in
        // the caller always getting a connection or an exception. If closed
        // the channel is simply discarded so this also acts as a purge
        // for dead channels during a health check.
        if (channel.isOpen()) {
            return channel;
        }
    }

    ChannelFuture f = bootstrap.connect();

    try {
        f.await();
    } catch (InterruptedException ex) {
        logger.error("Thread interrupted waiting for new connection to be made; {}", remoteAddress);
        Thread.currentThread().interrupt();
        throw new ConnectionFailedException(ex);
    }

    if (!f.isSuccess()) {
        logger.error("Connection attempt failed: {}:{}; {}", remoteAddress, port, f.cause());
        consecutiveFailedConnectionAttempts.incrementAndGet();
        throw new ConnectionFailedException(f.cause());
    }

    consecutiveFailedConnectionAttempts.set(0);
    Channel c = f.channel();

    if (trustStore != null) {
        SSLContext context;
        try {
            context = SSLContext.getInstance("TLS");
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(trustStore);

            context.init(null, tmf.getTrustManagers(), null);

        } catch (Exception ex) {
            c.close();
            logger.error("Failure configuring SSL; {}:{} {}", remoteAddress, port, ex);
            throw new ConnectionFailedException(ex);
        }

        SSLEngine engine = context.createSSLEngine();

        Set<String> protocols = new HashSet<String>(Arrays.asList(engine.getSupportedProtocols()));

        if (protocols.contains("TLSv1.2")) {
            engine.setEnabledProtocols(new String[] { "TLSv1.2" });
            logger.debug("Using TLSv1.2");
        } else if (protocols.contains("TLSv1.1")) {
            engine.setEnabledProtocols(new String[] { "TLSv1.1" });
            logger.debug("Using TLSv1.1");
        }

        engine.setUseClientMode(true);
        RiakSecurityDecoder decoder = new RiakSecurityDecoder(engine, username, password);
        c.pipeline().addFirst(decoder);

        try {
            DefaultPromise<Void> promise = decoder.getPromise();
            promise.await();

            if (promise.isSuccess()) {
                logger.debug("Auth succeeded; {}:{}", remoteAddress, port);
            } else {
                c.close();
                logger.error("Failure during Auth; {}:{} {}", remoteAddress, port, promise.cause());
                throw new ConnectionFailedException(promise.cause());
            }

        } catch (InterruptedException e) {
            c.close();
            logger.error("Thread interrupted during Auth; {}:{}", remoteAddress, port);
            Thread.currentThread().interrupt();
            throw new ConnectionFailedException(e);
        }

    }

    return c;

}

From source file:com.cloudera.livy.client.local.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//*from   www  .  j  av a 2 s  . c om*/
public static Promise<Rpc> createClient(final LocalConf config, final EventLoopGroup eloop, String host,
        int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:com.cloudera.livy.client.local.rpc.Rpc.java

License:Apache License

/**
 * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the
 * operation./*  ww w  . ja v  a2s.  co m*/
 *
 * @param msg RPC call to send.
 * @param retType Type of expected reply.
 * @return A future used to monitor the operation.
 */
public <T> Future<T> call(Object msg, Class<T> retType) {
    Preconditions.checkArgument(msg != null);
    Preconditions.checkState(channel.isOpen(), "RPC channel is closed.");
    try {
        final long id = rpcId.getAndIncrement();
        final Promise<T> promise = createPromise();
        ChannelFutureListener listener = new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture cf) {
                if (!cf.isSuccess() && !promise.isDone()) {
                    LOG.warn("Failed to send RPC, closing connection.", cf.cause());
                    promise.setFailure(cf.cause());
                    dispatcher.discardRpc(id);
                    close();
                }
            }
        };

        dispatcher.registerRpc(id, promise, msg.getClass().getName());
        synchronized (channelLock) {
            channel.write(new MessageHeader(id, Rpc.MessageType.CALL)).addListener(listener);
            channel.writeAndFlush(msg).addListener(listener);
        }
        return promise;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.cloudera.livy.rsc.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//*from  ww  w  .ja v a 2s.c  om*/
public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port,
        final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}