Example usage for io.netty.channel ChannelInitializer ChannelInitializer

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

Introduction

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

Prototype

ChannelInitializer

Source Link

Usage

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

License:Open Source License

/**
 * Asynchronously connects to the APNs gateway in this connection's environment. The outcome of the connection
 * attempt is reported via this connection's listener.
 *
 * @see ApnsConnectionListener#handleConnectionSuccess(ApnsConnection)
 * @see ApnsConnectionListener#handleConnectionFailure(ApnsConnection, Throwable)
 *//*from w w w.j ava  2  s .  com*/
@SuppressWarnings("deprecation")
public synchronized void connect() {

    final ApnsConnection<T> apnsConnection = this;

    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);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // TODO Remove this when Netty 5 is available
    bootstrap.option(ChannelOption.AUTO_CLOSE, false);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

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

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

            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("decoder", new RejectedNotificationDecoder());
            pipeline.addLast("encoder", new ApnsPushNotificationEncoder());
            pipeline.addLast("handler", new ApnsConnectionHandler(apnsConnection));
        }
    });

    log.debug("{} beginning connection process.", apnsConnection.name);
    this.connectFuture = bootstrap.connect(this.environment.getApnsGatewayHost(),
            this.environment.getApnsGatewayPort());
    this.connectFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        public void operationComplete(final ChannelFuture connectFuture) {
            if (connectFuture.isSuccess()) {
                log.debug("{} connected; waiting for TLS handshake.", apnsConnection.name);

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

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

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

                                apnsConnection.handshakeCompleted = true;
                                apnsConnection.listener.handleConnectionSuccess(apnsConnection);
                            } else {
                                log.debug("{} failed to complete TLS handshake with APNs gateway.",
                                        apnsConnection.name, handshakeFuture.cause());

                                connectFuture.channel().close();
                                apnsConnection.listener.handleConnectionFailure(apnsConnection,
                                        handshakeFuture.cause());
                            }
                        }
                    });
                } catch (NullPointerException e) {
                    log.warn("{} failed to get SSL handler and could not wait for a TLS handshake.",
                            apnsConnection.name);

                    connectFuture.channel().close();
                    apnsConnection.listener.handleConnectionFailure(apnsConnection, e);
                }
            } else {
                log.debug("{} failed to connect to APNs gateway.", apnsConnection.name, connectFuture.cause());

                apnsConnection.listener.handleConnectionFailure(apnsConnection, connectFuture.cause());
            }
        }
    });
}

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 ww w.  j a v a 2  s  .c  o 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>// w  w  w  .j ava  2s  . c  om
 */
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.relayrides.pushy.apns.MockApnsServer.java

License:Open Source License

public synchronized void start() throws InterruptedException {
    final ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    final MockApnsServer server = this;

    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override/*  w  w w  . j av  a2  s.  co m*/
        protected void initChannel(final SocketChannel channel) throws Exception {
            channel.pipeline().addLast("ssl", new SslHandler(SSLTestUtil.createSSLEngineForMockServer()));
            channel.pipeline().addLast("encoder", new ApnsErrorEncoder());
            channel.pipeline().addLast("decoder", new ApnsPushNotificationDecoder());
            channel.pipeline().addLast("handler", new MockApnsServerHandler(server));
        }
    });

    this.channel = bootstrap.bind(this.port).await().channel();
}

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

License:Open Source License

public synchronized void start() throws InterruptedException {
    final ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioServerSocketChannel.class);

    final MockFeedbackServer server = this;
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override// w ww  .  j  a  va 2  s .c o  m
        protected void initChannel(final SocketChannel channel) throws Exception {
            channel.pipeline().addLast("ssl", new SslHandler(SSLTestUtil.createSSLEngineForMockServer()));
            channel.pipeline().addLast("encoder", new ExpiredTokenEncoder());
            channel.pipeline().addLast("handler", new MockFeedbackServerHandler(server));
        }
    });

    this.channel = bootstrap.bind(this.port).await().channel();
}

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) {/*from www . j  a  va  2s .  c om*/
        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.ja  v  a 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) {//w  w w.j  a va  2  s  .  co  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 {//from   ww w.  j  ava2 s . c  o  m
        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. j  a  v  a 2 s  .c  om
        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();
    }
}