io.netty.channel.ChannelInboundHandlerAdapter Java Examples

The following examples show how to use io.netty.channel.ChannelInboundHandlerAdapter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Http2MultiplexCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void channelClosedWhenInactiveFired() {
    LastInboundHandler inboundHandler = streamActiveAndWriteHeaders(inboundStream);
    Http2StreamChannel childChannel = (Http2StreamChannel) inboundHandler.channel();

    final AtomicBoolean channelOpen = new AtomicBoolean(false);
    final AtomicBoolean channelActive = new AtomicBoolean(false);
    assertTrue(childChannel.isOpen());
    assertTrue(childChannel.isActive());

    childChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            channelOpen.set(ctx.channel().isOpen());
            channelActive.set(ctx.channel().isActive());

            super.channelInactive(ctx);
        }
    });

    childChannel.close().syncUninterruptibly();
    assertFalse(channelOpen.get());
    assertFalse(channelActive.get());
}
 
Example #2
Source File: Http1BackendHandlerTest.java    From nitmproxy with MIT License 6 votes vote down vote up
@Test
public void shouldFireOutboundChannelClosedEvent() throws InterruptedException {
    inboundChannel.pipeline().addLast(handler);

    List<Object> events = new ArrayList<>(1);
    outboundChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            events.add(evt);
        }
    });

    inboundChannel.close().sync();

    assertFalse(events.isEmpty());
    assertEquals(1, events.size());
    assertTrue(events.get(0) instanceof OutboundChannelClosedEvent);
}
 
Example #3
Source File: Http2ServerUpgradeCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void testUpgrade(Http2ConnectionHandler handler) {
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "*");
    request.headers().set(HttpHeaderNames.HOST, "netty.io");
    request.headers().set(HttpHeaderNames.CONNECTION, "Upgrade, HTTP2-Settings");
    request.headers().set(HttpHeaderNames.UPGRADE, "h2c");
    request.headers().set("HTTP2-Settings", "AAMAAABkAAQAAP__");

    EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
    ChannelHandlerContext ctx = channel.pipeline().firstContext();
    Http2ServerUpgradeCodec codec = new Http2ServerUpgradeCodec("connectionHandler", handler);
    assertTrue(codec.prepareUpgradeResponse(ctx, request, new DefaultHttpHeaders()));
    codec.upgradeTo(ctx, request);
    // Flush the channel to ensure we write out all buffered data
    channel.flush();

    assertSame(handler, channel.pipeline().remove("connectionHandler"));
    assertNull(channel.pipeline().get(handler.getClass()));
    assertTrue(channel.finish());

    // Check that the preface was send (a.k.a the settings frame)
    ByteBuf settingsBuffer = channel.readOutbound();
    assertNotNull(settingsBuffer);
    settingsBuffer.release();

    assertNull(channel.readOutbound());
}
 
Example #4
Source File: DatagramConnectNotExistsTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public void testConnectNotExists(Bootstrap cb) throws Throwable {
    final Promise<Throwable> promise = ImmediateEventExecutor.INSTANCE.newPromise();
    cb.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            promise.trySuccess(cause);
        }
    });
    ChannelFuture future = cb.connect(NetUtil.LOCALHOST, SocketTestPermutation.BAD_PORT);
    try {
        Channel datagramChannel = future.syncUninterruptibly().channel();
        Assert.assertTrue(datagramChannel.isActive());
        datagramChannel.writeAndFlush(
                Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII)).syncUninterruptibly();
        if (!(datagramChannel instanceof OioDatagramChannel)) {
            Assert.assertTrue(promise.syncUninterruptibly().getNow() instanceof PortUnreachableException);
        }
    } finally {
        future.channel().close();
    }
}
 
Example #5
Source File: MockClient.java    From simulacron with Apache License 2.0 6 votes vote down vote up
MockClient(EventLoopGroup elg, FrameCodec<ByteBuf> frameCodec) {
  // Set up so written Frames are encoded into bytes, received bytes are encoded into Frames put
  // on queue.
  cb.group(elg)
      .channel(LocalChannel.class)
      .handler(
          new ChannelInitializer<LocalChannel>() {
            @Override
            protected void initChannel(LocalChannel ch) throws Exception {
              ch.pipeline()
                  .addLast(new FrameEncoder(frameCodec))
                  .addLast(new TestFrameDecoder(frameCodec))
                  .addLast(
                      new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg)
                            throws Exception {
                          responses.offer((Frame) msg);
                        }
                      });
            }
          });
}
 
