Search in sources :

Example 91 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class HttpServerUpgradeHandlerTest method upgradesPipelineInSameMethodInvocation.

@Test
public void upgradesPipelineInSameMethodInvocation() {
    final HttpServerCodec httpServerCodec = new HttpServerCodec();
    final UpgradeCodecFactory factory = new UpgradeCodecFactory() {

        @Override
        public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
            return new TestUpgradeCodec();
        }
    };
    ChannelHandler testInStackFrame = new ChannelDuplexHandler() {

        // marker boolean to signal that we're in the `channelRead` method
        private boolean inReadCall;

        private boolean writeUpgradeMessage;

        private boolean writeFlushed;

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            assertFalse(inReadCall);
            assertFalse(writeUpgradeMessage);
            inReadCall = true;
            try {
                super.channelRead(ctx, msg);
                // All in the same call stack, the upgrade codec should receive the message,
                // written the upgrade response, and upgraded the pipeline.
                assertTrue(writeUpgradeMessage);
                assertFalse(writeFlushed);
                assertNull(ctx.pipeline().get(HttpServerCodec.class));
                assertNotNull(ctx.pipeline().get("marker"));
            } finally {
                inReadCall = false;
            }
        }

        @Override
        public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
            // We ensure that we're in the read call and defer the write so we can
            // make sure the pipeline was reformed irrespective of the flush completing.
            assertTrue(inReadCall);
            writeUpgradeMessage = true;
            ctx.channel().eventLoop().execute(new Runnable() {

                @Override
                public void run() {
                    ctx.write(msg, promise);
                }
            });
            promise.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) {
                    writeFlushed = true;
                }
            });
        }
    };
    HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(httpServerCodec, factory);
    EmbeddedChannel channel = new EmbeddedChannel(testInStackFrame, httpServerCodec, upgradeHandler);
    String upgradeString = "GET / HTTP/1.1\r\n" + "Host: example.com\r\n" + "Connection: Upgrade, HTTP2-Settings\r\n" + "Upgrade: nextprotocol\r\n" + "HTTP2-Settings: AAMAAABkAAQAAP__\r\n\r\n";
    ByteBuf upgrade = Unpooled.copiedBuffer(upgradeString, CharsetUtil.US_ASCII);
    assertFalse(channel.writeInbound(upgrade));
    assertNull(channel.pipeline().get(HttpServerCodec.class));
    assertNotNull(channel.pipeline().get("marker"));
    channel.flushOutbound();
    ByteBuf upgradeMessage = channel.readOutbound();
    String expectedHttpResponse = "HTTP/1.1 101 Switching Protocols\r\n" + "connection: upgrade\r\n" + "upgrade: nextprotocol\r\n\r\n";
    assertEquals(expectedHttpResponse, upgradeMessage.toString(CharsetUtil.US_ASCII));
    assertTrue(upgradeMessage.release());
    assertFalse(channel.finishAndReleaseAll());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) UpgradeCodecFactory(io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodecFactory) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ChannelHandler(io.netty.channel.ChannelHandler) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) Test(org.junit.jupiter.api.Test)

Example 92 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class LocalChannelTest method testWriteInWritePromiseCompletePreservesOrder.

