Example usage for io.netty.util.concurrent Future isSuccess

List of usage examples for io.netty.util.concurrent Future isSuccess

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future isSuccess.

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

From source file:org.vootoo.client.netty.connect.SimpleConnectionPool.java

License:Apache License

public Channel acquireConnect() throws NettyConnectLessException {
    Future<Channel> future = acquire();

    // see https://netty.io/4.0/api/io/netty/channel/ChannelFuture.html
    // use bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    // so await without timeout
    future.awaitUninterruptibly();//from  w  w  w. j  a v a  2 s  .co m

    assert future.isDone();

    if (future.isCancelled()) {
        // Connection attempt cancelled by user
        throw new NettyConnectLessException("connection cancelled tcp=" + socketAddress);
    } else if (!future.isSuccess()) {
        throw new NettyConnectLessException(
                "connect tcp=" + socketAddress + " fail within " + connectTimeout + "ms time!", future.cause());
    } else {
        // Connection established successfully
        Channel channel = future.getNow();

        if (logger.isDebugEnabled()) {
            logger.debug("acquire connect success channel={}", channel);
        }

        assert channel != null;

        if (channel == null) {
            throw new NettyConnectLessException("connect tcp=" + socketAddress + " fail within "
                    + connectTimeout + "ms time, future.getNow return null!");
        }

        return channel;
    }
}

From source file:org.waarp.common.crypto.ssl.WaarpSslUtility.java

License:Open Source License

/**
 * Wait for the handshake on the given channel (better to use addSslHandler when handler is added after channel is active)
 * /*  w w w  . ja va  2s .co m*/
 * @param channel
 * @return True if the Handshake is done correctly
 */
public static boolean waitForHandshake(Channel channel) {
    final ChannelHandler handler = channel.pipeline().first();
    if (handler instanceof SslHandler) {
        logger.debug("Start handshake SSL: " + channel);
        final SslHandler sslHandler = (SslHandler) handler;
        // Get the SslHandler and begin handshake ASAP.
        // Get notified when SSL handshake is done.
        Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
        try {
            handshakeFuture.await(sslHandler.getHandshakeTimeoutMillis() + 100);
        } catch (InterruptedException e1) {
        }
        logger.debug("Handshake: " + handshakeFuture.isSuccess() + ": " + channel, handshakeFuture.cause());
        if (!handshakeFuture.isSuccess()) {
            channel.close();
            return false;
        }
        return true;
    } else {
        logger.error("SSL Not found but connected: " + handler.getClass().getName());
        return true;
    }
}

From source file:org.waarp.ftp.core.data.handler.ftps.FtpsTemporaryFirstHandler.java

License:Open Source License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    // Get the SslHandler in the current pipeline.
    Channel channel = ctx.channel();

    if (session == null) {
        setSession(channel);/*from   ww w .  ja v a2  s.c  om*/
    }
    if (session == null) {
        logger.error("Cannot find session for SSL");
        return;
    }
    // Server: no renegotiation still, but possible clientAuthent
    // Mode is always as SSL Server mode.
    SslHandler sslHandler = FtpsInitializer.waarpSslContextFactory.initInitializer(true,
            FtpsInitializer.waarpSslContextFactory.needClientAuthentication(),
            FtpChannelUtils.getRemoteInetSocketAddress(session.getControlChannel()).getAddress()
                    .getHostAddress(),
            FtpChannelUtils.getRemoteInetSocketAddress(session.getControlChannel()).getPort());
    WaarpSslUtility.addSslOpenedChannel(channel);
    // Get the SslHandler and begin handshake ASAP.
    logger.debug("SSL found but need handshake: " + ctx.channel().toString());
    final FtpsTemporaryFirstHandler myself = this;
    WaarpSslUtility.addSslHandler(null, ctx.pipeline(), sslHandler,
            new GenericFutureListener<Future<? super Channel>>() {
                public void operationComplete(Future<? super Channel> future) throws Exception {
                    logger.debug("Handshake: " + future.isSuccess() + ":" + ((Channel) future.get()).toString(),
                            future.cause());
                    if (future.isSuccess()) {
                        logger.debug("End of initialization of SSL and data channel");
                        myself.superChannelActive(ctx);
                        ctx.pipeline().remove(myself);
                    } else {
                        ctx.close();
                    }
                }
            });
}

