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.couchbase.client.core.io.endpoint.AbstractEndpoint.java

License:Open Source License

@Override
public Promise<EndpointState> disconnect() {
    shouldRetry = false;/*from   w ww  .j  a va 2s. com*/
    if (state != EndpointState.CONNECTED) {
        if (state == EndpointState.CONNECTING || state == EndpointState.RECONNECTING) {
            transitionState(EndpointState.DISCONNECTED);
        }

        return Promises.success(state).get();
    }

    transitionState(EndpointState.DISCONNECTING);

    final Deferred<EndpointState, Promise<EndpointState>> deferred = Promises.defer(env, defaultPromiseEnv);
    channel.disconnect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            transitionState(EndpointState.DISCONNECTED);
            deferred.accept(state);
            if (future.isSuccess()) {
                LOGGER.debug("Successfully disconnected Endpoint from: " + channel.remoteAddress());
            } else {
                LOGGER.error("Detected error during Endpoint disconnect phase from: " + channel.remoteAddress(),
                        future.cause());
            }
            channel = null;
        }
    });
    return deferred.compose();
}

From source file:com.couchbase.client.QueryConnection.java

License:Open Source License

public QueryConnection(List<String> nodes, CouchbaseConnectionFactory cf) {
    connectionFactory = cf;/*from   w w w .  ja v  a 2  s.co m*/

    Class<? extends SocketChannel> channel = NioSocketChannel.class;
    Bootstrap bootstrap = new Bootstrap().group(group).channel(channel).handler(new QueryInitializer());

    List<ChannelFuture> connectFutures = new ArrayList<ChannelFuture>();
    for (String node : nodes) {
        connectFutures.add(bootstrap.connect(node, QUERY_PORT));
    }

    long startTime = System.nanoTime();
    long connectTimeout = TimeUnit.MILLISECONDS.toNanos(CONNECT_TIMEOUT);
    while (connectFutures.size() > 0 && System.nanoTime() - startTime <= connectTimeout) {
        Iterator<ChannelFuture> iterator = connectFutures.iterator();
        while (iterator.hasNext()) {
            ChannelFuture connectFuture = iterator.next();
            if (!connectFuture.isDone()) {
                continue;
            }

            if (connectFuture.isSuccess()) {
                connectedChannels.add(connectFuture.channel());
            } else {
                getLogger().error("Could not connect to Query node, skipping: " + connectFuture.cause());
            }

            iterator.remove();
        }
    }

    if (connectedChannels.size() == 0) {
        throw new BootstrapException("Could not connect to at least one io node, stopping bootstrap.");
    }
}

From source file:com.datastax.driver.core.Connection.java

License:Apache License

