Example usage for io.netty.channel ChannelFuture channel

List of usage examples for io.netty.channel ChannelFuture channel

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture channel.

Prototype

Channel channel();

Source Link

Document

Returns a channel where the I/O operation associated with this future takes place.

Usage

From source file:com.slyak.services.proxy.handler.Socks5CommandRequestHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext requestChannelContext,
        final DefaultSocks5CommandRequest msg) throws Exception {
    if (Socks5CommandType.CONNECT.equals(msg.type())) {
        log.debug("Start to connect remote server : {}:{}", msg.dstAddr(), msg.dstPort());
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(remoteEventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override//w  ww. ja v  a  2  s  . c  o m
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new IdleStateHandler(0, 0, 30));
                        pipeline.addLast(new IdleEventHandler());
                        pipeline.addLast(new Remote2RequestHandler(requestChannelContext.channel()));
                        pipeline.addLast(ExceptionHandler.INSTANCE);
                    }
                });
        final ChannelFuture future = bootstrap.connect(msg.dstAddr(), msg.dstPort());
        this.remoteChannel = future.channel();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(final ChannelFuture connectFuture) throws Exception {
                if (connectFuture.isSuccess()) {
                    log.debug("Connected to remote server");
                    requestChannelContext.pipeline().addLast(new Request2RemoteHandler(remoteChannel));
                    Socks5CommandResponse response = new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.SUCCESS, Socks5AddressType.IPv4);
                    //add client to dest handler to receive response
                    requestChannelContext.writeAndFlush(response);
                } else {
                    log.debug("Failed to connect to remote server");
                    Socks5CommandResponse commandResponse = new DefaultSocks5CommandResponse(
                            Socks5CommandStatus.FAILURE, Socks5AddressType.IPv4);
                    requestChannelContext.writeAndFlush(commandResponse);
                }
            }
        });
    } else {
        log.debug("Fire channel read");
        requestChannelContext.fireChannelRead(msg);
    }
}

From source file:com.slyak.services.proxy.server.NettyProxyServer.java

License:Apache License

@SneakyThrows(InterruptedException.class)
public void start() {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(proxyProperties.getBoss());
    workerGroup = new NioEventLoopGroup(proxyProperties.getWorker());
    clientGroup = new NioEventLoopGroup(proxyProperties.getClient());
    try {//  w  w w  .ja v a2  s .  com
        bootstrap.group(bossGroup, workerGroup).channel(getChannelClass())
                .option(ChannelOption.SO_BACKLOG, proxyProperties.getBackLog())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, proxyProperties.getConnectTimeout())

                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_REUSEADDR, true)

                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //channel time out handler
                        pipeline.addLast(new IdleStateHandler(0, 0, 30));
                        pipeline.addLast(new IdleEventHandler());
                        //logging
                        pipeline.addLast(new LoggingHandler());

                        if (isRouter()) {
                            pipeline.addLast(getProxyHandler(proxyProperties));
                        } else {
                            pipeline.addLast(getCustomChannelHandlers(clientGroup));
                        }
                        pipeline.addLast(ExceptionHandler.INSTANCE);
                    }
                });
        //start server
        ChannelFuture future = bootstrap.bind(proxyProperties.getPort()).sync();
        log.debug("Starting proxy server , port is {}", proxyProperties.getPort());
        future.channel().closeFuture().sync();
    } finally {
        stop();
    }
}

From source file:com.snh.chat.core.group.DefaultChannelGroupFuture.java

License:Apache License

/**
 * Creates a new instance./*from  w  w w.j  a  va 2  s.c  o  m*/
 */
DefaultChannelGroupFuture(ChannelGroup group, Collection<ChannelFuture> futures, EventExecutor executor) {
    super(executor);
    if (group == null) {
        throw new NullPointerException("group");
    }
    if (futures == null) {
        throw new NullPointerException("futures");
    }

    this.group = group;

    Map<Channel, ChannelFuture> futureMap = new LinkedHashMap<Channel, ChannelFuture>();
    for (ChannelFuture f : futures) {
        futureMap.put(f.channel(), f);
    }

    this.futures = Collections.unmodifiableMap(futureMap);

    for (ChannelFuture f : this.futures.values()) {
        f.addListener(childListener);
    }

    // Done on arrival?
    if (this.futures.isEmpty()) {
        setSuccess0();
    }
}

From source file:com.splicemachine.stream.ResultStreamer.java

License:Apache License