From source file:org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel networkChannel = ctx.channel();
    logger.debug("Add channel to ssl");
    WaarpSslUtility.addSslOpenedChannel(networkChannel);
    isSSL = true;//from   w  w  w . j  a  v a2s.com
    // Check first if allowed
    if (NetworkTransaction.isBlacklisted(networkChannel)) {
        logger.warn("Connection refused since Partner is in BlackListed from "
                + networkChannel.remoteAddress().toString());
        isBlackListed = true;
        if (Configuration.configuration.getR66Mib() != null) {
            Configuration.configuration.getR66Mib().notifyError("Black Listed connection temptative",
                    "During Handshake");
        }
        // close immediately the connection
        WaarpSslUtility.closingSslChannel(networkChannel);
        return;
    }
    // Get the SslHandler in the current pipeline.
    // We added it in NetworkSslServerInitializer.
    final ChannelHandler handler = ctx.pipeline().first();
    if (handler instanceof SslHandler) {
        final SslHandler sslHandler = (SslHandler) handler;
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            public void operationComplete(Future<? super Channel> future) throws Exception {
                if (!future.isSuccess()) {
                    if (Configuration.configuration.getR66Mib() != null) {
                        Configuration.configuration.getR66Mib().notifyError("SSL Connection Error",
                                "During Handshake");
                    }
                }
            }
        });
    } else {
        logger.error("SSL Not found");
    }
    super.channelActive(ctx);
}

From source file:org.waarp.openr66.proxy.network.ssl.NetworkSslServerHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    logger.debug("Add channel to ssl");
    WaarpSslUtility.addSslOpenedChannel(channel);
    isSSL = true;//from  w ww  .  j a va2  s . c o m
    // Get the SslHandler in the current pipeline.
    // We added it in NetworkSslServerInitializer.
    final ChannelHandler handler = ctx.pipeline().first();
    if (handler instanceof SslHandler) {
        final SslHandler sslHandler = (SslHandler) handler;
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            public void operationComplete(Future<? super Channel> future) throws Exception {
                if (!future.isSuccess()) {
                    if (Configuration.configuration.getR66Mib() != null) {
                        Configuration.configuration.getR66Mib().notifyError("SSL Connection Error",
                                "During Handshake");
                    }
                }
            }
        });
    } else {
        logger.error("SSL Not found");
    }
    super.channelActive(ctx);
}