public ListenableFuture<Void> initAsync() {
    if (factory.isShutdown)
        return Futures
                .immediateFailedFuture(new ConnectionException(address, "Connection factory is shut down"));

    ProtocolVersion protocolVersion = factory.protocolVersion == null ? ProtocolVersion.NEWEST_SUPPORTED
            : factory.protocolVersion;//from   w ww  . j  a v a2s .  c  o  m
    final SettableFuture<Void> channelReadyFuture = SettableFuture.create();

    try {
        Bootstrap bootstrap = factory.newBootstrap();
        ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
        bootstrap.handler(new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(),
                protocolOptions.getSSLOptions(),
                factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
                factory.configuration.getNettyOptions()));

        ChannelFuture future = bootstrap.connect(address);

        writer.incrementAndGet();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                writer.decrementAndGet();
                channel = future.channel();
                if (isClosed()) {
                    channel.close().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            channelReadyFuture.setException(new TransportException(Connection.this.address,
                                    "Connection closed during initialization."));
                        }
                    });
                } else {
                    Connection.this.factory.allChannels.add(channel);
                    if (!future.isSuccess()) {
                        if (logger.isDebugEnabled())
                            logger.debug(String.format("%s Error connecting to %s%s", Connection.this,
                                    Connection.this.address, extractMessage(future.cause())));
                        channelReadyFuture.setException(new TransportException(Connection.this.address,
                                "Cannot connect", future.cause()));
                    } else {
                        logger.debug("{} Connection established, initializing transport", Connection.this);
                        channel.closeFuture().addListener(new ChannelCloseListener());
                        channelReadyFuture.set(null);
                    }
                }
            }
        });
    } catch (RuntimeException e) {
        closeAsync().force();
        throw e;
    }

    Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor();

    ListenableFuture<Void> initializeTransportFuture = Futures.transformAsync(channelReadyFuture,
            onChannelReady(protocolVersion, initExecutor), initExecutor);

    // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
    ListenableFuture<Void> initFuture = Futures.catchingAsync(initializeTransportFuture, Throwable.class,
            new AsyncFunction<Throwable, Void>() {
                @Override
                public ListenableFuture<Void> apply(@Nullable Throwable t) throws Exception {
                    SettableFuture<Void> future = SettableFuture.create();
                    // Make sure the connection gets properly closed.
                    if (t instanceof ClusterNameMismatchException
                            || t instanceof UnsupportedProtocolVersionException) {
                        // Just propagate
                        closeAsync().force();
                        future.setException(t);
                    } else {
                        // Defunct to ensure that the error will be signaled (marking the host down)
                        Exception e = (t instanceof ConnectionException || t instanceof DriverException
                                || t instanceof InterruptedException) ? (Exception) t
                                        : new ConnectionException(Connection.this.address, String.format(
                                                "Unexpected error during transport initialization (%s)", t), t);
                        future.setException(defunct(e));
                    }
                    return future;
                }
            }, initExecutor);

    // Ensure the connection gets closed if the caller cancels the returned future.
    Futures.addCallback(initFuture, new MoreFutures.FailureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            if (!isClosed()) {
                closeAsync().force();
            }
        }
    }, initExecutor);

    return initFuture;
}

From source file:com.datastax.driver.core.Connection.java

License:Apache License

private ChannelFutureListener writeHandler(final Message.Request request, final ResponseHandler handler) {
    return new ChannelFutureListener() {
        @Override//  w  w  w  .ja  v a 2s .  c o  m
        public void operationComplete(ChannelFuture writeFuture) {

            writer.decrementAndGet();

            if (!writeFuture.isSuccess()) {
                logger.debug("{}, stream {}, Error writing request {}", Connection.this, request.getStreamId(),
                        request);
                // Remove this handler from the dispatcher so it don't get notified of the error
                // twice (we will fail that method already)
                dispatcher.removeHandler(handler, true);

                final ConnectionException ce;
                if (writeFuture.cause() instanceof java.nio.channels.ClosedChannelException) {
                    ce = new TransportException(address, "Error writing: Closed channel");
                } else {
                    ce = new TransportException(address, "Error writing", writeFuture.cause());
                }
                final long latency = System.nanoTime() - handler.startTime;
                // This handler is executed while holding the writeLock of the channel.
                // defunct might close the pool, which will close all of its connections; closing a connection also
                // requires its writeLock.
                // Therefore if multiple connections in the same pool get a write error, they could deadlock;
                // we run defunct on a separate thread to avoid that.
                ListeningExecutorService executor = factory.manager.executor;
                if (!executor.isShutdown())
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            handler.callback.onException(Connection.this, defunct(ce), latency,
                                    handler.retryCount);
                        }
                    });
            } else {
                logger.trace("{}, stream {}, request sent successfully", Connection.this,
                        request.getStreamId());
            }
        }
    };
}

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();//  w w w . j av  a 2  s  . c  o  m
    if (!future.isSuccess()) {
        LOGGER.log(Level.SEVERE, "failed to get result from stp", future.cause());
    } else {
        connection.setIsConnected(true);
    }
    connection.setFuture(future);

    return new DefaultPooledObject<Connection>(connection);
}