Example #6
Source File: SocketCloseForciblyTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public void testCloseForcibly(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    sb.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            SocketChannel childChannel = (SocketChannel) msg;
            childChannel.config().setSoLinger(0);
            childChannel.unsafe().closeForcibly();
        }
    }).childHandler(new ChannelInboundHandlerAdapter());

    cb.handler(new ChannelInboundHandlerAdapter());

    Channel sc = sb.bind().sync().channel();

    cb.connect(sc.localAddress()).channel().closeFuture().syncUninterruptibly();
    sc.close().sync();
}
 
Example #7
Source File: NonSslRedirectHandler.java    From qonduit with Apache License 2.0 6 votes vote down vote up
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
    return new ChannelInboundHandlerAdapter() {

        private HttpResponseEncoder encoder = new HttpResponseEncoder();

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            LOG.trace("Received non-SSL request, returning redirect");
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
            response.headers().set(HttpHeaderNames.LOCATION, redirectAddress);
            LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
            encoder.write(ctx, response, ctx.voidPromise());
            ctx.flush();
        }
    };
}
 
Example #8
Source File: NonSslRedirectHandler.java    From timely with Apache License 2.0 6 votes vote down vote up
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
    return new ChannelInboundHandlerAdapter() {

        private HttpResponseEncoder encoder = new HttpResponseEncoder();

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            LOG.trace("Received non-SSL request, returning redirect");
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
            response.headers().set(HttpHeaderNames.LOCATION, redirectAddress);
            LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
            encoder.write(ctx, response, ctx.voidPromise());
            ctx.flush();
        }
    };
}
 
Example #9
Source File: MessageExpiryHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_pubrel_dont_expired() throws InterruptedException {
    InternalConfigurations.EXPIRE_INFLIGHT_PUBRELS = false;
    final PUBREL pubrel = new PUBREL(1);
    pubrel.setExpiryInterval(0L);
    pubrel.setPublishTimestamp(System.currentTimeMillis());
    final CountDownLatch droppedEventFiredLatch = new CountDownLatch(1);

    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, @NotNull final Object evt)
                throws Exception {
            if (evt instanceof PubrelDroppedEvent) {
                droppedEventFiredLatch.countDown();
            }
        }
    });

    channel.writeOutbound(pubrel);
    assertFalse(droppedEventFiredLatch.await(50, TimeUnit.MILLISECONDS));
    assertEquals(0L, pubrel.getExpiryInterval().longValue());
}
 
Example #10
Source File: MessageExpiryHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_pubrel_expired() throws InterruptedException {
    InternalConfigurations.EXPIRE_INFLIGHT_PUBRELS = true;

    final PUBREL pubrel = new PUBREL(1);
    pubrel.setExpiryInterval(0L);
    pubrel.setPublishTimestamp(System.currentTimeMillis());
    final CountDownLatch droppedEventFiredLatch = new CountDownLatch(1);
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, @NotNull final Object evt)
                throws Exception {
            if (evt instanceof PubrelDroppedEvent) {
                droppedEventFiredLatch.countDown();
            }
        }
    });

    channel.writeOutbound(pubrel);
    assertTrue(droppedEventFiredLatch.await(5, TimeUnit.SECONDS));
    assertEquals(0L, pubrel.getExpiryInterval().longValue());

}
 
Example #11
Source File: MessageExpiryHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_message_expired_qos_2_dup() throws Exception {
    InternalConfigurations.EXPIRE_INFLIGHT_MESSAGES = true;
    final PUBLISH publish = TestMessageUtil.createMqtt5Publish("topic", QoS.EXACTLY_ONCE);
    publish.setMessageExpiryInterval(1);
    publish.setDuplicateDelivery(true);

    Thread.sleep(2000);

    final CountDownLatch droppedEventFiredLatch = new CountDownLatch(1);
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, @NotNull final Object evt)
                throws Exception {
            if (evt instanceof PublishDroppedEvent) {
                droppedEventFiredLatch.countDown();
            }
        }
    });
    channel.writeOutbound(ctx, publish, channel.newPromise());

    assertTrue(droppedEventFiredLatch.await(5, TimeUnit.SECONDS));
    assertEquals(0, publish.getMessageExpiryInterval());
}
 
