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.github.ambry.rest.NettyClient.java

License:Open Source License

/**
 * Create a NettyClient./*  w  ww. jav a 2  s  . co  m*/
 * @param hostname the host to connect to.
 * @param port the port to connect to.
 */
public NettyClient(String hostname, int port) throws InterruptedException {
    this.hostname = hostname;
    this.port = port;
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new HttpClientCodec()).addLast(new ChunkedWriteHandler())
                    .addLast(communicationHandler);
        }
    });
    createChannel();
}

From source file:com.github.ambry.rest.NettyServerFactory.java

License:Open Source License

/**
 * Creates a new instance of NettyServerFactory.
 * @param verifiableProperties the in-memory {@link VerifiableProperties} to use.
 * @param metricRegistry the {@link MetricRegistry} to use.
 * @param requestHandler the {@link RestRequestHandler} that handles general requests.
 * @param publicAccessLogger the {@link PublicAccessLogger} that can be used for public access logging
 * @param restServerState the {@link RestServerState} that can be used to check the health of the system
 *                              to respond to health check requests
 * @throws IllegalArgumentException if any of the arguments are null.
 *//*from  w w w  . jav a 2  s . co m*/
public NettyServerFactory(VerifiableProperties verifiableProperties, MetricRegistry metricRegistry,
        final RestRequestHandler requestHandler, final PublicAccessLogger publicAccessLogger,
        final RestServerState restServerState) {
    if (verifiableProperties == null || metricRegistry == null || requestHandler == null
            || publicAccessLogger == null || restServerState == null) {
        throw new IllegalArgumentException("Null arg(s) received during instantiation of NettyServerFactory");
    } else {
        this.nettyConfig = new NettyConfig(verifiableProperties);
        this.nettyMetrics = new NettyMetrics(metricRegistry);
        channelInitializer = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ch.pipeline()
                        // for http encoding/decoding. Note that we get content in 8KB chunks and a change to that number has
                        // to go here.
                        .addLast("codec", new HttpServerCodec())
                        // for health check request handling
                        .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics))
                        // for public access logging
                        .addLast("publicAccessLogHandler",
                                new PublicAccessLogHandler(publicAccessLogger, nettyMetrics))
                        // for detecting connections that have been idle too long - probably because of an error.
                        .addLast("idleStateHandler",
                                new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds))
                        // for safe writing of chunks for responses
                        .addLast("chunker", new ChunkedWriteHandler())
                        // custom processing class that interfaces with a BlobStorageService.
                        .addLast("processor",
                                new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler));
            }
        };
    }
}

From source file:com.github.ambry.rest.NettyServerTest.java

License:Open Source License

/**
 * Gets an instance of {@link NettyServer}.
 * @param properties the in-memory {@link Properties} to use.
 * @return an instance of {@link NettyServer}.
 * @throws InstantiationException/*from  w  w  w .  j ava2s  . c  o  m*/
 * @throws IOException
 */
private NettyServer getNettyServer(Properties properties) throws InstantiationException, IOException {
    if (properties == null) {
        // dud properties. should pick up defaults
        properties = new Properties();
    }
    VerifiableProperties verifiableProperties = new VerifiableProperties(properties);
    final NettyConfig nettyConfig = new NettyConfig(verifiableProperties);
    final NettyMetrics nettyMetrics = new NettyMetrics(new MetricRegistry());
    final RestRequestHandler requestHandler = new MockRestRequestResponseHandler();
    final PublicAccessLogger publicAccessLogger = new PublicAccessLogger(new String[] {}, new String[] {});
    final RestServerState restServerState = new RestServerState("/healthCheck");
    return new NettyServer(nettyConfig, nettyMetrics, new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) {
            ch.pipeline()
                    // for http encoding/decoding. Note that we get content in 8KB chunks and a change to that number has
                    // to go here.
                    .addLast("codec", new HttpServerCodec())
                    // for health check request handling
                    .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics))
                    // for public access logging
                    .addLast("publicAccessLogHandler",
                            new PublicAccessLogHandler(publicAccessLogger, nettyMetrics))
                    // for detecting connections that have been idle too long - probably because of an error.
                    .addLast("idleStateHandler",
                            new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds))
                    // for safe writing of chunks for responses
                    .addLast("chunker", new ChunkedWriteHandler())
                    // custom processing class that interfaces with a BlobStorageService.
                    .addLast("processor", new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler));
        }
    });
}