@Test
public void testWriteInWritePromiseCompletePreservesOrder() throws InterruptedException {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    final CountDownLatch messageLatch = new CountDownLatch(2);
    final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
    final ByteBuf data2 = Unpooled.wrappedBuffer(new byte[512]);
    try {
        cb.group(group1).channel(LocalChannel.class).handler(new TestHandler());
        sb.group(group2).channel(LocalServerChannel.class).childHandler(new ChannelInboundHandlerAdapter() {

            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                final long count = messageLatch.getCount();
                if ((data.equals(msg) && count == 2) || (data2.equals(msg) && count == 1)) {
                    ReferenceCountUtil.safeRelease(msg);
                    messageLatch.countDown();
                } else {
                    super.channelRead(ctx, msg);
                }
            }
        });
        Channel sc = null;
        Channel cc = null;
        try {
            // Start server
            sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
            // Connect to the server
            cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
            final Channel ccCpy = cc;
            // Make sure a write operation is executed in the eventloop
            cc.pipeline().lastContext().executor().execute(new Runnable() {

                @Override
                public void run() {
                    ChannelPromise promise = ccCpy.newPromise();
                    promise.addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            ccCpy.writeAndFlush(data2.retainedDuplicate(), ccCpy.newPromise());
                        }
                    });
                    ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
                }
            });
            assertTrue(messageLatch.await(5, SECONDS));
        } finally {
            closeChannel(cc);
            closeChannel(sc);
        }
    } finally {
        data.release();
        data2.release();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 93 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class LocalChannelTest method testConnectFutureBeforeChannelActive.

@Test
@Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
public void testConnectFutureBeforeChannelActive() throws Exception {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    cb.group(group1).channel(LocalChannel.class).handler(new ChannelInboundHandlerAdapter());
    sb.group(group2).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new TestHandler());
        }
    });
    Channel sc = null;
    Channel cc = null;
    try {
        // Start server
        sc = sb.bind(TEST_ADDRESS).sync().channel();
        cc = cb.register().sync().channel();
        final ChannelPromise promise = cc.newPromise();
        final Promise<Void> assertPromise = cc.eventLoop().newPromise();
        cc.pipeline().addLast(new TestHandler() {

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                // Ensure the promise was done before the handler method is triggered.
                if (promise.isDone()) {
                    assertPromise.setSuccess(null);
                } else {
                    assertPromise.setFailure(new AssertionError("connect promise should be done"));
                }
            }
        });
        // Connect to the server
        cc.connect(sc.localAddress(), promise).sync();
        assertPromise.syncUninterruptibly();
        assertTrue(promise.isSuccess());
    } finally {
        closeChannel(cc);
        closeChannel(sc);
    }
}
Also used : AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) ChannelPromise(io.netty.channel.ChannelPromise) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 94 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class EmbeddedChannelTest method testWriteLater.

@Test
public void testWriteLater() {
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() {

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

                @Override
                public void run() {
                    ctx.write(msg, promise);
                }
            });
        }
    });
    Object msg = new Object();
    assertTrue(channel.writeOutbound(msg));
    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 95 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class EmbeddedChannelTest method testWriteOneOutbound.

@Test
public void testWriteOneOutbound() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger flushCount = new AtomicInteger(0);
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            ctx.write(msg, promise);
            latch.countDown();
        }

        @Override
        public void flush(ChannelHandlerContext ctx) throws Exception {
            flushCount.incrementAndGet();
        }
    });
    // This shouldn't trigger a #flush()
    channel.writeOneOutbound("Hello, Netty!");
    if (!latch.await(1L, TimeUnit.SECONDS)) {
        fail("Nobody called #write() in time.");
    }
    channel.close().syncUninterruptibly();
    // There was no #flushOutbound() call so nobody should have called #flush()
    assertEquals(0, flushCount.get());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) CountDownLatch(java.util.concurrent.CountDownLatch) ClosedChannelException(java.nio.channels.ClosedChannelException) Test(org.junit.jupiter.api.Test)

Aggregations

ChannelPromise (io.netty.channel.ChannelPromise)218 Test (org.junit.jupiter.api.Test)87 ChannelFuture (io.netty.channel.ChannelFuture)62 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)59 DefaultChannelPromise (io.netty.channel.DefaultChannelPromise)57 ByteBuf (io.netty.buffer.ByteBuf)54 ChannelOutboundHandlerAdapter (io.netty.channel.ChannelOutboundHandlerAdapter)27 Test (org.junit.Test)24 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)22 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)22 Channel (io.netty.channel.Channel)21 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)21 ClosedChannelException (java.nio.channels.ClosedChannelException)20 ChannelFutureListener (io.netty.channel.ChannelFutureListener)19 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)18 InvocationOnMock (org.mockito.invocation.InvocationOnMock)18 AsciiString (io.netty.util.AsciiString)15 IOException (java.io.IOException)13 Bootstrap (io.netty.bootstrap.Bootstrap)12 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)12