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.relayrides.pushy.apns.FeedbackServiceClient.java

License:Open Source License

/**
 * <p>Retrieves a list of expired tokens from the APNs feedback service. Be warned that this is a
 * <strong>destructive operation</strong>. According to Apple's documentation:</p>
 *
 * <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback
 * service, the information it returns lists only the failures that have happened since you last
 * connected.</blockquote>/*from   w  ww.  ja v  a  2  s .  co  m*/
 *
 * @param timeout the time after the last received data after which the connection to the feedback service should
 * be closed
 * @param timeoutUnit the unit of time in which the given {@code timeout} is measured
 *
 * @return a list of tokens that have expired since the last connection to the feedback service
 *
 * @throws InterruptedException if interrupted while waiting for a response from the feedback service
 * @throws FeedbackConnectionException if the connection to the feedback service failed for any reason
 */
public synchronized List<ExpiredToken> getExpiredTokens(final long timeout, final TimeUnit timeoutUnit)
        throws InterruptedException, FeedbackConnectionException {

    this.expiredTokens.clear();

    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);

    final FeedbackServiceClient feedbackClient = this;
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();

            final SSLEngine sslEngine = feedbackClient.sslContext.createSSLEngine();
            sslEngine.setUseClientMode(true);

            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(timeout, timeoutUnit));
            pipeline.addLast("decoder", new ExpiredTokenDecoder());
            pipeline.addLast("handler", new FeedbackClientHandler(feedbackClient));
        }

    });

    final ChannelFuture connectFuture = bootstrap
            .connect(this.environment.getFeedbackHost(), this.environment.getFeedbackPort()).await();

    if (connectFuture.isSuccess()) {
        log.debug("Connected to feedback service.");

        final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class);

        if (sslHandler != null) {
            final Future<Channel> handshakeFuture = sslHandler.handshakeFuture().await();

            if (handshakeFuture.isSuccess()) {
                log.debug("Completed TLS handshake with feedback service.");

                // The feedback service will send us a list of device tokens as soon as we complete the SSL
                // handshake, then hang up. While we're waiting to sync with the connection closure, we'll be
                // receiving messages from the feedback service from another thread.
                connectFuture.channel().closeFuture().await();
            } else {
                log.debug("Failed to complete TLS handshake with feedback service.", handshakeFuture.cause());

                connectFuture.channel().close().await();
                throw new FeedbackConnectionException(handshakeFuture.cause());
            }
        } else {
            log.warn("Feedback client failed to get SSL handler and could not wait for TLS handshake.");

            connectFuture.channel().close().await();
            throw new FeedbackConnectionException(null);
        }
    } else {
        log.debug("Failed to connect to feedback service.", connectFuture.cause());
        throw new FeedbackConnectionException(connectFuture.cause());
    }

    return new ArrayList<ExpiredToken>(this.expiredTokens);
}

From source file:com.relayrides.pushy.apns.FeedbackServiceConnection.java

License:Open Source License

/**
 * <p>Connects to the APNs feedback service and waits for expired tokens to arrive. Be warned that this is a
 * <strong>destructive operation</strong>. According to Apple's documentation:</p>
 *
 * <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback
 * service, the information it returns lists only the failures that have happened since you last
 * connected.</blockquote>/*from   ww  w .j a  v  a  2  s .  co  m*/
 */
