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:blazingcache.network.netty.NettyChannel.java

License:Apache License

@Override
public void sendOneWayMessage(Message message, SendResultCallback callback) {
    if (message.getMessageId() == null) {
        message.setMessageId(UUID.randomUUID().toString());
    }/* ww w.  j a  v  a 2 s  .  c  o  m*/
    SocketChannel _socket = this.socket;
    if (_socket == null || !_socket.isOpen()) {
        callback.messageSent(message, new Exception(this + " connection is closed"));
        return;
    }
    _socket.writeAndFlush(message).addListener(new GenericFutureListener() {

        @Override
        public void operationComplete(Future future) throws Exception {
            if (future.isSuccess()) {
                callback.messageSent(message, null);
            } else {
                LOGGER.log(Level.SEVERE, this + ": error " + future.cause(), future.cause());
                callback.messageSent(message, future.cause());
                close();
            }
        }

    });
}

From source file:cc.agentx.client.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    boolean proxyMode = isAgentXNeeded(request.host());
    log.info("\tClient -> Proxy           \tTarget {}:{} [{}]", request.host(), request.port(),
            proxyMode ? "AGENTX" : "DIRECT");
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new FutureListener<Channel>() {
        @Override//from  www. jav  a2s  .com
        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(channelFuture -> {
                            ByteBuf byteBuf = Unpooled.buffer();
                            request.encodeAsByteBuf(byteBuf);
                            if (byteBuf.hasArray()) {
                                byte[] xRequestBytes = new byte[byteBuf.readableBytes()];
                                byteBuf.getBytes(0, xRequestBytes);

                                if (proxyMode) {
                                    // handshaking to remote proxy
                                    xRequestBytes = requestWrapper.wrap(xRequestBytes);
                                    outboundChannel.writeAndFlush(Unpooled.wrappedBuffer(
                                            exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes)));
                                }

                                // task handover
                                ReferenceCountUtil.retain(request); // auto-release? a trap?
                                ctx.pipeline().remove(XConnectHandler.this);
                                outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(),
                                        proxyMode ? wrapper : rawWrapper, false));
                                ctx.pipeline().addLast(new XRelayHandler(outboundChannel,
                                        proxyMode ? wrapper : rawWrapper, true));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));

                if (ctx.channel().isActive()) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    });

    String host = request.host();
    int port = request.port();
    if (host.equals(config.getConsoleDomain())) {
        host = "localhost";
        port = config.getConsolePort();
    } else if (proxyMode) {
        host = config.getServerHost();
        port = config.getServerPort();
    }

    // ping target
    bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.channel().writeAndFlush(
                                new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                        if (ctx.channel().isActive()) {
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        }
                    }
                }
            });
}

