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:io.vertx.core.http.impl.HttpClientImpl.java

License:Open Source License

private void internalConnect(ContextImpl context, int port, String host,
        Handler<ClientConnection> connectHandler, Handler<Throwable> connectErrorHandler,
        ConnectionLifeCycleListener listener) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(context.eventLoop());
    bootstrap.channelFactory(new VertxNioSocketChannelFactory());
    sslHelper.validate(vertx);/*  w  ww  .  j a  v a 2s  .  c om*/
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (options.isSsl()) {
                pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, true, host, port));
            }

            pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false));
            if (options.isTryUseCompression()) {
                pipeline.addLast("inflater", new HttpContentDecompressor(true));
            }
            if (options.getIdleTimeout() > 0) {
                pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
            }
            pipeline.addLast("handler", new ClientHandler(vertx, context));
        }
    });
    applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener((ChannelFuture channelFuture) -> {
        Channel ch = channelFuture.channel();
        if (channelFuture.isSuccess()) {
            if (options.isSsl()) {
                // TCP connected, so now we must do the SSL handshake

                SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
                fut.addListener(fut2 -> {
                    if (fut2.isSuccess()) {
                        connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
                    } else {
                        connectionFailed(context, ch, connectErrorHandler,
                                new SSLHandshakeException("Failed to create SSL connection"), listener);
                    }
                });
            } else {
                connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
            }
        } else {
            connectionFailed(context, ch, connectErrorHandler, channelFuture.cause(), listener);
        }
    });
}

From source file:io.vertx.core.net.impl.ChannelFutureListenerAdapter.java

License:Open Source License

@Override
public void operationComplete(ChannelFuture future) {
    Future<T> res = future.isSuccess() ? Future.succeededFuture(result) : Future.failedFuture(future.cause());
    context.executeFromIO(res, handler);
}

From source file:io.viewserver.network.netty.NettyNetworkAdapter.java

License:Apache License

@Override
public ListenableFuture<IChannel> connect(IEndpoint endpoint) {
    SettableFuture<IChannel> promise = SettableFuture.create();
    final INettyEndpoint.IClient client = ((INettyEndpoint) endpoint).getClient(getClientWorkerGroup(),
            new NettyPipelineInitialiser(networkMessageWheel));
    ChannelFuture channelFuture = client.connect();
    channelFuture.addListener(new ChannelFutureListener() {
        @Override//ww w.  j  a  v a  2s.  c  o  m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                NettyChannel channel = new NettyChannel(future.channel());
                promise.set(channel);
            } else {
                promise.setException(future.cause());
            }
        }
    });
    return promise;
}

From source file:it.jnrpe.JNRPE.java

License:Apache License

/**
 * Starts a new thread that listen for requests. The method is <b>not
 * blocking</b>/*from   w  w  w.  ja  va  2s  .com*/
 * 
 * @param address
 *            The address to bind to
 * @param port
 *            The listening port
 * @param useSSL
 *            <code>true</code> if an SSL socket must be created.
        
 * @throws UnknownHostException
 *             - */
public void listen(final String address, final int port, final boolean useSSL) throws UnknownHostException {

    // Bind and start to accept incoming connections.
    ChannelFuture cf = getServerBootstrap(useSSL).bind(address, port);
    cf.addListener(new ChannelFutureListener() {

        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                context.getEventBus().post(new JNRPEStatusEvent(STATUS.STARTED, this, "JNRPE Server started"));
                LOG.info(context, "Listening on " + (useSSL ? "SSL/" : "") + address + ":" + port);
            } else {
                getExecutionContext().getEventBus()
                        .post(new JNRPEStatusEvent(STATUS.FAILED, this, "JNRPE Server start failed"));
                LOG.error(context, "Unable to listen on " + (useSSL ? "SSL/" : "") + address + ":" + port,
                        future.cause());
            }
        }
    });

}

From source file:jj.http.server.websocket.WebSocketConnectionMaker.java

License:Apache License