public synchronized void connect() {

    if (this.connectFuture != null) {
        throw new IllegalStateException(String.format("%s already started a connection attempt.", this.name));
    }

    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);

    final FeedbackServiceConnection feedbackConnection = this;
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();

            final SSLEngine sslEngine = feedbackConnection.sslContext.createSSLEngine();
            sslEngine.setUseClientMode(true);

            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("readTimeoutHandler",
                    new ReadTimeoutHandler(feedbackConnection.configuration.getReadTimeout()));
            pipeline.addLast("decoder", new ExpiredTokenDecoder());
            pipeline.addLast("handler", new FeedbackClientHandler(feedbackConnection));
        }
    });

    this.connectFuture = bootstrap.connect(this.environment.getFeedbackHost(),
            this.environment.getFeedbackPort());
    this.connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(final ChannelFuture connectFuture) {

            if (connectFuture.isSuccess()) {
                log.debug("{} connected; waiting for TLS handshake.", feedbackConnection.name);

                final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class);

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

                        @Override
                        public void operationComplete(final Future<Channel> handshakeFuture) {
                            if (handshakeFuture.isSuccess()) {
                                log.debug("{} successfully completed TLS handshake.", feedbackConnection.name);

                                if (feedbackConnection.listener != null) {
                                    feedbackConnection.listener.handleConnectionSuccess(feedbackConnection);
                                }

                            } else {
                                log.debug("{} failed to complete TLS handshake with APNs feedback service.",
                                        feedbackConnection.name, handshakeFuture.cause());

                                connectFuture.channel().close();

                                if (feedbackConnection.listener != null) {
                                    feedbackConnection.listener.handleConnectionFailure(feedbackConnection,
                                            handshakeFuture.cause());
                                }
                            }
                        }
                    });
                } catch (NullPointerException e) {
                    log.warn("{} failed to get SSL handler and could not wait for a TLS handshake.",
                            feedbackConnection.name);

                    connectFuture.channel().close();

                    if (feedbackConnection.listener != null) {
                        feedbackConnection.listener.handleConnectionFailure(feedbackConnection, e);
                    }
                }
            } else {
                log.debug("{} failed to connect to APNs feedback service.", feedbackConnection.name,
                        connectFuture.cause());

                if (feedbackConnection.listener != null) {
                    feedbackConnection.listener.handleConnectionFailure(feedbackConnection,
                            connectFuture.cause());
                }
            }
        }
    });
}

From source file:com.replaymod.sponge.recording.spongecommon.SpongeImplementation.java

License:MIT License

@Listener
public void hookChannels(GameInitializationEvent event) {
    Game game = event.getGame();/*from   ww  w.j av  a2 s .com*/
    Server server = game.getServer();
    Method getNetworkSystem = null;
    for (Method m : server.getClass().getMethods()) {
        if ("net.minecraft.network.NetworkSystem".equals(m.getReturnType().getName())) {
            getNetworkSystem = m;
        }
    }
    if (getNetworkSystem == null) {
        throw new RuntimeException("Could not find getNetworkSystem in " + server);
    }
    try {
        Object networkSystem = getNetworkSystem.invoke(server);
        SpongeChannelInitializer channelInitializer = new SpongeChannelInitializer(game);
        @SuppressWarnings("unchecked")
        List<ChannelFuture> endpoints = (List) Reflection.getField(networkSystem.getClass(), "field_151274_e",
                networkSystem);
        for (ChannelFuture endpoint : endpoints) {
            endpoint.channel().pipeline().addFirst(channelInitializer);
        }
    } catch (IllegalAccessException | NoSuchFieldException | InvocationTargetException e) {
        e.printStackTrace();
    }
}

From source file:com.repo.netty.proxy.HexDumpProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override//w w w  .jav a2s .  com
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:com.robert.NettyProject.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {/* w w w .ja v  a  2  s  . com*/
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        p.addLast("encode", new StringEncoder());
                        p.addLast("decode", new StringDecoder());
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();
        Channel channel = f.channel();
        System.out.println("" + System.nanoTime());
        //         for(int i=0;i<10000;i++){            
        channel.writeAndFlush("hello");
        //         }

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.robert.NettyProject.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from   ww  w  .j  a va  2s .  c  o  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        p.addLast("encode", new StringEncoder());
                        p.addLast("decode", new StringDecoder());
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.rr.echoserver.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.out.println("Writing on separate threads: " + EchoServer.THREADED);

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  ww  w  . j  a v a2  s. c o  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.sample.netty.socket.client.Client.java

public static void main(String[] args) throws Exception {
    String host = "localhost";
    int port = 8080;
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  w ww  . j  a va2  s.  c  om
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new MessageDecoder(), new ClientHandlerInbound());
                ch.pipeline().addLast(new MessageEncoder(), new ClientHandlerOutbound());
            }
        });
        ChannelFuture f = b.connect(host, port).sync();
        f.channel().writeAndFlush(
                String.format("Usurio = '%s'", System.getProperties().getProperty("user.name")));
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.sample.netty.socket.server.Server.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w  w w  .  ja  v a  2s  .  c  o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MessageDecoder(), new ServerHandlerInbound());
                        ch.pipeline().addLast(new MessageEncoder(), new ServerHandlerOutbound());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.sangupta.swift.netty.proxy.ProxyBackendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext channelHandlerContext, Object message) {
    inboundChannel.writeAndFlush(message).addListener(new ChannelFutureListener() {

        @Override/*from  w  ww .j  a  v a2 s. c  o  m*/
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                channelHandlerContext.channel().read();
            } else {
                future.channel().close();
            }
        }

    });
}