From source file:cc.agentx.server.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {/*from w w w  .  j  a  v  a 2 s  .c o m*/
        ByteBuf byteBuf = (ByteBuf) msg;
        if (!byteBuf.hasArray()) {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(0, bytes);

            if (!requestParsed) {
                if (!exposedRequest) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes == null) {
                        log.info("\tClient -> Proxy           \tHalf Request");
                        return;
                    }
                }
                XRequest xRequest = requestWrapper.parse(bytes);
                String host = xRequest.getHost();
                int port = xRequest.getPort();
                int dataLength = xRequest.getSubsequentDataLength();
                if (dataLength > 0) {
                    byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length);
                    if (exposedRequest) {
                        tailData = wrapper.unwrap(tailData);
                        if (tailData != null) {
                            tailDataBuffer.write(tailData, 0, tailData.length);
                        }
                    } else {
                        tailDataBuffer.write(tailData, 0, tailData.length);
                    }
                }
                log.info("\tClient -> Proxy           \tTarget {}:{}{}", host, port,
                        DnsCache.isCached(host) ? " [Cached]" : "");
                if (xRequest.getAtyp() == XRequest.Type.DOMAIN) {
                    try {
                        host = DnsCache.get(host);
                        if (host == null) {
                            host = xRequest.getHost();
                        }
                    } catch (UnknownHostException e) {
                        log.warn("\tClient <- Proxy           \tBad DNS! ({})", e.getMessage());
                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        return;
                    }
                }

                Promise<Channel> promise = ctx.executor().newPromise();
                promise.addListener(new FutureListener<Channel>() {
                    @Override
                    public void operationComplete(final Future<Channel> future) throws Exception {
                        final Channel outboundChannel = future.getNow();
                        if (future.isSuccess()) {
                            // handle tail
                            byte[] tailData = tailDataBuffer.toByteArray();
                            tailDataBuffer.close();
                            if (tailData.length > 0) {
                                log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length);
                            }
                            outboundChannel
                                    .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData)
                                            : Unpooled.EMPTY_BUFFER)
                                    .addListener(channelFuture -> {
                                        // task handover
                                        outboundChannel.pipeline()
                                                .addLast(new XRelayHandler(ctx.channel(), wrapper, false));
                                        ctx.pipeline()
                                                .addLast(new XRelayHandler(outboundChannel, wrapper, true));
                                        ctx.pipeline().remove(XConnectHandler.this);
                                    });

                        } else {
                            if (ctx.channel().isActive()) {
                                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

                final String finalHost = host;
                bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (!future.isSuccess()) {
                                    if (ctx.channel().isActive()) {
                                        log.warn("\tClient <- Proxy           \tBad Ping! ({}:{})", finalHost,
                                                port);
                                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                                .addListener(ChannelFutureListener.CLOSE);
                                    }
                                }
                            }
                        });

                requestParsed = true;
            } else {
                bytes = wrapper.unwrap(bytes);
                if (bytes != null)
                    tailDataBuffer.write(bytes, 0, bytes.length);
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:cc.ly.mc.client.netty.SocketClient.java

License:Apache License

public void write(Message message) {
    channel.writeAndFlush(message).addListener(new GenericFutureListener<Future<Void>>() {
        @Override//from  w w w . j  a  v  a  2  s  . c o  m
        public void operationComplete(Future future) throws Exception {
            if (!future.isSuccess()) {
                System.out.println("failed to send message");
            }
        }
    });
}

From source file:cn.david.socks.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override// ww w. ja va  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(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.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(request.host(), request.port()).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.
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:com.addthis.hydra.query.tracker.DetailedStatusHandler.java

License:Apache License

@Override
public void operationComplete(Future<TaskSourceInfo[]> future) throws Exception {
    if (future.isSuccess()) {
        try {/*ww  w .j  a  v a2  s  . c  om*/
            TaskSourceInfo[] taskSourceInfos = future.get();
            QueryEntryInfo queryEntryInfo = queryEntry.getStat();
            long exactLines = 0;
            for (TaskSourceInfo taskSourceInfo : taskSourceInfos) {
                exactLines += taskSourceInfo.lines;
            }
            queryEntryInfo.lines = exactLines;
            queryEntryInfo.tasks = taskSourceInfos;
            onSuccess(queryEntryInfo);
        } catch (Throwable t) {
            onFailure(t);
        }
    } else {
        onFailure(future.cause());
    }
}

From source file:com.addthis.hydra.query.web.DetailedStatusHandler.java

License:Apache License

@Override
public void operationComplete(Future<QueryEntryInfo> future) throws Exception {
    if (future.isSuccess()) {
        onSuccess(future.get());/*from   ww  w  .  j  av a2s.  co  m*/
    } else {
        onFailure(future.cause());
    }
}

From source file:com.addthis.meshy.MeshyServer.java

License:Apache License

public MeshyServer(final int port, final File rootDir, @Nullable String[] netif, final MeshyServerGroup group)
        throws IOException {
    super();/*from  w w w  .j  a va2  s .c  o  m*/
    this.group = group;
    this.rootDir = rootDir;
    this.filesystems = loadFileSystems(rootDir);
    this.serverPeers = new AtomicInteger(0);
    bossGroup = new NioEventLoopGroup(1);
    ServerBootstrap bootstrap = new ServerBootstrap()
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK)
            .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK)
            .channel(NioServerSocketChannel.class).group(bossGroup, workerGroup)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelState(MeshyServer.this, ch));
                }
            });
    /* bind to one or more interfaces, if supplied, otherwise all */
    if ((netif == null) || (netif.length == 0)) {
        ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap.bind(new InetSocketAddress(port))
                .syncUninterruptibly().channel();
        serverLocal = serverChannel.localAddress();
    } else {
        InetSocketAddress primaryServerLocal = null;
        for (String net : netif) {
            NetworkInterface nicif = NetworkInterface.getByName(net);
            if (nicif == null) {
                log.warn("missing speficied NIC: {}", net);
                continue;
            }
            for (InterfaceAddress addr : nicif.getInterfaceAddresses()) {
                InetAddress inAddr = addr.getAddress();
                if (inAddr.getAddress().length != 4) {
                    log.trace("skip non-ipV4 address: {}", inAddr);
                    continue;
                }
                ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap
                        .bind(new InetSocketAddress(inAddr, port)).syncUninterruptibly().channel();
                if (primaryServerLocal != null) {
                    log.info("server [{}-*] binding to extra address: {}", super.getUUID(), primaryServerLocal);
                }
                primaryServerLocal = serverChannel.localAddress();
            }
        }
        if (primaryServerLocal == null) {
            throw new IllegalArgumentException("no valid interface / port specified");
        }
        serverLocal = primaryServerLocal;
    }
    this.serverNetIf = NetworkInterface.getByInetAddress(serverLocal.getAddress());
    this.serverPort = serverLocal.getPort();
    if (serverNetIf != null) {
        serverUuid = super.getUUID() + "-" + serverPort + "-" + serverNetIf.getName();
    } else {
        serverUuid = super.getUUID() + "-" + serverPort;
    }
    log.info("server [{}] on {} @ {}", getUUID(), serverLocal, rootDir);
    closeFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
    workerGroup.terminationFuture().addListener((Future<Object> workerFuture) -> {
        bossGroup.terminationFuture().addListener((Future<Object> bossFuture) -> {
            if (!workerFuture.isSuccess()) {
                closeFuture.tryFailure(workerFuture.cause());
            } else if (!bossFuture.isSuccess()) {
                closeFuture.tryFailure(bossFuture.cause());
            } else {
                closeFuture.trySuccess(null);
            }
        });
    });
    addMessageFileSystemPaths();
    group.join(this);
    if (autoMesh) {
        startAutoMesh(serverPort, autoMeshTimeout);
    }
}

