Search in sources :

Example 46 with ChannelHandler

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

the class EmbeddedChannelTest method testHandlerAddedExecutedInEventLoop.

@Test
@Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
public void testHandlerAddedExecutedInEventLoop() throws Throwable {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    final ChannelHandler handler = new ChannelHandlerAdapter() {

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            try {
                assertTrue(ctx.executor().inEventLoop());
            } catch (Throwable cause) {
                error.set(cause);
            } finally {
                latch.countDown();
            }
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(handler);
    assertFalse(channel.finish());
    latch.await();
    Throwable cause = error.get();
    if (cause != null) {
        throw cause;
    }
}
Also used : ChannelHandlerAdapter(io.netty.channel.ChannelHandlerAdapter) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 47 with ChannelHandler

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

the class EmbeddedChannelTest method testConstructWithChannelInitializer.

@Test
public void testConstructWithChannelInitializer() {
    final Integer first = 1;
    final Integer second = 2;
    final ChannelHandler handler = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ctx.fireChannelRead(first);
            ctx.fireChannelRead(second);
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(handler);
        }
    });
    ChannelPipeline pipeline = channel.pipeline();
    assertSame(handler, pipeline.firstContext().handler());
    assertTrue(channel.writeInbound(3));
    assertTrue(channel.finish());
    assertSame(first, channel.readInbound());
    assertSame(second, channel.readInbound());
    assertNull(channel.readInbound());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelPipeline(io.netty.channel.ChannelPipeline) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 48 with ChannelHandler

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

the class AbstractCompatibleMarshallingDecoderTest method testTooBigObject.