From source file:com.digisky.stresstest.HttpSnoopClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/* ww w  .ja  v  a  2  s  .c  o  m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        System.out.println("try to connect!");
        ChannelFuture f = b.connect(host, port);
        f.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                // Perform post-closure operation
                // ...
                System.out.println("complete!");
                if (!future.isSuccess()) {
                    // You might get a NullPointerException here because the future
                    // might not be completed yet.
                    future.cause().printStackTrace();
                } else {
                    System.out.println("ok!!!!");
                }
            }
        });
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.digitalpetri.modbus.master.ModbusTcpMaster.java

License:Apache License

public static CompletableFuture<Channel> bootstrap(ModbusTcpMaster master, ModbusTcpMasterConfig config) {
    CompletableFuture<Channel> future = new CompletableFuture<>();

    Bootstrap bootstrap = new Bootstrap();

    config.getBootstrapConsumer().accept(bootstrap);

    bootstrap.group(config.getEventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) config.getTimeout().toMillis())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/* ww w  .j a va  2 s.c om*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                            new ModbusTcpCodec(new ModbusRequestEncoder(), new ModbusResponseDecoder()));
                    ch.pipeline().addLast(new ModbusTcpMasterHandler(master));
                }
            }).connect(config.getAddress(), config.getPort()).addListener((ChannelFuture f) -> {
                if (f.isSuccess()) {
                    future.complete(f.channel());
                } else {
                    future.completeExceptionally(f.cause());
                }
            });

    return future;
}

From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java

License:Apache License

public CompletableFuture<ModbusTcpSlave> bind(String host, int port) {
    CompletableFuture<ModbusTcpSlave> bindFuture = new CompletableFuture<>();

    ServerBootstrap bootstrap = new ServerBootstrap();

    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
        @Override//  w  w w . j  av a  2  s.  co m
        protected void initChannel(SocketChannel channel) throws Exception {
            channelCounter.inc();
            logger.info("channel initialized: {}", channel);

            channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
            channel.pipeline()
                    .addLast(new ModbusTcpCodec(new ModbusResponseEncoder(), new ModbusRequestDecoder()));
            channel.pipeline().addLast(new ModbusTcpSlaveHandler(ModbusTcpSlave.this));

            channel.closeFuture().addListener(future -> channelCounter.dec());
        }
    };

    config.getBootstrapConsumer().accept(bootstrap);

    bootstrap.group(config.getEventLoop()).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(initializer)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    bootstrap.bind(host, port).addListener((ChannelFuture future) -> {
        if (future.isSuccess()) {
            Channel channel = future.channel();
            serverChannels.put(channel.localAddress(), channel);
            bindFuture.complete(ModbusTcpSlave.this);
        } else {
            bindFuture.completeExceptionally(future.cause());
        }
    });

    return bindFuture;
}

From source file:com.digitalpetri.opcua.stack.client.UaTcpStackClient.java

License:Apache License

public static CompletableFuture<ClientSecureChannel> bootstrap(UaTcpStackClient client,
        Optional<ClientSecureChannel> existingChannel) {

    CompletableFuture<ClientSecureChannel> handshake = new CompletableFuture<>();

    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(client.getConfig().getEventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from  w ww  . java 2  s .  co  m
                protected void initChannel(SocketChannel channel) throws Exception {
                    UaTcpClientAcknowledgeHandler acknowledgeHandler = new UaTcpClientAcknowledgeHandler(client,
                            existingChannel, handshake);

                    channel.pipeline().addLast(acknowledgeHandler);
                }
            });

    try {
        URI uri = URI.create(client.getEndpointUrl());

        bootstrap.connect(uri.getHost(), uri.getPort()).addListener((ChannelFuture f) -> {
            if (!f.isSuccess()) {
                handshake.completeExceptionally(f.cause());
            }
        });
    } catch (Throwable t) {
        UaException failure = new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid,
                "endpoint URL invalid: " + client.getEndpointUrl());

        handshake.completeExceptionally(failure);
    }

    return handshake;
}

From source file:com.digitalpetri.opcua.stack.server.tcp.SocketServer.java

License:Apache License

public synchronized void bind() throws ExecutionException, InterruptedException {
    if (channel != null)
        return; // Already bound

    CompletableFuture<Void> bindFuture = new CompletableFuture<>();

    bootstrap.bind(address).addListener(new ChannelFutureListener() {
        @Override//www .j a v a  2s  .c  om
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                bindFuture.complete(null);
            } else {
                bindFuture.completeExceptionally(future.cause());
            }
        }
    });

    bindFuture.get();
}