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:io.grpc.netty.ProtocolNegotiatorsTest.java

License:Apache License

@Test
public void tlsHandler_userEventTriggeredSslEvent_handshakeFailure() throws Exception {
    ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext);
    pipeline.addLast(handler);/*w ww .jav  a  2  s .  c  o  m*/
    channelHandlerCtx = pipeline.context(handler);
    Object sslEvent = new SslHandshakeCompletionEvent(new RuntimeException("bad"));

    final AtomicReference<Throwable> error = new AtomicReference<>();
    ChannelHandler errorCapture = new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            error.set(cause);
        }
    };

    pipeline.addLast(errorCapture);

    pipeline.fireUserEventTriggered(sslEvent);

    // No h2 protocol was specified, so there should be an error, (normally handled by WBAEH)
    assertThat(error.get()).hasMessageThat().contains("bad");
    ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
    assertNull(grpcHandlerCtx);
}

From source file:io.grpc.netty.ProtocolNegotiatorsTest.java

License:Apache License

@Test
public void waitUntilActiveHandler_firesNegotiation() throws Exception {
    EventLoopGroup elg = new DefaultEventLoopGroup(1);
    SocketAddress addr = new LocalAddress("addr");
    final AtomicReference<Object> event = new AtomicReference<>();
    ChannelHandler next = new ChannelInboundHandlerAdapter() {
        @Override/*from w  w  w .  jav a 2  s .  c  o  m*/
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
            event.set(evt);
            ctx.close();
        }
    };
    Channel s = new ServerBootstrap().childHandler(new ChannelInboundHandlerAdapter()).group(elg)
            .channel(LocalServerChannel.class).bind(addr).sync().channel();
    Channel c = new Bootstrap().handler(new WaitUntilActiveHandler(next)).channel(LocalChannel.class)
            .group(group).connect(addr).sync().channel();
    c.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT);
    SocketAddress localAddr = c.localAddress();
    ProtocolNegotiationEvent expectedEvent = ProtocolNegotiationEvent.DEFAULT
            .withAttributes(Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, localAddr)
                    .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, addr)
                    .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.NONE).build());

    c.closeFuture().sync();
    assertThat(event.get()).isInstanceOf(ProtocolNegotiationEvent.class);
    ProtocolNegotiationEvent actual = (ProtocolNegotiationEvent) event.get();
    assertThat(actual).isEqualTo(expectedEvent);

    s.close();
    elg.shutdownGracefully();
}

From source file:io.hekate.network.netty.NettyServer.java

License:Apache License