Example #12
Source File: MessageExpiryHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_message_qos_2_dup() throws Exception {
    final PUBLISH publish = TestMessageUtil.createMqtt5Publish("topic", QoS.EXACTLY_ONCE);
    publish.setMessageExpiryInterval(1);
    publish.setDuplicateDelivery(true);

    Thread.sleep(2000);

    final CountDownLatch droppedEventFiredLatch = new CountDownLatch(1);
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, @NotNull final Object evt)
                throws Exception {
            if (evt instanceof PublishDroppedEvent) {
                droppedEventFiredLatch.countDown();
            }
        }
    });
    channel.writeOutbound(ctx, publish, channel.newPromise());

    assertFalse(droppedEventFiredLatch.await(1, TimeUnit.SECONDS));
    assertEquals(0, publish.getMessageExpiryInterval());
}
 
Example #13
Source File: MessageExpiryHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_message_expired_qos_2_not_dup() throws Exception {

    final PUBLISH publish = TestMessageUtil.createMqtt5Publish("topic", QoS.EXACTLY_ONCE);
    publish.setMessageExpiryInterval(1);

    Thread.sleep(2000);

    final CountDownLatch droppedEventFiredLatch = new CountDownLatch(1);
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, @NotNull final Object evt)
                throws Exception {
            if (evt instanceof PublishDroppedEvent) {
                droppedEventFiredLatch.countDown();
            }
        }
    });
    channel.writeOutbound(ctx, publish, channel.newPromise());

    assertTrue(droppedEventFiredLatch.await(5, TimeUnit.SECONDS));
    assertEquals(0, publish.getMessageExpiryInterval());
}
 
Example #14
Source File: SocketMultipleConnectTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public void testMultipleConnect(ServerBootstrap sb, Bootstrap cb) throws Exception {
    Channel sc = null;
    Channel cc = null;
    try {
        sb.childHandler(new ChannelInboundHandlerAdapter());
        sc = sb.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();

        cb.handler(new ChannelInboundHandlerAdapter());
        cc = cb.register().syncUninterruptibly().channel();
        cc.connect(sc.localAddress()).syncUninterruptibly();
        ChannelFuture connectFuture2 = cc.connect(sc.localAddress()).await();
        assertTrue(connectFuture2.cause() instanceof AlreadyConnectedException);
    } finally {
        if (cc != null) {
            cc.close();
        }
        if (sc != null) {
            sc.close();
        }
    }
}
 
Example #15
Source File: Http2MultiplexCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void outboundStreamShouldWriteResetFrameOnClose_headersSent() {
    childChannelInitializer.handler = new ChannelInboundHandlerAdapter() {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers()));
            ctx.fireChannelActive();
        }
    };

    Channel childChannel = newOutboundStream();
    assertTrue(childChannel.isActive());

    Http2FrameStream stream2 = readOutboundHeadersAndAssignId();

    childChannel.close();
    parentChannel.runPendingTasks();

    Http2ResetFrame reset = parentChannel.readOutbound();
    assertEquals(stream2, reset.stream());
    assertEquals(Http2Error.CANCEL.code(), reset.errorCode());
}
 
Example #16
Source File: MessageExpiryHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_message_expired_qos_1() throws Exception {

    final PUBLISH publish = TestMessageUtil.createMqtt5Publish("topic", QoS.AT_LEAST_ONCE);
    publish.setMessageExpiryInterval(1);

    Thread.sleep(2000);

    final CountDownLatch droppedEventFiredLatch = new CountDownLatch(1);
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, @NotNull final Object evt)
                throws Exception {
            if (evt instanceof PublishDroppedEvent) {
                droppedEventFiredLatch.countDown();
            }
        }
    });
    channel.writeOutbound(ctx, publish, channel.newPromise());

    assertTrue(droppedEventFiredLatch.await(5, TimeUnit.SECONDS));
    assertEquals(0, publish.getMessageExpiryInterval());
}
 