@Override
public Iterator<String> call(Integer partition, Iterator<T> locatedRowIterator) throws Exception {
    InetSocketAddress socketAddr = new InetSocketAddress(host, port);
    this.partition = partition;
    this.locatedRowIterator = locatedRowIterator;
    this.active = new CountDownLatch(1);
    taskContext = TaskContext.get();/*from   ww w.j av a 2  s .c o  m*/
    Bootstrap bootstrap;
    ThreadFactory tf = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("ResultStreamer-" + host + ":" + port + "[" + partition + "]").build();
    this.workerGroup = new NioEventLoopGroup(2, tf);

    try {

        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new OpenHandler(this));

        ChannelFuture futureConnect = bootstrap.connect(socketAddr).sync();

        active.await();
        long consumed = future.get();
        futureConnect.channel().closeFuture().sync();

        String result;
        if (consumed >= limit) {
            // We reached the limit, stop processing partitions
            result = "STOP";
        } else {
            // We didn't reach the limit, continue executing more partitions
            result = "CONTINUE";
        }
        return Arrays.asList(result).iterator();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.splicemachine.stream.StreamListenerServer.java

License:Apache License

public void start() throws StandardException {
    ThreadFactory tf = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("StreamerListenerServer-boss-%s").build();
    this.bossGroup = new NioEventLoopGroup(4, tf);
    tf = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("StreamerListenerServer-worker-%s").build();
    this.workerGroup = new NioEventLoopGroup(4, tf);
    try {/*from w w w. j  a v a2 s .co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new OpenHandler(this))
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync();

        this.serverChannel = f.channel();
        InetSocketAddress socketAddress = (InetSocketAddress) this.serverChannel.localAddress();
        String host = InetAddress.getLocalHost().getHostName();
        int port = socketAddress.getPort();

        this.hostAndPort = HostAndPort.fromParts(host, port);
        LOG.info("StreamListenerServer listening on " + hostAndPort);

    } catch (IOException e) {
        throw Exceptions.parseException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.spotify.ffwd.debug.NettyDebugServer.java

License:Apache License

public AsyncFuture<Void> start() {
    final ResolvableFuture<Void> future = async.future();

    final ServerBootstrap s = new ServerBootstrap();

    s.channel(NioServerSocketChannel.class);
    s.group(boss, worker);//from  w  w w. ja va 2 s . c om

    s.childHandler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            connected.add(ch);
            log.info("Connected {}", ch);

            ch.closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    connected.remove(ch);
                    log.info("Disconnected {}", ch);
                }
            });
        }
    });

    s.bind(localAddress).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture f) throws Exception {
            if (!f.isSuccess()) {
                future.fail(f.cause());
                return;
            }

            log.info("Bound to {}", localAddress);

            if (!server.compareAndSet(null, f.channel())) {
                f.channel().close();
                future.fail(new IllegalStateException("server already started"));
                return;
            }

            future.resolve(null);
        }
    });

    return future;
}

From source file:com.spotify.ffwd.protocol.RetryingProtocolConnection.java

License:Apache License

private void trySetup(final int attempt) {
    log.info("Attempt {}", action);

    final ChannelFuture connect = action.setup();

    connect.addListener(new ChannelFutureListener() {
        @Override//from  w  ww.  ja v a2  s . c o m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                log.info("Successful {}", action);
                setChannel(future.channel());
                return;
            }

            final long delay = policy.delay(attempt);

            log.warn("Failed {} (attempt: {}), retrying in {}s: {}", action, attempt + 1,
                    TimeUnit.SECONDS.convert(delay, TimeUnit.MILLISECONDS), future.cause().getMessage());

            timer.newTimeout(new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    if (stopped.get()) {
                        return;
                    }

                    trySetup(attempt + 1);
                }
            }, delay, TimeUnit.MILLISECONDS);
        }
    });
}

From source file:com.spotify.folsom.client.DefaultRawMemcacheClient.java

License:Apache License

public static ListenableFuture<RawMemcacheClient> connect(final HostAndPort address,
        final int outstandingRequestLimit, final boolean binary, final Executor executor,
        final long timeoutMillis) {

    final ChannelInboundHandler decoder;
    if (binary) {
        decoder = new BinaryMemcacheDecoder();
    } else {/*from ww w  .j  a  v a 2s  . co  m*/
        decoder = new AsciiMemcacheDecoder();
    }

    final ChannelHandler initializer = new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(new TcpTuningHandler(), decoder,

                    // Downstream
                    new MemcacheEncoder());
        }
    };

    final SettableFuture<RawMemcacheClient> clientFuture = SettableFuture.create();

    final Bootstrap bootstrap = new Bootstrap().group(EVENT_LOOP_GROUP).handler(initializer)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, SimpleSizeEstimator.INSTANCE);

    final ChannelFuture connectFuture = bootstrap
            .connect(new InetSocketAddress(address.getHostText(), address.getPort()));

    connectFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Create client
                final RawMemcacheClient client = new DefaultRawMemcacheClient(address, future.channel(),
                        outstandingRequestLimit, executor, timeoutMillis);
                clientFuture.set(client);
            } else {
                clientFuture.setException(future.cause());
            }
        }
    });

    return onExecutor(clientFuture, executor);
}

From source file:com.spotify.heroic.consumer.collectd.Server.java

License:Apache License

public static AsyncFuture<Server> setup(final AsyncFramework async, final CollectdChannelHandler handler,
        final InetAddress host, final int port) {
    final EventLoopGroup group = new NioEventLoopGroup();
    final Bootstrap b = new Bootstrap();

    b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(handler);

    final ResolvableFuture<Server> future = async.future();

    b.bind(host, port).addListener(new ChannelFutureListener() {
        @Override//from   w  w  w  .j  a v  a2s  .  c o  m
        public void operationComplete(final ChannelFuture f) throws Exception {
            if (f.isSuccess()) {
                future.resolve(new Server(async, f.channel()));
            } else {
                future.fail(f.cause() != null ? f.cause() : new RuntimeException("Failed to bind"));
            }
        }
    });

    return future;
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClient.java

License:Apache License

private <R> ChannelFutureListener handleConnect(final NativeRpcRequest request,
        final ResolvableFuture<R> future, final AtomicReference<Timeout> heartbeatTimeout,
        final Timeout requestTimeout) {
    return new ChannelFutureListener() {
        @Override//from  ww w  . j a v  a  2  s  .co  m
        public void operationComplete(ChannelFuture f) throws Exception {
            if (!f.isSuccess()) {
                future.fail(f.cause());
                return;
            }

            f.channel().writeAndFlush(request)
                    .addListener(handleRequestSent(future, heartbeatTimeout, requestTimeout));
        }
    };
}