Search in sources :

Example 46 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class SniClientJava8TestUtil method testSniClient.

static void testSniClient(SslProvider sslClientProvider, SslProvider sslServerProvider, final boolean match) throws Exception {
    final String sniHost = "sni.netty.io";
    SelfSignedCertificate cert = new SelfSignedCertificate();
    LocalAddress address = new LocalAddress("test");
    EventLoopGroup group = new DefaultEventLoopGroup(1);
    SslContext sslServerContext = null;
    SslContext sslClientContext = null;
    Channel sc = null;
    Channel cc = null;
    try {
        sslServerContext = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(sslServerProvider).build();
        final Promise<Void> promise = group.next().newPromise();
        ServerBootstrap sb = new ServerBootstrap();
        final SslContext finalContext = sslServerContext;
        sc = sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                SslHandler handler = finalContext.newHandler(ch.alloc());
                SSLParameters parameters = handler.engine().getSSLParameters();
                SNIMatcher matcher = new SNIMatcher(0) {

                    @Override
                    public boolean matches(SNIServerName sniServerName) {
                        return match;
                    }
                };
                parameters.setSNIMatchers(Collections.singleton(matcher));
                handler.engine().setSSLParameters(parameters);
                ch.pipeline().addFirst(handler);
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        if (evt instanceof SslHandshakeCompletionEvent) {
                            SslHandshakeCompletionEvent event = (SslHandshakeCompletionEvent) evt;
                            if (match) {
                                if (event.isSuccess()) {
                                    promise.setSuccess(null);
                                } else {
                                    promise.setFailure(event.cause());
                                }
                            } else {
                                if (event.isSuccess()) {
                                    promise.setFailure(new AssertionError("expected SSLException"));
                                } else {
                                    Throwable cause = event.cause();
                                    if (cause instanceof SSLException) {
                                        promise.setSuccess(null);
                                    } else {
                                        promise.setFailure(new AssertionError("cause not of type SSLException: " + ThrowableUtil.stackTraceToString(cause)));
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }).bind(address).syncUninterruptibly().channel();
        sslClientContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(sslClientProvider).build();
        SslHandler sslHandler = new SslHandler(sslClientContext.newEngine(ByteBufAllocator.DEFAULT, sniHost, -1));
        Bootstrap cb = new Bootstrap();
        cc = cb.group(group).channel(LocalChannel.class).handler(sslHandler).connect(address).syncUninterruptibly().channel();
        promise.syncUninterruptibly();
        sslHandler.handshakeFuture().syncUninterruptibly();
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        ReferenceCountUtil.release(sslServerContext);
        ReferenceCountUtil.release(sslClientContext);
        cert.delete();
        group.shutdownGracefully();
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) LocalChannel(io.netty.channel.local.LocalChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) SSLException(javax.net.ssl.SSLException) SNIServerName(javax.net.ssl.SNIServerName) SSLParameters(javax.net.ssl.SSLParameters) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) KeyStoreException(java.security.KeyStoreException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SNIMatcher(javax.net.ssl.SNIMatcher) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 47 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class WriteTimeoutHandlerTest method testPromiseUseDifferentExecutor.

@Test
public void testPromiseUseDifferentExecutor() throws Exception {
    EventExecutorGroup group1 = new DefaultEventExecutorGroup(1);
    EventExecutorGroup group2 = new DefaultEventExecutorGroup(1);
    EmbeddedChannel channel = new EmbeddedChannel(false, false);
    try {
        channel.pipeline().addLast(group1, new WriteTimeoutHandler(10000));
        final CountDownLatch latch = new CountDownLatch(1);
        channel.pipeline().addLast(group2, new ChannelInboundHandlerAdapter() {

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                ctx.writeAndFlush("something").addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        latch.countDown();
                    }
                });
            }
        });
        channel.register();
        latch.await();
        assertTrue(channel.finishAndReleaseAll());
    } finally {
        group1.shutdownGracefully();
        group2.shutdownGracefully();
    }
}
Also used : DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) ChannelFuture(io.netty.channel.ChannelFuture) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 48 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class TrafficShapingHandlerTest method testHandlerRemove0.