Example #17
Source File: NettyNioServer.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void server(int port) throws Exception {
	final ByteBuf buf = Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8"));
	EventLoopGroup group = new NioEventLoopGroup();
	try {
		ServerBootstrap b = new ServerBootstrap();
		b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					public void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
							@Override
							public void channelActive(ChannelHandlerContext ctx) throws Exception {
								ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
							}
						});
					}
				});
		ChannelFuture f = b.bind().sync();
		f.channel().closeFuture().sync();
	} finally {
		group.shutdownGracefully().sync();
	}
}
 
Example #18
Source File: NettyOioServer.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void server(int port) throws Exception {
	final ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8")));
	EventLoopGroup group = new OioEventLoopGroup();
	try {
		ServerBootstrap b = new ServerBootstrap();
		b.group(group).channel(OioServerSocketChannel.class).localAddress(new InetSocketAddress(port))
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					public void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
							@Override
							public void channelActive(ChannelHandlerContext ctx) throws Exception {
								ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
							}
						});
					}
				});
		ChannelFuture f = b.bind().sync();
		f.channel().closeFuture().sync();
	} finally {
		group.shutdownGracefully().sync();
	}
}
 
Example #19
Source File: FlowControlHandlerTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static Channel newClient(SocketAddress server) {
    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(GROUP)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
        .handler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                fail("In this test the client is never receiving a message from the server.");
            }
        });

    return bootstrap.connect(server)
            .syncUninterruptibly()
            .channel();
}
 
Example #20
Source File: ServerChannelInitializer.java    From Cleanstone with MIT License 6 votes vote down vote up
@Override
protected void initChannel(Channel channel) {
    // inbound
    channel.pipeline().addLast("identificationHandler", new IdentificationHandler(nettyNetworking));
    channel.pipeline().addLast("encryptionDecoder", new ChannelInboundHandlerAdapter());
    channel.pipeline().addLast("byteStreamDecoder", new ByteStreamDecoder());
    channel.pipeline().addLast("compressionDecoder", new ChannelInboundHandlerAdapter());
    channel.pipeline().addLast("packetDataDecoder", new PacketDataDecoder(nettyNetworking.getProtocol()));
    channel.pipeline().addLast("inboundPacketHandler", new InboundPacketHandler(nettyNetworking));
    // outbound
    channel.pipeline().addFirst("outboundPacketHandler", new OutboundPacketHandler(nettyNetworking));
    channel.pipeline().addFirst("packetEncoder", new PacketEncoder(nettyNetworking.getProtocol()));
    channel.pipeline().addFirst("compressionEncoder", new ChannelOutboundHandlerAdapter());
    channel.pipeline().addFirst("byteStreamEncoder", new ByteStreamEncoder());
    channel.pipeline().addFirst("encryptionEncoder", new ChannelOutboundHandlerAdapter());
}
 
Example #21
Source File: RequestResponseCloseHandlerTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void serverProtocolEndEventEmitsUserEventWhenClosing() {
    AtomicBoolean ab = new AtomicBoolean(false);
    final EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
            if (evt == CloseHandler.ProtocolPayloadEndEvent.OUTBOUND) {
                ab.set(true);
            }
            ctx.fireUserEventTriggered(evt);
        }
    });
    final RequestResponseCloseHandler ch = new RequestResponseCloseHandler(false);
    channel.eventLoop().execute(() -> ch.userClosing(channel));
    channel.eventLoop().execute(() -> ch.protocolPayloadEndOutbound(channel.pipeline().firstContext()));
    channel.close().syncUninterruptibly();
    assertThat("ProtocolPayloadEndEvent.OUTBOUND not fired", ab.get(), is(true));
}
 
Example #22
Source File: LocalTransportThreadModelTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() {
    // Configure a test server
    group = new DefaultEventLoopGroup();
    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() {
                  @Override
                  public void channelRead(ChannelHandlerContext ctx, Object msg) {
                      // Discard
                      ReferenceCountUtil.release(msg);
                  }
              });
          }
      });

    localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
}
 
