Search in sources :

Example 26 with ChannelOutboundHandlerAdapter

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

the class EmbeddedChannelTest method testWriteScheduled.

@Test
public void testWriteScheduled() throws InterruptedException {
    final int delay = 500;
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
            ctx.executor().schedule(new Runnable() {

                @Override
                public void run() {
                    ctx.writeAndFlush(msg, promise);
                }
            }, delay, TimeUnit.MILLISECONDS);
        }
    });
    Object msg = new Object();
    assertFalse(channel.writeOutbound(msg));
    Thread.sleep(delay * 2);
    assertTrue(channel.finish());
    assertSame(msg, channel.readOutbound());
    assertNull(channel.readOutbound());
}
Also used : ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ClosedChannelException(java.nio.channels.ClosedChannelException) Test(org.junit.jupiter.api.Test)

Example 27 with ChannelOutboundHandlerAdapter

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

the class HttpContentCompressorTest method testExecutorPreserveOrdering.

@Test
public void testExecutorPreserveOrdering() throws Exception {
    final EventLoopGroup compressorGroup = new DefaultEventLoopGroup(1);
    EventLoopGroup localGroup = new DefaultEventLoopGroup(1);
    Channel server = null;
    Channel client = null;
    try {
        ServerBootstrap bootstrap = new ServerBootstrap().channel(LocalServerChannel.class).group(localGroup).childHandler(new ChannelInitializer<LocalChannel>() {

            @Override
            protected void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new HttpServerCodec()).addLast(new HttpObjectAggregator(1024)).addLast(compressorGroup, new HttpContentCompressor()).addLast(new ChannelOutboundHandlerAdapter() {

                    @Override
                    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                        super.write(ctx, msg, promise);
                    }
                }).addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        if (msg instanceof FullHttpRequest) {
                            FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer("Hello, World", CharsetUtil.US_ASCII));
                            ctx.writeAndFlush(res);
                            ReferenceCountUtil.release(msg);
                            return;
                        }
                        super.channelRead(ctx, msg);
                    }
                });
            }
        });
        LocalAddress address = new LocalAddress(UUID.randomUUID().toString());
        server = bootstrap.bind(address).sync().channel();
        final BlockingQueue<HttpObject> responses = new LinkedBlockingQueue<HttpObject>();
        client = new Bootstrap().channel(LocalChannel.class).remoteAddress(address).group(localGroup).handler(new ChannelInitializer<LocalChannel>() {

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

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        if (msg instanceof HttpObject) {
                            responses.put((HttpObject) msg);
                            return;
                        }
                        super.channelRead(ctx, msg);
                    }
                });
            }
        }).connect().sync().channel();
        client.writeAndFlush(newRequest()).sync();
        assertEncodedResponse((HttpResponse) responses.poll(1, TimeUnit.SECONDS));
        HttpContent c = (HttpContent) responses.poll(1, TimeUnit.SECONDS);
        assertNotNull(c);
        assertThat(ByteBufUtil.hexDump(c.content()), is("1f8b0800000000000000f248cdc9c9d75108cf2fca4901000000ffff"));
        c.release();
        c = (HttpContent) responses.poll(1, TimeUnit.SECONDS);
        assertNotNull(c);
        assertThat(ByteBufUtil.hexDump(c.content()), is("0300c6865b260c000000"));
        c.release();
        LastHttpContent last = (LastHttpContent) responses.poll(1, TimeUnit.SECONDS);
        assertNotNull(last);
        assertThat(last.content().readableBytes(), is(0));
        last.release();
        assertNull(responses.poll(1, TimeUnit.SECONDS));
    } finally {
        if (client != null) {
            client.close().sync();
        }
        if (server != null) {
            server.close().sync();
        }
        compressorGroup.shutdownGracefully();
        localGroup.shutdownGracefully();
    }
}
Also used : LocalChannel(io.netty.channel.local.LocalChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) 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) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EncoderException(io.netty.handler.codec.EncoderException) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 28 with ChannelOutboundHandlerAdapter

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

the class HttpContentDecompressorTest method testInvokeReadWhenNotProduceMessage.

// See https://github.com/netty/netty/issues/8915.
@Test
public void testInvokeReadWhenNotProduceMessage() {
    final AtomicInteger readCalled = new AtomicInteger();
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() {

        @Override
        public void read(ChannelHandlerContext ctx) {
            readCalled.incrementAndGet();
            ctx.read();
        }
    }, new HttpContentDecompressor(), new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ctx.fireChannelRead(msg);
            ctx.read();
        }
    });
    channel.config().setAutoRead(false);
    readCalled.set(0);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(HttpHeaderNames.CONTENT_ENCODING, "gzip");
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8");
    response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    assertTrue(channel.writeInbound(response));
    // we triggered read explicitly
    assertEquals(1, readCalled.get());
    assertTrue(channel.readInbound() instanceof HttpResponse);
    assertFalse(channel.writeInbound(new DefaultHttpContent(Unpooled.EMPTY_BUFFER)));
    // read was triggered by the HttpContentDecompressor itself as it did not produce any message to the next
    // inbound handler.
    assertEquals(2, readCalled.get());
    assertFalse(channel.finishAndReleaseAll());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 29 with ChannelOutboundHandlerAdapter

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

the class Http2ConnectionRoundtripTest method writeFailureFlowControllerRemoveFrame.

