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.wolfbe.configcenter.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();
    }//ww  w. jav 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) {

                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(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.wuma.file.uptime.UptimeClient.java

License:Apache License

static void connect(Bootstrap b) {
    b.connect().addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.cause() != null) {
                handler.startTime = -1;/*from  ww  w.ja v  a 2 s  .c  om*/
                handler.println("Failed to connect: " + future.cause());
            }
        }
    });
}

From source file:com.yahoo.pulsar.client.impl.ConnectionPool.java

License:Apache License

private CompletableFuture<ClientCnx> createConnection(InetSocketAddress address, int connectionKey) {
    if (log.isDebugEnabled()) {
        log.debug("Connection for {} not found in cache", address);
    }//w  w w  .j  ava2  s  .co m

    final CompletableFuture<ClientCnx> cnxFuture = new CompletableFuture<ClientCnx>();

    // Trigger async connect to broker
    bootstrap.connect(address).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            cnxFuture.completeExceptionally(new PulsarClientException(future.cause()));
            cleanupConnection(address, connectionKey, cnxFuture);
            return;
        }

        log.info("[{}] Connected to server", future.channel());

        future.channel().closeFuture().addListener(v -> {
            // Remove connection from pool when it gets closed
            cleanupConnection(address, connectionKey, cnxFuture);
        });

        // We are connected to broker, but need to wait until the connect/connected handshake is
        // complete
        final ClientCnx cnx = (ClientCnx) future.channel().pipeline().get("handler");
        cnx.connectionFuture().thenRun(() -> {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Connection handshake completed", cnx.channel());
            }
            cnxFuture.complete(cnx);
        }).exceptionally(exception -> {
            log.warn("[{}] Connection handshake failed: {}", cnx.channel(), exception.getMessage());
            cnxFuture.completeExceptionally(exception);
            cleanupConnection(address, connectionKey, cnxFuture);
            cnx.ctx().close();
            return null;
        });

    });

    return cnxFuture;
}

From source file:com.yahoo.pulsar.discovery.service.DiscoveryServiceTest.java

License:Apache License

/**
 * creates ClientHandler channel to connect and communicate with server
 * /*from  w w w  . ja  v a 2  s.  co  m*/
 * @param serviceUrl
 * @param latch
 * @return
 * @throws URISyntaxException
 */
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls)
        throws URISyntaxException {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);

    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (tls) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                X509Certificate[] certificates = SecurityUtility
                        .loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
                builder.keyManager(privateKey, (X509Certificate[]) certificates);
                SslContext sslCtx = builder.build();
                ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast(new ClientHandler(latch));
        }
    });
    URI uri = new URI(serviceUrl);
    InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    b.connect(serviceAddress).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            throw new IllegalStateException(future.cause());
        }
    });
    return workerGroup;
}

From source file:com.zaradai.distributor.messaging.netty.ChannelConnection.java

License:Apache License

@Override
protected void doSend(final Message message) throws MessagingException {
    channel.writeAndFlush(message).addListener(new ChannelFutureListener() {
        @Override//from  w w w  .j a  v  a  2  s  .  c o m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                onSuccess(message);
            } else {
                onFailure(message, future.cause());
            }
        }
    });
}

From source file:com.zaradai.distributor.messaging.netty.NettyClient.java

License:Apache License

private void connect(final RetryPolicy retryPolicy) {
    ChannelFuture future = bootstrap.connect(endpoint);
    future.addListener(new ChannelFutureListener() {
        @Override/*from ww w .ja v  a 2  s  .  c  o m*/
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            final ChannelFuture fut = channelFuture;

            if (channelFuture.isSuccess()) {
                connected();
            } else {
                eventLoopGroups.getClientGroup().submit(new Runnable() {
                    @Override
                    public void run() {
                        if (retryPolicy.retry()) {
                            connect(retryPolicy);
                        } else {
                            failed(fut.cause());
                        }
                    }
                });
            }
        }
    });
}

From source file:com.zaradai.distributor.messaging.netty.NettyServer.java

License:Apache License

private void bindComplete(ChannelFuture channelFuture) {
    if (channelFuture.isSuccess()) {
        LOGGER.info("Listening on {}", channelFuture.channel().localAddress());
        serverChannelGroup.add(channelFuture.channel());
    } else {/* ww w. j ava  2 s  . co  m*/
        LOGGER.warn("Unable to listen", channelFuture.cause());
    }
}

From source file:com.zextras.modules.chat.server.EventSenderImpl.java

License:Open Source License

public void tryDelivery(String stanza) throws Throwable {
    Channel channel = getChannel();
    ChannelFuture channelFuture = channel
            .writeAndFlush(Unpooled.wrappedBuffer(stanza.getBytes(Charset.defaultCharset()))).sync();
    if (!channelFuture.isSuccess()) {
        throw channelFuture.cause();
    }/*from   www. j  a  v  a 2 s  .  c  om*/
}

From source file:com.zextras.modules.chat.server.EventSenderImpl.java

License:Open Source License

@Override
public void stop() throws InterruptedException {
    if (mChannel != null && mChannel.isOpen()) {
        ChannelFuture future = mChannel.close().sync();
        if (!future.isSuccess()) {
            throw new RuntimeException(future.cause());
        }/*w  w w  .java 2s .c om*/
    }
    if (mThread == null) {
        throw new RuntimeException("Invalid Thread state");
    }
    mRequestStop = true;
    mThread.interrupt();
    mThread = null;
}

From source file:com.zextras.modules.chat.server.LocalXmppConnectionProviderImpl.java

License:Open Source License

@Override
public Channel openConnection(String host, int port, final ChannelHandler channelHandler) throws IOException {
    ChannelHandler handler = new ChannelInitializer<SocketChannel>() {
        @Override//from  w w w .ja  v  a2  s. co  m
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            SSLEngine sslEngine = mZimbraSSLContextProvider.get().createSSLEngine();
            sslEngine.setUseClientMode(true);
            SslHandler sslHandler = new SslHandler(sslEngine);
            socketChannel.pipeline().addFirst("ssl", sslHandler);
            socketChannel.pipeline().addLast("handler", channelHandler);
        }
    };
    ChannelFuture channelFuture = new Bootstrap().channel(NioSocketChannel.class).group(new NioEventLoopGroup())
            .handler(handler).connect(host, port);

    try {
        channelFuture.sync();
        if (!channelFuture.isSuccess()) {
            throw channelFuture.cause();
        }

        return channelFuture.channel();
    } catch (Throwable t) {
        throw new IOException(t);
    }
}