Search in sources :

Example 76 with ChannelInboundHandlerAdapter

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

the class EmbeddedChannelTest method testScheduling.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testScheduling() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
    final CountDownLatch latch = new CountDownLatch(2);
    ScheduledFuture future = ch.eventLoop().schedule(new Runnable() {

        @Override
        public void run() {
            latch.countDown();
        }
    }, 1, TimeUnit.SECONDS);
    future.addListener(new FutureListener() {

        @Override
        public void operationComplete(Future future) throws Exception {
            latch.countDown();
        }
    });
    long next = ch.runScheduledPendingTasks();
    assertTrue(next > 0);
    // Sleep for the nanoseconds but also give extra 50ms as the clock my not be very precise and so fail the test
    // otherwise.
    Thread.sleep(TimeUnit.NANOSECONDS.toMillis(next) + 50);
    assertEquals(-1, ch.runScheduledPendingTasks());
    latch.await();
}
Also used : ChannelFutureListener(io.netty.channel.ChannelFutureListener) FutureListener(io.netty.util.concurrent.FutureListener) ScheduledFuture(io.netty.util.concurrent.ScheduledFuture) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) CountDownLatch(java.util.concurrent.CountDownLatch) ScheduledFuture(io.netty.util.concurrent.ScheduledFuture) ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 77 with ChannelInboundHandlerAdapter

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

the class DefaultChannnelGroupTest method testNotThrowBlockingOperationException.

// Test for #1183
@Test
public void testNotThrowBlockingOperationException() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);
    b.childHandler(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            allChannels.add(ctx.channel());
        }
    });
    b.channel(NioServerSocketChannel.class);
    ChannelFuture f = b.bind(0).syncUninterruptibly();
    if (f.isSuccess()) {
        allChannels.add(f.channel());
        allChannels.close().awaitUninterruptibly();
    }
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
    bossGroup.terminationFuture().sync();
    workerGroup.terminationFuture().sync();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 78 with ChannelInboundHandlerAdapter

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

the class LocalChannelTest method testPeerWriteInWritePromiseCompleteSameEventLoopPreservesOrder.

@Test
public void testPeerWriteInWritePromiseCompleteSameEventLoopPreservesOrder() 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]);
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    final AtomicReference<Channel> serverChannelRef = new AtomicReference<Channel>();
    try {
        cb.group(sharedGroup).channel(LocalChannel.class).handler(new ChannelInboundHandlerAdapter() {

            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                if (data2.equals(msg) && messageLatch.getCount() == 1) {
                    ReferenceCountUtil.safeRelease(msg);
                    messageLatch.countDown();
                } else {
                    super.channelRead(ctx, msg);
                }
            }
        });
        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 (data.equals(msg) && messageLatch.getCount() == 2) {
                            ReferenceCountUtil.safeRelease(msg);
                            messageLatch.countDown();
                        } else {
                            super.channelRead(ctx, msg);
                        }
                    }
                });
                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 {
                            Channel serverChannelCpy = serverChannelRef.get();
                            serverChannelCpy.writeAndFlush(data2.retainedDuplicate(), serverChannelCpy.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) 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 79 with ChannelInboundHandlerAdapter

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

the class SimpleChannelPoolTest method testBoundedChannelPoolSegment.

@Test
public void testBoundedChannelPoolSegment() throws Exception {
    EventLoopGroup group = new LocalEventLoopGroup();
    LocalAddress addr = new LocalAddress(LOCAL_ADDR_ID);
    Bootstrap cb = new Bootstrap();
    cb.remoteAddress(addr);
    cb.group(group).channel(LocalChannel.class);
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter());
        }
    });
    // Start server
    Channel sc = sb.bind(addr).sync().channel();
    CountingChannelPoolHandler handler = new CountingChannelPoolHandler();
    ChannelPool pool = new SimpleChannelPool(cb, handler, ChannelHealthChecker.ACTIVE) {

        private final Queue<Channel> queue = new LinkedBlockingQueue<Channel>(1);

        @Override
        protected Channel pollChannel() {
            return queue.poll();
        }

        @Override
        protected boolean offerChannel(Channel ch) {
            return queue.offer(ch);
        }
    };
    Channel channel = pool.acquire().sync().getNow();
    Channel channel2 = pool.acquire().sync().getNow();
    pool.release(channel).syncUninterruptibly().getNow();
    try {
        pool.release(channel2).syncUninterruptibly();
        fail();
    } catch (IllegalStateException e) {
    // expected
    }
    channel2.close().sync();
    assertEquals(2, handler.channelCount());
    assertEquals(0, handler.acquiredCount());
    assertEquals(1, handler.releasedCount());
    sc.close().sync();
    channel.close().sync();
    channel2.close().sync();
    group.shutdownGracefully();
}
Also used : LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ExpectedException(org.junit.rules.ExpectedException) EventLoopGroup(io.netty.channel.EventLoopGroup) LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Queue(java.util.Queue) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 80 with ChannelInboundHandlerAdapter

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