@Test
public void writeFailureFlowControllerRemoveFrame() throws Exception {
    bootstrapEnv(1, 1, 2, 1);
    final ChannelPromise dataPromise = newPromise();
    final ChannelPromise assertPromise = newPromise();
    runInChannel(clientChannel, new Http2Runnable() {

        @Override
        public void run() throws Http2Exception {
            http2Client.encoder().writeHeaders(ctx(), 3, EmptyHttp2Headers.INSTANCE, 0, (short) 16, false, 0, false, newPromise());
            clientChannel.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {

                @Override
                public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                    ReferenceCountUtil.release(msg);
                    // Ensure we update the window size so we will try to write the rest of the frame while
                    // processing the flush.
                    http2Client.encoder().flowController().initialWindowSize(8);
                    promise.setFailure(new IllegalStateException());
                }
            });
            http2Client.encoder().flowController().initialWindowSize(4);
            http2Client.encoder().writeData(ctx(), 3, randomBytes(8), 0, false, dataPromise);
            assertTrue(http2Client.encoder().flowController().hasFlowControlled(http2Client.connection().stream(3)));
            http2Client.flush(ctx());
            try {
                // The Frame should have been removed after the write failed.
                assertFalse(http2Client.encoder().flowController().hasFlowControlled(http2Client.connection().stream(3)));
                assertPromise.setSuccess();
            } catch (Throwable error) {
                assertPromise.setFailure(error);
            }
        }
    });
    ExecutionException e = assertThrows(ExecutionException.class, new Executable() {

        @Override
        public void execute() throws Throwable {
            dataPromise.get();
        }
    });
    assertThat(e.getCause(), is(instanceOf(IllegalStateException.class)));
    assertPromise.sync();
}
Also used : Http2Runnable(io.netty.handler.codec.http2.Http2TestUtil.Http2Runnable) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelPromise(io.netty.channel.ChannelPromise) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ExecutionException(java.util.concurrent.ExecutionException) Executable(org.junit.jupiter.api.function.Executable) Test(org.junit.jupiter.api.Test)

Example 30 with ChannelOutboundHandlerAdapter

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

the class Http2StreamFrameToHttpObjectCodecTest method testIsSharableBetweenChannels.

@Test
public void testIsSharableBetweenChannels() throws Exception {
    final Queue<Http2StreamFrame> frames = new ConcurrentLinkedQueue<Http2StreamFrame>();
    final ChannelHandler sharedHandler = new Http2StreamFrameToHttpObjectCodec(false);
    final SslContext ctx = SslContextBuilder.forClient().sslProvider(SslProvider.JDK).build();
    EmbeddedChannel tlsCh = new EmbeddedChannel(ctx.newHandler(ByteBufAllocator.DEFAULT), new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            if (msg instanceof Http2StreamFrame) {
                frames.add((Http2StreamFrame) msg);
                promise.setSuccess();
            } else {
                ctx.write(msg, promise);
            }
        }
    }, sharedHandler);
    EmbeddedChannel plaintextCh = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
            if (msg instanceof Http2StreamFrame) {
                frames.add((Http2StreamFrame) msg);
                promise.setSuccess();
            } else {
                ctx.write(msg, promise);
            }
        }
    }, sharedHandler);
    FullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world");
    assertTrue(tlsCh.writeOutbound(req));
    assertTrue(tlsCh.finishAndReleaseAll());
    Http2HeadersFrame headersFrame = (Http2HeadersFrame) frames.poll();
    Http2Headers headers = headersFrame.headers();
    assertThat(headers.scheme().toString(), is("https"));
    assertThat(headers.method().toString(), is("GET"));
    assertThat(headers.path().toString(), is("/hello/world"));
    assertTrue(headersFrame.isEndStream());
    assertNull(frames.poll());
    // Run the plaintext channel
    req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world");
    assertFalse(plaintextCh.writeOutbound(req));
    assertFalse(plaintextCh.finishAndReleaseAll());
    headersFrame = (Http2HeadersFrame) frames.poll();
    headers = headersFrame.headers();
    assertThat(headers.scheme().toString(), is("http"));
    assertThat(headers.method().toString(), is("GET"));
    assertThat(headers.path().toString(), is("/hello/world"));
    assertTrue(headersFrame.isEndStream());
    assertNull(frames.poll());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ChannelHandler(io.netty.channel.ChannelHandler) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) SslContext(io.netty.handler.ssl.SslContext) Test(org.junit.jupiter.api.Test)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)32 ChannelOutboundHandlerAdapter (io.netty.channel.ChannelOutboundHandlerAdapter)32 ChannelPromise (io.netty.channel.ChannelPromise)30 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)18 Test (org.junit.jupiter.api.Test)17 ByteBuf (io.netty.buffer.ByteBuf)10 Test (org.junit.Test)9 IOException (java.io.IOException)7 ClosedChannelException (java.nio.channels.ClosedChannelException)7 ChannelFuture (io.netty.channel.ChannelFuture)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 Channel (io.netty.channel.Channel)3 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)3 SslContext (io.netty.handler.ssl.SslContext)3 ByteBuffer (java.nio.ByteBuffer)3 WritableByteChannel (java.nio.channels.WritableByteChannel)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 ApiErrorWithMetadata (com.nike.backstopper.apierror.ApiErrorWithMetadata)2 NettyHttpClientRequestBuilder (com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientRequestBuilder)2 NettyHttpClientResponse (com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientResponse)2