Example #23
Source File: LocalTransportThreadModelTest3.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() {
    // Configure a test server
    group = new DefaultEventLoopGroup();
    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() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            // Discard
                            ReferenceCountUtil.release(msg);
                        }
                    });
                }
            });

    localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
}
 
Example #24
Source File: RequestResponseCloseHandlerTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void serverProtocolEndEventDoesntEmitUntilClosing() {
    AtomicBoolean ab = new AtomicBoolean(false);
    final EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
            if (evt == CloseHandler.ProtocolPayloadEndEvent.OUTBOUND) {
                ab.set(true);
            }
            ctx.fireUserEventTriggered(evt);
        }
    });
    final RequestResponseCloseHandler ch = new RequestResponseCloseHandler(false);
    channel.eventLoop().execute(() -> ch.protocolPayloadEndOutbound(channel.pipeline().firstContext()));
    channel.close().syncUninterruptibly();
    assertThat("ProtocolPayloadEndEvent.OUTBOUND should not fire", ab.get(), is(false));
}
 
Example #25
Source File: RequestResponseCloseHandlerTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void clientProtocolEndEventEmitsUserEventAlways() {
    AtomicBoolean ab = new AtomicBoolean(false);
    final EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
            if (evt == CloseHandler.ProtocolPayloadEndEvent.OUTBOUND) {
                ab.set(true);
            }
            ctx.fireUserEventTriggered(evt);
        }
    });
    final RequestResponseCloseHandler ch = new RequestResponseCloseHandler(true);
    channel.eventLoop().execute(() -> ch.protocolPayloadEndOutbound(channel.pipeline().firstContext()));
    channel.close().syncUninterruptibly();
    assertThat("ProtocolPayloadEndEvent.OUTBOUND not fired", ab.get(), is(true));
}
 
Example #26
Source File: EpollSocketChannelTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSoLingerNoAssertError() throws Exception {
    EventLoopGroup group = new EpollEventLoopGroup(1);

    try {
        Bootstrap bootstrap = new Bootstrap();
        EpollSocketChannel ch = (EpollSocketChannel) bootstrap.group(group)
                .channel(EpollSocketChannel.class)
                .option(ChannelOption.SO_LINGER, 10)
                .handler(new ChannelInboundHandlerAdapter())
                .bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        ch.close().syncUninterruptibly();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #27
Source File: EmbeddedChannelTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlushInbound() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
          latch.countDown();
        }
    });

    channel.flushInbound();

    if (!latch.await(1L, TimeUnit.SECONDS)) {
        fail("Nobody called #channelReadComplete() in time.");
    }
}
 
Example #28
Source File: MessageExpiryHandlerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_message_expired_qos_0() throws Exception {

    final PUBLISH publish = TestMessageUtil.createMqtt5Publish("topic", QoS.AT_MOST_ONCE);
    publish.setMessageExpiryInterval(1);

    Thread.sleep(2000);

    final CountDownLatch droppedEventFiredLatch = new CountDownLatch(1);
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void userEventTriggered(final ChannelHandlerContext ctx, @NotNull final Object evt)
                throws Exception {
            if (evt instanceof PublishDroppedEvent) {
                droppedEventFiredLatch.countDown();
            }
        }
    });
    channel.writeOutbound(ctx, publish, channel.newPromise());

    assertTrue(droppedEventFiredLatch.await(5, TimeUnit.SECONDS));
    assertEquals(0, publish.getMessageExpiryInterval());
}
 
Example #29
Source File: OioEventLoopTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
 
Example #30
Source File: KQueueChannelConfigTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSoLingerNoAssertError() throws Exception {
    EventLoopGroup group = new KQueueEventLoopGroup(1);

    try {
        Bootstrap bootstrap = new Bootstrap();
        KQueueSocketChannel ch = (KQueueSocketChannel) bootstrap.group(group)
                .channel(KQueueSocketChannel.class)
                .option(ChannelOption.SO_LINGER, 10)
                .handler(new ChannelInboundHandlerAdapter())
                .bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        ch.close().syncUninterruptibly();
    } finally {
        group.shutdownGracefully();
    }
}