private void doHandshake(final ChannelHandlerContext ctx, final FullHttpRequest request,
        final WebSocketServerHandshaker handshaker) {
    handshaker.handshake(ctx.channel(), request).addListener(new ChannelFutureListener() {

        private boolean isHandshakeFailure(ChannelFuture future) {
            return future.cause() != null && future.cause() instanceof WebSocketHandshakeException;
        }//from  ww w  .j  a v  a2 s.c o m

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {

                URIMatch uriMatch = new URIMatch(request.getUri());

                WebSocketConnectionHost host = null;

                for (Class<? extends WebSocketConnectionHost> hostClass : webSocketConnectionHostClasses) {
                    host = resourceFinder.findResource(hostClass, AppLocation.Virtual, uriMatch.name);
                    if (host != null)
                        break;
                }

                if (host == null) {

                    // 1011 indicates that a server is terminating the connection because
                    // it encountered an unexpected condition that prevented it from
                    // fulfilling the request.
                    ctx.writeAndFlush(new CloseWebSocketFrame(1011, null)).addListener(CLOSE);
                    // TODO: is closing here the right thing? or do we count on the client closing the connection
                    // to avoid the time_wait state? 

                } else if (!uriMatch.sha1.equals(host.sha1())) {

                    ctx.writeAndFlush(new TextWebSocketFrame("jj-reload"))
                            .addListener(new ChannelFutureListener() {

                                @Override
                                public void operationComplete(ChannelFuture future) throws Exception {
                                    // 1001 indicates that an endpoint is "going away", such as a server
                                    // going down or a browser having navigated away from a page.
                                    ctx.writeAndFlush(new CloseWebSocketFrame(1001, null)).addListener(CLOSE);
                                    // TODO: is closing here the right thing? or do we count on the client closing the connection
                                    // to avoid the time_wait state? 
                                }
                            });

                } else {

                    ctx.pipeline().replace(JJEngine.toString(), JJWebsocketHandler.toString(),
                            handlerCreator.createHandler(handshaker, host));
                }

            } else if (isHandshakeFailure(future)) {
                response.sendError(HttpResponseStatus.BAD_REQUEST);
            } else {
                ctx.close();
            }
        }
    });
}

From source file:jj.repl.ReplIntegrationTest.java

License:Apache License

