Search in sources :

Example 36 with ChannelHandlerContext

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

the class WebSocketServerProtocolHandlerTest method testHttpUpgradeRequest.

@Test
public void testHttpUpgradeRequest() throws Exception {
    EmbeddedChannel ch = createChannel(new MockOutboundHandler());
    ChannelHandlerContext handshakerCtx = ch.pipeline().context(WebSocketServerProtocolHandshakeHandler.class);
    writeUpgradeRequest(ch);
    FullHttpResponse response = responses.remove();
    assertEquals(SWITCHING_PROTOCOLS, response.status());
    response.release();
    assertNotNull(WebSocketServerProtocolHandler.getHandshaker(handshakerCtx.channel()));
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Test(org.junit.Test)

Example 37 with ChannelHandlerContext

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

the class LocalChannelTest method testClosePeerInWritePromiseCompleteSameEventLoopPreservesOrder.

@Test
public void testClosePeerInWritePromiseCompleteSameEventLoopPreservesOrder() throws InterruptedException {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    final CountDownLatch messageLatch = new CountDownLatch(2);
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
    final AtomicReference<Channel> serverChannelRef = new AtomicReference<Channel>();
    try {
        cb.group(sharedGroup).channel(LocalChannel.class).handler(new TestHandler());
        sb.group(sharedGroup).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

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

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        if (msg.equals(data)) {
                            ReferenceCountUtil.safeRelease(msg);
                            messageLatch.countDown();
                        } else {
                            super.channelRead(ctx, msg);
                        }
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        messageLatch.countDown();
                        super.channelInactive(ctx);
                    }
                });
                serverChannelRef.set(ch);
                serverChannelLatch.countDown();
            }
        });
        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();
            assertTrue(serverChannelLatch.await(5, SECONDS));
            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 {
                            serverChannelRef.get().close();
                        }
                    });
                    ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
                }
            });
            assertTrue(messageLatch.await(5, SECONDS));
            assertFalse(cc.isOpen());
            assertFalse(serverChannelRef.get().isOpen());
        } finally {
            closeChannel(cc);
            closeChannel(sc);
        }
    } finally {
        data.release();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) 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.Test)

Example 38 with ChannelHandlerContext

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

the class NioSocketChannelTest method testChannelReRegisterRead.

private static void testChannelReRegisterRead(final boolean sameEventLoop) throws Exception {
    final EventLoopGroup group = new NioEventLoopGroup(2);
    final CountDownLatch latch = new CountDownLatch(1);
    // Just some random bytes
    byte[] bytes = new byte[1024];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);
    Channel sc = null;
    Channel cc = null;
    ServerBootstrap b = new ServerBootstrap();
    try {
        b.group(group).channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) {
                        // We was able to read something from the Channel after reregister.
                        latch.countDown();
                    }

                    @Override
                    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                        final EventLoop loop = group.next();
                        if (sameEventLoop) {
                            deregister(ctx, loop);
                        } else {
                            loop.execute(new Runnable() {

                                @Override
                                public void run() {
                                    deregister(ctx, loop);
                                }
                            });
                        }
                    }

                    private void deregister(ChannelHandlerContext ctx, final EventLoop loop) {
                        // As soon as the channel becomes active re-register it to another
                        // EventLoop. After this is done we should still receive the data that
                        // was written to the channel.
                        ctx.deregister().addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture cf) {
                                Channel channel = cf.channel();
                                assertNotSame(loop, channel.eventLoop());
                                group.next().register(channel);
                            }
                        });
                    }
                });
            }
        });
        sc = b.bind(0).syncUninterruptibly().channel();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInboundHandlerAdapter());
        cc = bootstrap.connect(sc.localAddress()).syncUninterruptibly().channel();
        cc.writeAndFlush(Unpooled.wrappedBuffer(bytes)).syncUninterruptibly();
        latch.await();
    } finally {
        if (cc != null) {
            cc.close();
        }
        if (sc != null) {
            sc.close();
        }
        group.shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 39 with ChannelHandlerContext

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

the class NioSocketChannelTest method testFlushAfterGatheredFlush.

/**
     * Reproduces the issue #1679
     */
@Test
public void testFlushAfterGatheredFlush() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInboundHandlerAdapter() {

            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                // Trigger a gathering write by writing two buffers.
                ctx.write(Unpooled.wrappedBuffer(new byte[] { 'a' }));
                ChannelFuture f = ctx.write(Unpooled.wrappedBuffer(new byte[] { 'b' }));
                f.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // This message must be flushed
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'c' }));
                    }
                });
                ctx.flush();
            }
        });
        SocketAddress address = sb.bind(0).sync().channel().localAddress();
        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());
        DataInput in = new DataInputStream(s.getInputStream());
        byte[] buf = new byte[3];
        in.readFully(buf);
        assertThat(new String(buf, CharsetUtil.US_ASCII), is("abc"));
        s.close();
    } finally {
        group.shutdownGracefully().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DataInputStream(java.io.DataInputStream) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) DataInput(java.io.DataInput) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Socket(java.net.Socket) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 40 with ChannelHandlerContext

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