From source file:com.github.ambry.tools.perf.rest.NettyPerfClient.java

License:Open Source License

/**
 * Starts the NettyPerfClient.//from  ww  w . j a  v a 2s  .co  m
 * @throws InterruptedException
 */
protected void start() {
    logger.info("Starting NettyPerfClient");
    reporter.start();
    group = new NioEventLoopGroup(concurrency);
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (sslFactory != null) {
                ch.pipeline().addLast(
                        new SslHandler(sslFactory.createSSLEngine(host, port, SSLFactory.Mode.CLIENT)));
            }
            ch.pipeline().addLast(new HttpClientCodec()).addLast(new ChunkedWriteHandler())
                    .addLast(new ResponseHandler());
        }
    });
    logger.info("Connecting to {}:{}", host, port);
    b.remoteAddress(host, port);
    perfClientStartTime = System.currentTimeMillis();
    for (int i = 0; i < concurrency; i++) {
        b.connect().addListener(channelConnectListener);
    }
    isRunning = true;
    logger.info("Created {} channel(s)", concurrency);
    logger.info("NettyPerfClient started");
}

From source file:com.github.brandtg.switchboard.LogReceiver.java

License:Apache License

/**
 * A server that listens for log regions and pipes them to an output stream.
 *
 * @param address/*from   w  ww  .ja  v  a  2 s.  com*/
 *  The socket address on which to listen
 * @param eventExecutors
 *  The Netty executor service to use for incoming traffic
 * @param outputStream
 *  The output stream to which all data should be piped
 */
public LogReceiver(InetSocketAddress address, EventLoopGroup eventExecutors, final OutputStream outputStream) {
    this.address = address;
    this.isShutdown = new AtomicBoolean(true);
    this.listeners = new HashSet<Object>();
    this.serverBootstrap = new ServerBootstrap().group(eventExecutors).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline()
                            .addLast(new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET,
                                    LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP));
                    ch.pipeline().addLast(new LogMessageHandler(outputStream, listeners));
                }
            });
}

From source file:com.github.brandtg.switchboard.LogRegionResource.java

License:Apache License

/**
 * Creates a resource that can serve log regions.
 *
 * @param eventExecutors The Netty executors used to send log regions asynchronously
 * @param logIndex       Used to determine which file regions to send
 * @param logReader      Used to physically read file regions if async is not used
 *//*from   ww w  .j a  v a 2 s. c o m*/
public LogRegionResource(EventLoopGroup eventExecutors, LogIndex logIndex, LogReader logReader) {
    this.logIndex = logIndex;
    this.logReader = logReader;
    this.bootstrap = new Bootstrap().group(eventExecutors).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new LengthFieldPrepender(4));
                    channel.pipeline().addLast(new ChunkedWriteHandler());
                }
            });
}

From source file:com.github.herong.rpc.netty.protobuf.demo1.ProtobufClient.java

License:Apache License

public void run() throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {/* w  w w .j av a  2s .c  o  m*/
        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 {
                        ch.pipeline()

                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(AddressBookProtos.AddressBook.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new ProtobufClientHandler());

                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();

        sendMsg(f.channel());
        // 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.github.herong.rpc.netty.protobuf.demo1.ProtobufServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*www  . ja v a  2  s. c  om*/
        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 {
                        ch.pipeline()
                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(AddressBookProtos.AddressBook.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new ProtobufServerHandler());
                    }
                });

        // 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.github.herong.rpc.netty.protobuf.demo2.Demo2ProtobufClient.java

License:Apache License

public void run() throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from  w ww  .jav a  2  s . co m
        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 {
                        ch.pipeline()

                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(Message.DTO.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new Demo2ProtobufClientHandler());

                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();

        sendMsg(f.channel());
        // 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.github.herong.rpc.netty.protobuf.demo2.Demo2ProtobufServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/* ww  w.  ja v a  2s  .  co  m*/
        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 {
                        ch.pipeline()
                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(Message.DTO.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new Demo2ProtobufServerHandler());
                    }
                });

        // 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();
    }
}