@Test
public void testTooBigObject() throws IOException {
    MarshallerFactory marshallerFactory = createMarshallerFactory();
    MarshallingConfiguration configuration = createMarshallingConfig();
    ChannelHandler mDecoder = createDecoder(4);
    EmbeddedChannel ch = new EmbeddedChannel(mDecoder);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    Marshaller marshaller = marshallerFactory.createMarshaller(configuration);
    marshaller.start(Marshalling.createByteOutput(bout));
    marshaller.writeObject(testObject);
    marshaller.finish();
    marshaller.close();
    byte[] testBytes = bout.toByteArray();
    onTooBigFrame(ch, input(testBytes));
}
Also used : MarshallerFactory(org.jboss.marshalling.MarshallerFactory) Marshaller(org.jboss.marshalling.Marshaller) MarshallingConfiguration(org.jboss.marshalling.MarshallingConfiguration) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandler(io.netty.channel.ChannelHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Test(org.junit.jupiter.api.Test)

Example 49 with ChannelHandler

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

the class FlowControlHandlerTest method testRemoveFlowControl.

@Test
public void testRemoveFlowControl() throws Exception {
    final CountDownLatch latch = new CountDownLatch(3);
    ChannelInboundHandlerAdapter handler = new ChannelDuplexHandler() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            // do the first read
            ctx.read();
            super.channelActive(ctx);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            latch.countDown();
            super.channelRead(ctx, msg);
        }
    };
    FlowControlHandler flow = new FlowControlHandler() {

        private int num;

        @Override
        public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
            super.channelRead(ctx, msg);
            ++num;
            if (num >= 3) {
                // We have received 3 messages. Remove myself later
                final ChannelHandler handler = this;
                ctx.channel().eventLoop().execute(new Runnable() {

                    @Override
                    public void run() {
                        ctx.pipeline().remove(handler);
                    }
                });
            }
        }
    };
    ChannelInboundHandlerAdapter tail = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            // consume this msg
            ReferenceCountUtil.release(msg);
        }
    };
    Channel server = newServer(false, /* no auto read */
    flow, handler, tail);
    Channel client = newClient(server.localAddress());
    try {
        // Write one message
        client.writeAndFlush(newOneMessage()).sync();
        // We should receive 3 messages
        assertTrue(latch.await(1L, SECONDS));
        assertTrue(flow.isQueueEmpty());
    } finally {
        client.close();
        server.close();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 50 with ChannelHandler

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

the class CipherSuiteCanaryTest method testHandshake.

@ParameterizedTest(name = "{index}: serverSslProvider = {0}, clientSslProvider = {1}, rfcCipherName = {2}, delegate = {3}")
@MethodSource("parameters")
public void testHandshake(SslProvider serverSslProvider, SslProvider clientSslProvider, String rfcCipherName, boolean delegate) throws Exception {
    // Check if the cipher is supported at all which may not be the case for various JDK versions and OpenSSL API
    // implementations.
    assumeCipherAvailable(serverSslProvider, rfcCipherName);
    assumeCipherAvailable(clientSslProvider, rfcCipherName);
    List<String> ciphers = Collections.singletonList(rfcCipherName);
    final SslContext sslServerContext = SslContextBuilder.forServer(CERT.certificate(), CERT.privateKey()).sslProvider(serverSslProvider).ciphers(ciphers).protocols(SslProtocols.TLS_v1_2).build();
    final ExecutorService executorService = delegate ? Executors.newCachedThreadPool() : null;
    try {
        final SslContext sslClientContext = SslContextBuilder.forClient().sslProvider(clientSslProvider).ciphers(ciphers).protocols(SslProtocols.TLS_v1_2).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        try {
            final Promise<Object> serverPromise = GROUP.next().newPromise();
            final Promise<Object> clientPromise = GROUP.next().newPromise();
            ChannelHandler serverHandler = new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(newSslHandler(sslServerContext, ch.alloc(), executorService));
                    pipeline.addLast(new SimpleChannelInboundHandler<Object>() {

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            serverPromise.cancel(true);
                            ctx.fireChannelInactive();
                        }

                        @Override
                        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (serverPromise.trySuccess(null)) {
                                ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'P', 'O', 'N', 'G' }));
                            }
                            ctx.close();
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            if (!serverPromise.tryFailure(cause)) {
                                ctx.fireExceptionCaught(cause);
                            }
                        }
                    });
                }
            };
            LocalAddress address = new LocalAddress("test-" + serverSslProvider + '-' + clientSslProvider + '-' + rfcCipherName);
            Channel server = server(address, serverHandler);
            try {
                ChannelHandler clientHandler = new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(newSslHandler(sslClientContext, ch.alloc(), executorService));
                        pipeline.addLast(new SimpleChannelInboundHandler<Object>() {

                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                clientPromise.cancel(true);
                                ctx.fireChannelInactive();
                            }

                            @Override
                            public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                                clientPromise.trySuccess(null);
                                ctx.close();
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                if (!clientPromise.tryFailure(cause)) {
                                    ctx.fireExceptionCaught(cause);
                                }
                            }
                        });
                    }
                };
                Channel client = client(server, clientHandler);
                try {
                    client.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'P', 'I', 'N', 'G' })).syncUninterruptibly();
                    assertTrue(clientPromise.await(5L, TimeUnit.SECONDS), "client timeout");
                    assertTrue(serverPromise.await(5L, TimeUnit.SECONDS), "server timeout");
                    clientPromise.sync();
                    serverPromise.sync();
                } finally {
                    client.close().sync();
                }
            } finally {
                server.close().sync();
            }
        } finally {
            ReferenceCountUtil.release(sslClientContext);
        }
    } finally {
        ReferenceCountUtil.release(sslServerContext);
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ExecutorService(java.util.concurrent.ExecutorService) ChannelInitializer(io.netty.channel.ChannelInitializer) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Aggregations

ChannelHandler (io.netty.channel.ChannelHandler)186 Test (org.junit.Test)88 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)44 Channel (io.netty.channel.Channel)26 ChannelPipeline (io.netty.channel.ChannelPipeline)25 SslHandler (io.netty.handler.ssl.SslHandler)25 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)22 FilterChainMatchingHandler (io.grpc.xds.FilterChainMatchingProtocolNegotiators.FilterChainMatchingHandler)20 ChannelFuture (io.netty.channel.ChannelFuture)20 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)20 FilterChainSelector (io.grpc.xds.FilterChainMatchingProtocolNegotiators.FilterChainMatchingHandler.FilterChainSelector)19 ChannelHandlerAdapter (io.netty.channel.ChannelHandlerAdapter)18 DownstreamTlsContext (io.grpc.xds.EnvoyServerProtoData.DownstreamTlsContext)17 FilterChain (io.grpc.xds.EnvoyServerProtoData.FilterChain)17 InetSocketAddress (java.net.InetSocketAddress)16 Test (org.junit.jupiter.api.Test)16 LineBasedFrameDecoder (io.netty.handler.codec.LineBasedFrameDecoder)12 AtomicReference (java.util.concurrent.atomic.AtomicReference)12 Bootstrap (io.netty.bootstrap.Bootstrap)11 ArrayList (java.util.ArrayList)11