private void testHandlerRemove0(final AbstractTrafficShapingHandler trafficHandler) throws Exception {
    Channel svrChannel = null;
    Channel ch = null;
    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.channel(LocalServerChannel.class).group(GROUP, GROUP).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ctx.writeAndFlush(msg);
                    }
                });
            }
        });
        final LocalAddress svrAddr = new LocalAddress("foo");
        svrChannel = serverBootstrap.bind(svrAddr).sync().channel();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(LocalChannel.class).group(GROUP).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast("traffic-shaping", trafficHandler);
            }
        });
        ch = bootstrap.connect(svrAddr).sync().channel();
        Attribute<Runnable> attr = ch.attr(AbstractTrafficShapingHandler.REOPEN_TASK);
        assertNull(attr.get());
        ch.writeAndFlush(Unpooled.wrappedBuffer("foo".getBytes(CharsetUtil.UTF_8)));
        ch.writeAndFlush(Unpooled.wrappedBuffer("bar".getBytes(CharsetUtil.UTF_8))).await();
        assertNotNull(attr.get());
        final Channel clientChannel = ch;
        ch.eventLoop().submit(new Runnable() {

            @Override
            public void run() {
                clientChannel.pipeline().remove("traffic-shaping");
            }
        }).await();
        // the attribute--reopen task must be released.
        assertNull(attr.get());
    } finally {
        if (ch != null) {
            ch.close().sync();
        }
        if (svrChannel != null) {
            svrChannel.close().sync();
        }
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 49 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class HttpContentDecoderTest method testExpectContinueResetHttpObjectDecoder.

@Test
public void testExpectContinueResetHttpObjectDecoder() {
    // request with header "Expect: 100-continue" must be replied with one "100 Continue" response
    // case 5: Test that HttpObjectDecoder correctly resets its internal state after a failed expectation.
    HttpRequestDecoder decoder = new HttpRequestDecoder();
    final int maxBytes = 10;
    HttpObjectAggregator aggregator = new HttpObjectAggregator(maxBytes);
    final AtomicReference<FullHttpRequest> secondRequestRef = new AtomicReference<FullHttpRequest>();
    EmbeddedChannel channel = new EmbeddedChannel(decoder, aggregator, new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof FullHttpRequest) {
                if (!secondRequestRef.compareAndSet(null, (FullHttpRequest) msg)) {
                    ((FullHttpRequest) msg).release();
                }
            } else {
                ReferenceCountUtil.release(msg);
            }
        }
    });
    String req1 = "POST /1 HTTP/1.1\r\n" + "Content-Length: " + (maxBytes + 1) + "\r\n" + "Expect: 100-continue\r\n" + "\r\n";
    assertFalse(channel.writeInbound(Unpooled.wrappedBuffer(req1.getBytes(CharsetUtil.US_ASCII))));
    FullHttpResponse resp = channel.readOutbound();
    assertEquals(HttpStatusClass.CLIENT_ERROR, resp.status().codeClass());
    resp.release();
    String req2 = "POST /2 HTTP/1.1\r\n" + "Content-Length: " + maxBytes + "\r\n" + "Expect: 100-continue\r\n" + "\r\n";
    assertFalse(channel.writeInbound(Unpooled.wrappedBuffer(req2.getBytes(CharsetUtil.US_ASCII))));
    resp = channel.readOutbound();
    assertEquals(100, resp.status().code());
    resp.release();
    byte[] content = new byte[maxBytes];
    assertFalse(channel.writeInbound(Unpooled.wrappedBuffer(content)));
    FullHttpRequest req = secondRequestRef.get();
    assertNotNull(req);
    assertEquals("/2", req.uri());
    assertEquals(10, req.content().readableBytes());
    req.release();
    assertHasInboundMessages(channel, false);
    assertHasOutboundMessages(channel, false);
    assertFalse(channel.finish());
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CodecException(io.netty.handler.codec.CodecException) DecoderException(io.netty.handler.codec.DecoderException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 50 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class HttpContentEncoderTest method testCleanupThrows.

@Test
public void testCleanupThrows() {
    HttpContentEncoder encoder = new HttpContentEncoder() {

        @Override
        protected Result beginEncode(HttpResponse httpResponse, String acceptEncoding) throws Exception {
            return new Result("myencoding", new EmbeddedChannel(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    ctx.fireExceptionCaught(new EncoderException());
                    ctx.fireChannelInactive();
                }
            }));
        }
    };
    final AtomicBoolean channelInactiveCalled = new AtomicBoolean();
    final EmbeddedChannel channel = new EmbeddedChannel(encoder, new ChannelInboundHandlerAdapter() {

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            assertTrue(channelInactiveCalled.compareAndSet(false, true));
            super.channelInactive(ctx);
        }
    });
    assertTrue(channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/")));
    assertTrue(channel.writeOutbound(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)));
    HttpContent content = new DefaultHttpContent(Unpooled.buffer().writeZero(10));
    assertTrue(channel.writeOutbound(content));
    assertEquals(1, content.refCnt());
    assertThrows(CodecException.class, new Executable() {

        @Override
        public void execute() {
            channel.finishAndReleaseAll();
        }
    });
    assertTrue(channelInactiveCalled.get());
    assertEquals(0, content.refCnt());
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) EncoderException(io.netty.handler.codec.EncoderException) CodecException(io.netty.handler.codec.CodecException) DecoderResult(io.netty.handler.codec.DecoderResult) EncoderException(io.netty.handler.codec.EncoderException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Executable(org.junit.jupiter.api.function.Executable) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Aggregations

ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)248 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)192 Channel (io.netty.channel.Channel)132 Bootstrap (io.netty.bootstrap.Bootstrap)109 Test (org.junit.jupiter.api.Test)102 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)99 ChannelFuture (io.netty.channel.ChannelFuture)71 CountDownLatch (java.util.concurrent.CountDownLatch)70 InetSocketAddress (java.net.InetSocketAddress)66 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)54 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)53 EventLoopGroup (io.netty.channel.EventLoopGroup)52 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)51 ByteBuf (io.netty.buffer.ByteBuf)47 AtomicReference (java.util.concurrent.atomic.AtomicReference)47 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)46 ClosedChannelException (java.nio.channels.ClosedChannelException)46 LocalServerChannel (io.netty.channel.local.LocalServerChannel)44 LocalChannel (io.netty.channel.local.LocalChannel)42 SocketChannel (io.netty.channel.socket.SocketChannel)39