From source file:org.wyb.sows.client.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    if (request.host().equals("127.0.0.1") || request.host().equals("localhost")) {
        System.err.println("Not able to establish bridge. Inform proxy client.");
        ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
        SocksServerUtils.closeOnFlush(ctx.channel());
    }/* w  ww. j  a  v  a2 s .  c om*/

    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                if (SocksServer.isDebug) {
                    System.out.println("Bridge is established. Inform proxy client.");
                }
                SocksCmdResponse resp = new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType());
                resp.setProtocolVersion(request.protocolVersion());
                ctx.channel().writeAndFlush(resp).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) {
                        ChannelPipeline pipeline = ctx.pipeline();
                        pipeline.remove(SocksServerConnectHandler.this);
                        // ctx.pipeline().addLast(new StringByteCodec());
                        pipeline.addLast(new WebSocketRelayHandler(outboundChannel));
                    }
                });
            } else {
                System.err.println("Not able to establish bridge. Inform proxy client.");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
    final Channel inboundChannel = ctx.channel();

    // Add authentication headers
    HttpHeaders authHeader = new DefaultHttpHeaders();
    authHeader.add(SowsAuthHelper.HEADER_SOWS_USER, this.userName);
    byte[] nonce = SowsAuthHelper.randomBytes(16);
    String seed = SowsAuthHelper.base64(nonce);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_SEED, seed);
    byte[] sha1 = SowsAuthHelper.sha1((this.passcode + seed).getBytes(CharsetUtil.US_ASCII));
    String token = SowsAuthHelper.base64(sha1);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_TOKEN, token);

    // initiating websocket client handler
    final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
            .newHandshaker(bridgeServiceUri, WebSocketVersion.V13, null, false, authHeader), promise,
            request.host(), request.port(), inboundChannel);
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                }
            });
    if (SocksServer.isDebug) {
        System.out.println("Try to connect to bridge service.");
    }
    b.connect(bridgeServiceUri.getHost(), bridgeServiceUri.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
                if (SocksServer.isDebug) {
                    System.out.printf("Brige service connection is established. host=%s,port=%d \r\n",
                            bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                }
            } else {
                // Close the connection if the connection attempt has
                // failed.
                System.err.printf("Not able to connect bridge service! host=%s,port=%d \r\n",
                        bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

}

From source file:org.wyb.sows.client.WebSocketClientHandler.java

License:Apache License

@Override
public void handlerAdded(ChannelHandlerContext ctx) {
    handshakeFuture = ctx.newPromise();/*from ww  w.j a  v  a2s.c  o m*/
    handshakeFuture.addListener(new GenericFutureListener<Future<Void>>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            // send out target host and port to remote service.
            if (future.isSuccess()) {
                SowsConnectCmd cmd = new SowsConnectCmd();
                cmd.setHost(targetHost);
                cmd.setPort(targetPort);
                if (SocksServer.isDebug) {
                    System.out.printf("Send remote connection request: %s \r\n", cmd);
                }
                WebSocketFrame frame = new TextWebSocketFrame(cmd.encode());
                ctx.writeAndFlush(frame);
            } else {
                promise.setFailure(new Exception("Bridge service handshake failed!"));
            }
        }

    });
}

From source file:pers.zlf.sslocal.handler.shadowsocks.ShadowsocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    final Option option = ShadowsocksClient.getShadowsocksOption(ctx.channel());
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*  w w w  .  j  a  v a 2  s. c o m*/
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                ctx.pipeline().remove(ShadowsocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(
                                        new ShadowsocksMessageCodec(CryptoFactory
                                                .createCrypto(option.getMethod(), option.getPassword())),
                                        new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));

                                outboundChannel.writeAndFlush(request);
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                ChannelUtils.closeOnFlush(ctx.channel());
            }
        }
    });

    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new DirectClientHandler(promise));

    b.connect(option.getRemoteHost(), option.getRemotePort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                if (logger.isErrorEnabled()) {
                    logger.error("Failed to connect shadowsocks server", future.cause());
                }

                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                ChannelUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:reactor.io.net.impl.netty.tcp.NettyTcpClient.java

License:Apache License

@Override
protected Promise<Void> doShutdown() {

    if (nettyOptions != null && nettyOptions.eventLoopGroup() != null) {
        return Promises.success();
    }//from   w  ww . ja v a 2 s  . c o m

    final Promise<Void> promise = Promises.prepare();

    ioGroup.shutdownGracefully().addListener(new FutureListener<Object>() {
        @Override
        public void operationComplete(Future<Object> future) throws Exception {
            if (future.isDone() && future.isSuccess()) {
                promise.onComplete();
            } else {
                promise.onError(future.cause());
            }
        }
    });
    return promise;
}

From source file:reactor.io.net.netty.tcp.NettyTcpClient.java

License:Apache License

@Override
public void close(@Nullable final Consumer<Boolean> onClose) {
    if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) {
        ioGroup.submit(new Runnable() {
            @Override// ww w .  j a  v  a 2 s .  c o  m
            public void run() {
                if (null != onClose) {
                    onClose.accept(true);
                }
            }
        });
    } else {
        ioGroup.shutdownGracefully().addListener(new FutureListener<Object>() {
            @Override
            public void operationComplete(Future<Object> future) throws Exception {
                if (null != onClose) {
                    onClose.accept(future.isDone() && future.isSuccess());
                }
            }
        });
    }
}