the class FragmentedMessageDeliveryTest method testPermutation.

private void testPermutation(byte[] unfragmented, ByteBuf[] fragments) throws Exception {
    // Given
    BoltStateMachine machine = mock(BoltStateMachine.class);
    Channel ch = mock(Channel.class);
    when(ch.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(ch);
    BoltProtocolV1 protocol = new BoltProtocolV1(new SynchronousBoltWorker(machine), ch, NullLogService.getInstance());
    // When data arrives split up according to the current permutation
    for (ByteBuf fragment : fragments) {
        fragment.readerIndex(0).retain();
        protocol.handle(ctx, fragment);
    }
    // Then the session should've received the specified messages, and the protocol should be in a nice clean state
    try {
        verify(machine).run(eq("Mjölnir"), anyMapOf(String.class, Object.class), any(BoltResponseHandler.class));
    } catch (AssertionError e) {
        throw new AssertionError("Failed to handle fragmented delivery.\n" + "Messages: " + Arrays.toString(messages) + "\n" + "Chunk size: " + chunkSize + "\n" + "Serialized data delivered in fragments: " + describeFragments(fragments) + "\n" + "Unfragmented data: " + HexPrinter.hex(unfragmented) + "\n", e);
    } finally {
        // To avoid buffer leak errors
        protocol.close();
    }
}
Also used : SynchronousBoltWorker(org.neo4j.bolt.v1.runtime.SynchronousBoltWorker) BoltStateMachine(org.neo4j.bolt.v1.runtime.BoltStateMachine) RecordingByteChannel(org.neo4j.bolt.v1.messaging.RecordingByteChannel) Channel(io.netty.channel.Channel) BoltResponseHandler(org.neo4j.bolt.v1.runtime.BoltResponseHandler) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) BoltProtocolV1(org.neo4j.bolt.v1.transport.BoltProtocolV1) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)661 Channel (io.netty.channel.Channel)274 ByteBuf (io.netty.buffer.ByteBuf)234 ChannelFuture (io.netty.channel.ChannelFuture)210 Test (org.junit.Test)208 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)201 Bootstrap (io.netty.bootstrap.Bootstrap)177 InetSocketAddress (java.net.InetSocketAddress)160 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)156 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)154 Test (org.junit.jupiter.api.Test)153 ChannelPipeline (io.netty.channel.ChannelPipeline)151 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)141 AtomicReference (java.util.concurrent.atomic.AtomicReference)140 IOException (java.io.IOException)137 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)120 ClosedChannelException (java.nio.channels.ClosedChannelException)119 CountDownLatch (java.util.concurrent.CountDownLatch)115 ArrayList (java.util.ArrayList)113 List (java.util.List)111