private void doStart(int attempt) {
    assert Thread.holdsLock(mux) : "Thread must hold lock.";

    ServerBootstrap boot = new ServerBootstrap();

    if (acceptors instanceof EpollEventLoopGroup) {
        if (DEBUG) {
            log.debug("Using EPOLL server socket channel.");
        }/*from ww  w  .j a v a2 s .  c o  m*/

        boot.channel(EpollServerSocketChannel.class);
    } else {
        if (DEBUG) {
            log.debug("Using NIO server socket channel.");
        }

        boot.channel(NioServerSocketChannel.class);
    }

    boot.group(acceptors, workers);

    setOpts(boot);
    setChildOpts(boot);

    boot.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            mayBeRetry(ctx.channel(), attempt, cause);
        }
    });

    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            InetSocketAddress remoteAddress = channel.remoteAddress();
            InetSocketAddress localAddress = channel.localAddress();

            synchronized (mux) {
                if (state == STOPPING || state == STOPPED) {
                    if (DEBUG) {
                        log.debug("Closing connection since server is in {} state [address={}].", state,
                                remoteAddress);
                    }

                    channel.close();

                    return;
                }

                // Setup pipeline.
                ChannelPipeline pipe = channel.pipeline();

                // Configure SSL.
                if (ssl != null) {
                    pipe.addLast(ssl.newHandler(channel.alloc()));
                }

                // Message codecs.
                NetworkProtocolCodec codec = new NetworkProtocolCodec(codecs);

                pipe.addLast(new NetworkProtocolVersion.Decoder());
                pipe.addLast(codec.encoder());
                pipe.addLast(codec.decoder());

                // Client handler.
                NettyServerClient client = new NettyServerClient(remoteAddress, localAddress, ssl != null,
                        hbInterval, hbLossThreshold, hbDisabled, handlers, workers);

                pipe.addLast(client);

                // Register client to this server.
                clients.put(channel, client);

                // Unregister client on disconnect.
                channel.closeFuture().addListener(close -> {
                    if (DEBUG) {
                        log.debug("Removing connection from server registry [address={}]", remoteAddress);
                    }

                    synchronized (mux) {
                        clients.remove(channel);
                    }
                });
            }
        }
    });

    ChannelFuture bindFuture = boot.bind(address);

    server = bindFuture.channel();

    bindFuture.addListener((ChannelFutureListener) bind -> {
        if (bind.isSuccess()) {
            synchronized (mux) {
                failoverInProgress = false;

                if (state == STARTING) {
                    state = STARTED;

                    // Updated since port can be automatically assigned by the underlying OS.
                    address = (InetSocketAddress) bind.channel().localAddress();

                    if (DEBUG) {
                        log.debug("Started [address={}]", address);
                    }

                    if (!startFuture.isDone() && callback != null) {
                        callback.onStart(this);
                    }

                    startFuture.complete(this);
                }
            }
        } else {
            mayBeRetry(bind.channel(), attempt, bind.cause());
        }
    });
}

From source file:io.lettuce.core.ProtectedModeTests.java

License:Apache License

@BeforeClass
public static void beforeClass() throws Exception {

    server = new MockTcpServer();

    server.addHandler(() -> {//w w  w.ja  va 2 s  .  c o m
        return new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {

                String message = getMessage();
                ByteBuf buffer = ctx.alloc().buffer(message.length() + 3);
                buffer.writeCharSequence("-", StandardCharsets.US_ASCII);
                buffer.writeCharSequence(message, StandardCharsets.US_ASCII);
                buffer.writeByte('\r').writeByte('\n');

                ctx.writeAndFlush(buffer).addListener(future -> {
                    ctx.close();
                });
            }
        };
    });

    server.initialize(TestSettings.nonexistentPort());

    client = RedisClient.create(TestClientResources.get(),
            RedisURI.create(TestSettings.host(), TestSettings.nonexistentPort()));
}

From source file:io.vertx.core.EventLoopGroupTest.java

License:Open Source License

@Test
public void testNettyServerUsesContextEventLoop() throws Exception {
    ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
    AtomicReference<Thread> contextThread = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    context.runOnContext(v -> {/* w ww.  j av  a2  s .  com*/
        contextThread.set(Thread.currentThread());
        latch.countDown();
    });
    awaitLatch(latch);
    ServerBootstrap bs = new ServerBootstrap();
    bs.group(context.nettyEventLoop());
    bs.channelFactory(((VertxInternal) vertx).transport().serverChannelFactory(false));
    bs.option(ChannelOption.SO_BACKLOG, 100);
    bs.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            assertSame(contextThread.get(), Thread.currentThread());
            context.executeFromIO(v -> {
                assertSame(contextThread.get(), Thread.currentThread());
                assertSame(context, Vertx.currentContext());
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(v -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf buf = (ByteBuf) msg;
                        assertEquals("hello", buf.toString(StandardCharsets.UTF_8));
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(v -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(v -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        });
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(v -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            testComplete();
                        });
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        fail(cause.getMessage());
                    }
                });
            });
        }
    });
    ChannelFuture fut = bs.bind("localhost", 1234);
    try {
        fut.sync();
        vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> {
            assertTrue(ar.succeeded());
            NetSocket so = ar.result();
            so.write(Buffer.buffer("hello"));
        });
        await();
    } finally {
        fut.channel().close().sync();
    }
}

