Example usage for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter

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

Introduction

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

Prototype

ChannelInboundHandlerAdapter

Source Link

Usage

From source file:reactor.io.net.tcp.syslog.SyslogTcpServerTests.java

License:Open Source License

@Test
@Ignore//from   w  w w  .j  a v a  2s .  c  om
public void testSyslogServer() throws InterruptedException, IOException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(2);
    EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    Configuration conf = new Configuration();
    conf.addResource("/usr/local/Cellar/hadoop/1.1.2/libexec/conf/core-site.xml");
    final HdfsConsumer hdfs = new HdfsConsumer(conf, "loadtests", "syslog");

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).localAddress(3000).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("framer",
                            new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                    pipeline.addLast("decoder", new StringDecoder());
                    pipeline.addLast("syslogDecoder", new MessageToMessageDecoder<String>() {
                        Function<Buffer, SyslogMessage> decoder = new SyslogCodec().decoder(null);

                        @Override
                        public void decode(ChannelHandlerContext ctx, String msg, List<Object> messages)
                                throws Exception {
                            messages.add(decoder.apply(Buffer.wrap(msg + "\n")));
                        }
                    });
                    pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            latch.countDown();
                            hdfs.accept((SyslogMessage) msg);
                        }
                    });
                }
            });

    // Bind and start to accept incoming connections.
    ChannelFuture channelFuture = b.bind().awaitUninterruptibly();

    for (int i = 0; i < threads; i++) {
        new SyslogMessageWriter(3000).start();
    }

    latch.await(60, TimeUnit.SECONDS);
    end.set(System.currentTimeMillis());

    assertThat("latch was counted down", latch.getCount(), is(0L));

    double elapsed = (end.get() - start.get()) * 1.0;
    System.out.println("elapsed: " + (int) elapsed + "ms");
    System.out.println("throughput: " + (int) ((msgs * threads) / (elapsed / 1000)) + "/sec");

    channelFuture.channel().close().awaitUninterruptibly();
}

From source file:rereverse.ReReverseHandler.java

License:Open Source License

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

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new ChannelInboundHandlerAdapter() {
                @Override//from  w w w. j av a 2  s .com
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    ctx.read();
                    ctx.write(Unpooled.EMPTY_BUFFER);
                }

                @Override
                public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
                    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (future.isSuccess()) {
                                ctx.channel().read();
                            } else {
                                future.channel().close();
                            }
                        }
                    });
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    closeChannel(inboundChannel);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    cause.printStackTrace();
                    closeChannel(ctx.channel());
                }
            }).option(ChannelOption.AUTO_READ, false);

    //TODO map using url without port (?)
    ChannelFuture f = b.connect(application.remoteHost, application.remotePort);
    outbound = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                inboundChannel.read();
            } else {
                // failed
                inboundChannel.close();
            }
        }
    });
}

From source file:rxweb.engine.server.netty.NettyServer.java

License:Apache License

private void init() {
    this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).group(new NioEventLoopGroup())
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {
                @Override/*from   w  w w .  ja v  a 2s  . c o m*/
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new LoggingHandler()).addLast(new HttpServerCodec())
                            .addLast(new NettyServerCodecHandlerAdapter())
                            .addLast(new ChannelInboundHandlerAdapter() {

                                private CompletableFuture<Channel> headersSent;

                                private final Logger logger = LoggerFactory.getLogger(getClass());

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg)
                                        throws Exception {
                                    if (msg instanceof ServerRequest) {
                                        handleRequest(ctx, (ServerRequest) msg);
                                    } else {
                                        super.channelRead(ctx, msg);
                                    }
                                }

                                private void handleRequest(ChannelHandlerContext ctx, ServerRequest request) {
                                    List<ServerHandler> handlers = handlerResolver.resolve(request);
                                    if (handlers.isEmpty()) {
                                        this.logger.info("No handler found for request " + request.getUri());
                                    }
                                    // In order to keep simple, we take the first handler
                                    ServerHandler handler = handlers.get(0);
                                    ServerResponse response = new NettyServerResponseAdapter(request);
                                    handler.handle(request, response);

                                    response.getContent().subscribe(new Subscriber<ByteBuffer>() {

                                        @Override
                                        public void onNext(ByteBuffer buffer) {
                                            if (headersSent != null) {
                                                ctx.writeAndFlush(buffer);
                                            } else {
                                                headersSent = CompletableFutureUtils
                                                        .fromChannelFuture(ctx.write(response));

                                                headersSent.handle((channel, t) -> {
                                                    if (channel != null) {
                                                        response.setStatusAndHeadersSent(true);
                                                        ctx.write(buffer);
                                                    } else {
                                                        logger.error(t.toString());
                                                    }
                                                    return channel;
                                                });
                                            }
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            logger.error("Error in response content observable: " + e);
                                        }

                                        @Override
                                        public void onCompleted() {
                                            if (response.isStatusAndHeadersSent()) {
                                                ctx.write(new DefaultLastHttpContent());
                                                ctx.flush();
                                                ctx.close();
                                            } else if (headersSent != null) {
                                                headersSent.thenRun(() -> {
                                                    ctx.write(new DefaultLastHttpContent());
                                                    ctx.flush();
                                                    ctx.close();
                                                });
                                            } else {
                                                CompletableFutureUtils.fromChannelFuture(ctx.write(response))
                                                        .thenRun(() -> {
                                                            response.setStatusAndHeadersSent(true);
                                                            ctx.write(new DefaultLastHttpContent());
                                                            ctx.flush();
                                                            ctx.close();
                                                        });
                                            }
                                        }

                                    });
                                }

                            });
                }

            });
}