the class SSLEngineTest method mySetupMutualAuth.

private void mySetupMutualAuth(KeyManagerFactory serverKMF, final File serverTrustManager, KeyManagerFactory clientKMF, File clientTrustManager, ClientAuth clientAuth, final boolean failureExpected, final boolean serverInitEngine) throws SSLException, InterruptedException {
    serverSslCtx = SslContextBuilder.forServer(serverKMF).sslProvider(sslServerProvider()).trustManager(serverTrustManager).clientAuth(clientAuth).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build();
    clientSslCtx = SslContextBuilder.forClient().sslProvider(sslClientProvider()).trustManager(clientTrustManager).keyManager(clientKMF).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build();
    serverConnectedChannel = null;
    sb = new ServerBootstrap();
    cb = new Bootstrap();
    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            SslHandler handler = serverSslCtx.newHandler(ch.alloc());
            if (serverInitEngine) {
                mySetupMutualAuthServerInitSslHandler(handler);
            }
            p.addLast(handler);
            p.addLast(new MessageDelegatorChannelHandler(serverReceiver, serverLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == SslHandshakeCompletionEvent.SUCCESS) {
                        if (failureExpected) {
                            serverException = new IllegalStateException("handshake complete. expected failure");
                        }
                        serverLatch.countDown();
                    } else if (evt instanceof SslHandshakeCompletionEvent) {
                        serverException = ((SslHandshakeCompletionEvent) evt).cause();
                        serverLatch.countDown();
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    if (cause.getCause() instanceof SSLHandshakeException) {
                        serverException = cause.getCause();
                        serverLatch.countDown();
                    } else {
                        serverException = cause;
                        ctx.fireExceptionCaught(cause);
                    }
                }
            });
            serverConnectedChannel = ch;
        }
    });
    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientSslCtx.newHandler(ch.alloc()));
            p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == SslHandshakeCompletionEvent.SUCCESS) {
                        if (failureExpected) {
                            clientException = new IllegalStateException("handshake complete. expected failure");
                        }
                        clientLatch.countDown();
                    } else if (evt instanceof SslHandshakeCompletionEvent) {
                        clientException = ((SslHandshakeCompletionEvent) evt).cause();
                        clientLatch.countDown();
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    if (cause.getCause() instanceof SSLHandshakeException) {
                        clientException = cause.getCause();
                        clientLatch.countDown();
                    } else {
                        ctx.fireExceptionCaught(cause);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
    int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
    ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Aggregations

ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)103 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)75 Channel (io.netty.channel.Channel)65 Test (org.junit.Test)62 Bootstrap (io.netty.bootstrap.Bootstrap)51 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)48 ChannelFuture (io.netty.channel.ChannelFuture)33 CountDownLatch (java.util.concurrent.CountDownLatch)32 EventLoopGroup (io.netty.channel.EventLoopGroup)28 InetSocketAddress (java.net.InetSocketAddress)26 ClosedChannelException (java.nio.channels.ClosedChannelException)26 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)23 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)23 ByteBuf (io.netty.buffer.ByteBuf)22 ChannelFutureListener (io.netty.channel.ChannelFutureListener)17 LocalServerChannel (io.netty.channel.local.LocalServerChannel)17 SocketChannel (io.netty.channel.socket.SocketChannel)17 LocalAddress (io.netty.channel.local.LocalAddress)16 LocalChannel (io.netty.channel.local.LocalChannel)16 AtomicReference (java.util.concurrent.atomic.AtomicReference)15