From source file:io.vertx.core.http.impl.FileStreamChannel.java

License:Open Source License

FileStreamChannel(Handler<AsyncResult<Long>> resultHandler, VertxHttp2Stream stream, long offset, long length) {
    super(null, Id.INSTANCE);

    pipeline().addLast(new ChannelInitializer<Channel>() {
        @Override/*from  ww  w.ja v  a 2  s . c o m*/
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new ChunkedWriteHandler());
            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof RandomAccessFile) {
                        ChannelFuture fut = ctx.writeAndFlush(new ChunkedFile((RandomAccessFile) evt, offset,
                                length, 8192 /* default chunk size */ ));
                        fut.addListener(f -> {
                            if (resultHandler != null) {
                                if (f.isSuccess()) {
                                    resultHandler.handle(Future.succeededFuture(bytesWritten));
                                } else {
                                    resultHandler.handle(Future.failedFuture(f.cause()));
                                }
                            }
                            fut.addListener(ChannelFutureListener.CLOSE);
                        });
                    }
                }
            });
        }
    });

    this.stream = stream;
}

From source file:io.vertx.test.core.EventLoopGroupTest.java

License:Open Source License

@Test
public void testNettyServerUsesContextEventLoop() throws Exception {
    ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
    AtomicReference<Thread> contextThread = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    context.runOnContext(v -> {//from www.j a  va2s.  c o m
        contextThread.set(Thread.currentThread());
        latch.countDown();
    });
    awaitLatch(latch);
    ServerBootstrap bs = new ServerBootstrap();
    bs.group(context.nettyEventLoop());
    bs.channel(NioServerSocketChannel.class);
    bs.option(ChannelOption.SO_BACKLOG, 100);
    bs.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            assertSame(contextThread.get(), Thread.currentThread());
            context.executeFromIO(() -> {
                assertSame(contextThread.get(), Thread.currentThread());
                assertSame(context, Vertx.currentContext());
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf buf = (ByteBuf) msg;
                        assertEquals("hello", buf.toString(StandardCharsets.UTF_8));
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        });
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            testComplete();
                        });
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        fail(cause.getMessage());
                    }
                });
            });
        }
    });
    bs.bind("localhost", 1234).sync();
    vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> {
        assertTrue(ar.succeeded());
        NetSocket so = ar.result();
        so.write(Buffer.buffer("hello"));
    });
    await();
}

From source file:io.viewserver.network.netty.NettyNetworkAdapter.java

License:Apache License

@Override
public void listen(IEndpoint endpoint) {
    if (parentGroup == null) {
        parentGroup = new NioEventLoopGroup(1,
                new DefaultThreadFactory(String.format("io-%s-server-boss", reactor.getName())));
        handlers = new NioEventLoopGroup(1,
                new DefaultThreadFactory(String.format("io-%s-server-worker", reactor.getName())));
    }//w w w. j a  v a2 s . com

    ServerBootstrap serverBootstrap = ((INettyEndpoint) endpoint).getServerBootstrap(parentGroup, handlers,
            new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("New connection on channel {}", ctx.channel());
                            NettyChannel channel = new NettyChannel(ctx.channel());
                            for (INetworkMessageListener listener : listeners) {
                                listener.onConnection(channel);
                            }

                            super.channelActive(ctx);
                        }

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("Disconnection on channel {}", ctx.channel());
                            NettyChannel channel = new NettyChannel(ctx.channel());
                            for (INetworkMessageListener listener : listeners) {
                                listener.onDisconnection(channel);
                            }

                            super.channelInactive(ctx);
                        }
                    });
                    new NettyPipelineInitialiser(networkMessageWheel).initChannel(ch);
                }
            });
    servers.add(serverBootstrap);
}

From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java

License:Apache License