@Test
public void test() throws Throwable {
    assertTrue("timed out waiting for init", latch.await(500, MILLISECONDS));

    // well... it started so that's something
    // connect to config.port() and send in some commands? why not
    latch = new CountDownLatch(1);

    final AtomicReference<Throwable> failure = new AtomicReference<>();

    final StringBuilder response = new StringBuilder().append("Welcome to JibbrJabbr\n>")
            .append("ReferenceError: \"whatever\" is not defined.\n").append("   at repl-console:1\n")
            .append("   at base-repl-system.js:8 ($$print)\n").append("   at repl-console:1\n").append("\n>");

    bootstrap = new Bootstrap().group(new NioEventLoopGroup(1)).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {

                @Override/*from w ww .ja v  a 2s. c  o m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new StringEncoder(US_ASCII)).addLast(new StringDecoder(US_ASCII))
                            .addLast(new SimpleChannelInboundHandler<String>() {

                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg)
                                        throws Exception {
                                    if (msg.equals(response.substring(0, msg.length()))) {
                                        response.delete(0, msg.length());
                                    }
                                    if (response.length() == 0) {
                                        latch.countDown();
                                    }
                                }
                            });
                }
            });
    bootstrap.connect("localhost", config.port()).addListener((ChannelFuture future) -> {
        if (future.isSuccess()) {
            future.channel().writeAndFlush("whatever\n");
        } else {
            failure.set(future.cause());
        }
    });

    assertTrue("timed out waiting for response", latch.await(1, SECONDS));
    if (failure.get() != null) {
        throw failure.get();
    }
}

From source file:jj.repl.ReplServer.java

License:Apache License

private void start() {
    port = (configuration.port() < 1023 || configuration.port() > 65535) ? DEFAULT_PORT : configuration.port();

    final ServerBootstrap bootstrap = new ServerBootstrap()
            .group(new NioEventLoopGroup(1, bossThreadFactory), new NioEventLoopGroup(1, workerThreadFactory))
            .channel(NioServerSocketChannel.class).childHandler(channelInitializer);

    bootstrap.bind("localhost", port).addListener(new ChannelFutureListener() {

        @Override/* w ww .ja v a2  s . c  om*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                publisher.publish(new ReplListening(port));
                server = bootstrap;
            } else {
                publisher.publish(new Emergency("could not start the REPL server", future.cause()));
                bootstrap.group().shutdownGracefully(0, 0, SECONDS);
                bootstrap.childGroup().shutdownGracefully(0, 0, SECONDS);
            }
        }
    });
}

From source file:jlibs.wamp4j.netty.NettyClientEndpoint.java

License:Apache License

@Override
public void connect(final URI uri, final ConnectListener listener, final String... subProtocols) {
    final SslContext sslContext;
    if ("wss".equals(uri.getScheme())) {
        try {//  www .ja v a2s.  com
            if (sslSettings == null) {
                sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                        .build();
            } else {
                sslContext = SslContextBuilder.forClient().trustManager(sslSettings.trustCertChainFile)
                        .keyManager(sslSettings.certificateFile, sslSettings.keyFile, sslSettings.keyPassword)
                        .build();
            }
        } catch (Throwable thr) {
            listener.onError(thr);
            return;
        }
    } else if ("ws".equals(uri.getScheme()))
        sslContext = null;
    else
        throw new IllegalArgumentException("invalid protocol: " + uri.getScheme());

    final int port = uri.getPort() == -1 ? (sslContext == null ? 80 : 443) : uri.getPort();

    Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.MAX_MESSAGES_PER_READ, 50000).option(ChannelOption.WRITE_SPIN_COUNT, 50000)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    if (sslContext != null)
                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
                    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
                            WebSocketVersion.V13, Util.toString(subProtocols), false, new DefaultHttpHeaders());
                    ch.pipeline().addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                            new WebSocketClientProtocolHandler(handshaker) {
                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                        throws Exception {
                                    super.exceptionCaught(ctx, cause);
                                    listener.onError(cause);
                                }
                            }, new HandshakeListener(handshaker, listener));
                }
            });
    bootstrap.connect(uri.getHost(), port).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                assert !future.channel().isOpen();
                listener.onError(future.cause());
            }
        }
    });
}

From source file:jlibs.wamp4j.netty.NettyServerEndpoint.java

License:Apache License

@Override
public void bind(final URI uri, final String subProtocols[], final AcceptListener listener) {
    final SslContext sslContext;
    if ("wss".equals(uri.getScheme())) {
        try {//from  w  w w.j av a  2 s  .c  o  m
            if (sslSettings == null) {
                SelfSignedCertificate ssc = new SelfSignedCertificate();
                sslSettings = new SSLSettings().keyFile(ssc.privateKey()).certificateFile(ssc.certificate());
            }
            ClientAuth clientAuth = ClientAuth.values()[sslSettings.clientAuthentication.ordinal()];
            sslContext = SslContextBuilder
                    .forServer(sslSettings.certificateFile, sslSettings.keyFile, sslSettings.keyPassword)
                    .clientAuth(clientAuth).trustManager(sslSettings.trustCertChainFile).build();
        } catch (Throwable thr) {
            listener.onError(thr);
            return;
        }
    } else if ("ws".equals(uri.getScheme()))
        sslContext = null;
    else
        throw new IllegalArgumentException("invalid protocol: " + uri.getScheme());

    int port = uri.getPort();
    if (port == -1)
        port = sslContext == null ? 80 : 443;
    ServerBootstrap bootstrap = new ServerBootstrap().group(eventLoopGroup)
            .channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.MAX_MESSAGES_PER_READ, 50000)
            .childOption(ChannelOption.WRITE_SPIN_COUNT, 50000)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    if (sslContext != null)
                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                    ch.pipeline().addLast(new HttpServerCodec(), new HttpObjectAggregator(65536),
                            new Handshaker(uri, listener, subProtocols));
                }
            });
    bootstrap.bind(uri.getHost(), port).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                channel.attr(ACCEPT_LISTENER).set(listener);
                listener.onBind(NettyServerEndpoint.this);
            } else
                listener.onError(future.cause());
        }
    });
}

From source file:jlibs.wamp4j.netty.NettyServerEndpoint.java

License:Apache License

@Override
public void close() {
    channel.close().addListener(new ChannelFutureListener() {
        @Override//from  ww  w .  ja  v a  2s .c  om
        public void operationComplete(ChannelFuture future) throws Exception {
            AcceptListener acceptListener = channel.attr(ACCEPT_LISTENER).get();
            if (!future.isSuccess())
                acceptListener.onError(future.cause());
            acceptListener.onClose(NettyServerEndpoint.this);
        }
    });
}