From source file:com.barchart.netty.server.pipeline.NegotiationHandler.java

License:BSD License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {

    if (msg instanceof Capabilities) {

        ctx.writeAndFlush(new Capabilities() {

            @Override//from   ww  w .ja  v a  2  s .co  m
            public Set<String> capabilities() {
                return capabilities;
            }

            @Override
            public Version version() {
                return version;
            }

            @Override
            public Version minVersion() {
                return minVersion;
            }

        });

    } else if (msg instanceof VersionRequest) {

        final VersionRequest request = (VersionRequest) msg;

        final Version v = request.version();

        if (minVersion.lessThanOrEqual(v) && version.greaterThanOrEqual(v)) {

            activeVersion = v;

            ctx.writeAndFlush(new VersionResponse() {

                @Override
                public boolean success() {
                    return true;
                }

                @Override
                public Version version() {
                    return v;
                }

            });

        } else {

            ctx.writeAndFlush(new VersionResponse() {

                @Override
                public boolean success() {
                    return false;
                }

                @Override
                public Version version() {
                    return version;
                }

            });

        }

    } else if (msg instanceof StartTLS) {

        // TODO Use a specific SSL cert?
        final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine();
        sslEngine.setUseClientMode(false);

        final SslHandler handler = new SslHandler(sslEngine, true);

        handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {

            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {

                if (future.isSuccess()) {

                    secure = true;

                } else {

                    secure = false;

                    // Failed, remove handler
                    ctx.pipeline().remove(SslHandler.class);

                }

            }

        });

        // Add SslHandler to pipeline
        ctx.pipeline().addFirst(handler);

        // Confirm start TLS, initiate handshake
        ctx.writeAndFlush(new StartTLS() {
        });

    } else {

        ctx.fireChannelRead(msg);

        // First non-negotiation message, we're done - clean up pipeline
        if (cleanup) {

            ctx.pipeline().remove(this);

            if (linked != null) {
                for (final ChannelHandler handler : linked) {
                    ctx.pipeline().remove(handler);
                }
            }

        }

    }

}

From source file:com.barchart.netty.server.pipeline.StartTLSHandler.java

License:BSD License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final StartTLS msg) throws Exception {

    // TODO Use a specific SSL cert?
    final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine();
    sslEngine.setUseClientMode(false);//from   ww  w  . j  a v  a2  s.  c o m

    final SslHandler handler = new SslHandler(sslEngine, true);

    handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {

            if (future.isSuccess()) {

                secure = true;

            } else {

                secure = false;

                // Failed, remove handler
                ctx.pipeline().remove(SslHandler.class);

            }

        }

    });

    // Add SslHandler to pipeline
    ctx.pipeline().addFirst(handler);

    // Confirm start TLS, initiate handshake
    ctx.writeAndFlush(new StartTLS() {
    });

}