@Override
public ServerBootstrap getServerBootstrap(EventLoopGroup parentGroup, EventLoopGroup childGroup,
        ChannelHandler handler) {//  w  w w  .  j  a v a2  s . c om
    if (this.uri.getScheme().equals("wss")) {
        if (keyCertChainFile == null) {
            log.warn("No certificate provided for WSS endpoint - will use self-signed");
            try {
                SelfSignedCertificate certificate = new SelfSignedCertificate();
                keyCertChainFile = certificate.certificate();
                keyFile = certificate.privateKey();
                usingSelfSignedCertificate = true;
            } catch (CertificateException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            serverSslContext = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword).build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else if (!this.uri.getScheme().equals("ws")) {
        throw new IllegalArgumentException("Invalid scheme '" + uri.getScheme() + "' for web socket endpoint");
    }

    ServerBootstrap server = new ServerBootstrap();
    server.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (serverSslContext != null) {
                        pipeline.addLast(serverSslContext.newHandler(ch.alloc()));
                    }
                    pipeline.addLast(new HttpServerCodec());
                    pipeline.addLast(new HttpObjectAggregator(65536));
                    //                        pipeline.addLast(new WebSocketServerCompressionHandler());
                    pipeline.addLast("websocket", new WebSocketServerProtocolHandler("/"));
                    pipeline.addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
                                ChannelPipeline pipeline = ctx.channel().pipeline();
                                pipeline.addAfter("websocket", "ws-decoder-xx",
                                        new MessageToMessageDecoder<BinaryWebSocketFrame>() {
                                            @Override
                                            protected void decode(ChannelHandlerContext ctx,
                                                    BinaryWebSocketFrame msg, List<Object> out)
                                                    throws Exception {
                                                out.add(msg.content().retain());
                                            }
                                        });

                                pipeline.addAfter("websocket", "ws-encoder-xx",
                                        new MessageToMessageEncoder<ByteBuf>() {
                                            @Override
                                            protected void encode(ChannelHandlerContext ctx, ByteBuf msg,
                                                    List<Object> out) throws Exception {
                                                out.add(new BinaryWebSocketFrame(msg).retain());
                                            }
                                        });
                            }

                            super.userEventTriggered(ctx, evt);
                        }
                    });

                    pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter());
                    pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter());
                    pipeline.addLast(handler);
                }
            });

    server.bind(uri.getPort());
    return server;
}

From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java

License:Apache License

@Override
public IClient getClient(EventLoopGroup eventLoopGroup, ChannelHandler handler) {
    SslContext sslContext;//www .  j a v a  2  s  .  c  o  m
    if (this.uri.getScheme().equals("wss")) {
        try {
            SslContextBuilder builder = SslContextBuilder.forClient();
            if (bypassCertificateChecks || usingSelfSignedCertificate) {
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            }
            sslContext = builder.build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslContext = null;
    }

    Bootstrap bootstrap = new Bootstrap();
    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (sslContext != null) {
                pipeline.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
            }
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(1 << 30));
            pipeline.addLast("websocket", new WebSocketClientProtocolHandler(handshaker));
            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
                        ChannelPipeline pipeline = ctx.channel().pipeline();
                        pipeline.addAfter("websocket", "ws-decoder-xx",
                                new MessageToMessageDecoder<BinaryWebSocketFrame>() {
                                    @Override
                                    protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame msg,
                                            List<Object> out) throws Exception {
                                        out.add(msg.content().retain());
                                    }
                                });

                        pipeline.addAfter("websocket", "ws-encoder-xx", new MessageToMessageEncoder<ByteBuf>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
                                    throws Exception {
                                out.add(new BinaryWebSocketFrame(msg).retain());
                            }
                        });
                    }

                    super.userEventTriggered(ctx, evt);
                }
            });

            pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter());
            pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter());
            pipeline.addLast(handler);
        }
    });
    return () -> bootstrap.connect(uri.getHost(), uri.getPort());
}