io.netty.channel.SimpleChannelInboundHandler Java Examples
The following examples show how to use
io.netty.channel.SimpleChannelInboundHandler.
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: UdpReporterTest.java From servicetalk with Apache License 2.0 | 7 votes |
TestReceiver(SpanBytesDecoder decoder) throws Exception { channel = new Bootstrap() .group(group) .channel(NioDatagramChannel.class) .option(ChannelOption.RCVBUF_ALLOCATOR, DEFAULT_RECV_BUF_ALLOCATOR) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) { byte[] b = new byte[msg.content().readableBytes()]; msg.content().readBytes(b); decoder.decode(b, queue); } }); } }) .localAddress(localAddress(0)) .bind().sync().channel(); }
Example #2
Source File: HttpCacheClientTest.java From bazel with Apache License 2.0 | 6 votes |
@Test(expected = DownloadTimeoutException.class, timeout = 30000) public void downloadTimeout() throws Exception { ServerChannel server = null; try { server = testServer.start( new SimpleChannelInboundHandler<FullHttpRequest>() { @Override protected void channelRead0( ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) { // Don't respond and force a client timeout. } }); Credentials credentials = newCredentials(); HttpCacheClient blobStore = createHttpBlobStore(server, /* timeoutSeconds= */ 1, credentials); getFromFuture(blobStore.downloadBlob(DIGEST, new ByteArrayOutputStream())); fail("Exception expected"); } finally { testServer.stop(server); } }
Example #3
Source File: ComponentTestUtils.java From riposte with Apache License 2.0 | 6 votes |
public static CompletableFuture<NettyHttpClientResponse> setupNettyHttpClientResponseHandler( Channel ch, Consumer<ChannelPipeline> pipelineAdjuster ) { CompletableFuture<NettyHttpClientResponse> responseFromServerFuture = new CompletableFuture<>(); ch.pipeline().replace("clientResponseHandler", "clientResponseHandler", new SimpleChannelInboundHandler<HttpObject>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof FullHttpResponse) { // Store the proxyServer response for asserting on later. responseFromServerFuture.complete(new NettyHttpClientResponse((FullHttpResponse) msg)); } else { // Should never happen. throw new RuntimeException("Received unexpected message type: " + msg.getClass()); } } }); if (pipelineAdjuster != null) pipelineAdjuster.accept(ch.pipeline()); return responseFromServerFuture; }
Example #4
Source File: ComponentTestUtils.java From riposte with Apache License 2.0 | 6 votes |
public static Bootstrap createNettyHttpClientBootstrap() { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(new NioEventLoopGroup()) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec()); p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE)); p.addLast("clientResponseHandler", new SimpleChannelInboundHandler<HttpObject>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { throw new RuntimeException("Client response handler was not setup before the call"); } }); } }); return bootstrap; }
Example #5
Source File: ErrorHandler.java From async-gamequery-lib with MIT License | 6 votes |
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (log.isDebugEnabled()) { log.error("Unhandled exception caught within the pipeline {} for Channel {}, Id: {}", cause, ctx.channel(), ctx.channel().id()); if (ctx.channel().hasAttr(ChannelAttributes.LAST_REQUEST_SENT)) { AbstractRequest request = ctx.channel().attr(ChannelAttributes.LAST_REQUEST_SENT).get(); if (request != null && SocketChannel.class.isAssignableFrom(ctx.channel().getClass())) { Throwable ex = new ResponseException(request, cause); SimpleChannelInboundHandler responseRouter = ctx.pipeline().get(SimpleChannelInboundHandler.class); responseRouter.channelRead(ctx, ex); return; } } throw new TransportException(cause); } }
Example #6
Source File: HttpResponseWriterTest.java From styx with Apache License 2.0 | 6 votes |
@Test public void failsTheResultWhenResponseWriteFails() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new CaptureChannelArgumentsHandler(channelArgs), new SimpleChannelInboundHandler<LiveHttpResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, LiveHttpResponse response) throws Exception { HttpResponseWriter writer = new HttpResponseWriter(ctx); CompletableFuture<Void> future = writer.write(response); assertThat(future.isDone(), is(false)); writeError(channelArgs); assertThat(future.isDone(), is(true)); future.get(200, MILLISECONDS); } } ); assertThrows(ExecutionException.class, () -> ch.writeInbound(response(OK).body(new ByteStream(contentObservable)).build())); }
Example #7
Source File: HttpCacheClientTest.java From bazel with Apache License 2.0 | 6 votes |
@Test(expected = UploadTimeoutException.class, timeout = 30000) public void uploadTimeout() throws Exception { ServerChannel server = null; try { server = testServer.start( new SimpleChannelInboundHandler<FullHttpRequest>() { @Override protected void channelRead0( ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) { // Don't respond and force a client timeout. } }); Credentials credentials = newCredentials(); HttpCacheClient blobStore = createHttpBlobStore(server, /* timeoutSeconds= */ 1, credentials); byte[] data = "File Contents".getBytes(Charsets.US_ASCII); getFromFuture(blobStore.uploadBlob(DIGEST_UTIL.compute(data), ByteString.copyFrom(data))); fail("Exception expected"); } finally { testServer.stop(server); } }
Example #8
Source File: HttpResponseWriterTest.java From styx with Apache License 2.0 | 6 votes |
@Test public void completesFutureOnlyAfterContentObservableIsCompleted() throws Exception { EmbeddedChannel ch = new EmbeddedChannel( new SimpleChannelInboundHandler<LiveHttpResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, LiveHttpResponse response) throws Exception { HttpResponseWriter writer = new HttpResponseWriter(ctx); CompletableFuture<Void> future = writer.write(response); assertThat(future.isDone(), is(false)); contentObservable.onNext(new Buffer("aaa", UTF_8)); assertThat(future.isDone(), is(false)); contentObservable.onComplete(); assertThat(future.isDone(), is(true)); channelRead.set(true); } } ); ch.writeInbound(response(OK).body(new ByteStream(contentObservable)).build()); assertThat(channelRead.get(), is(true)); }
Example #9
Source File: NettyConnectionFactoryTest.java From styx with Apache License 2.0 | 6 votes |
private Flux<HttpObject> channelRequestResponse(Channel channel, FullHttpRequest request) { return Flux.create(sink -> { channel.pipeline().addLast(new SimpleChannelInboundHandler<HttpObject>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { sink.next(msg); if (msg instanceof DefaultHttpResponse) { DefaultHttpResponse response = (DefaultHttpResponse) msg; if (response.decoderResult().isFailure()) { sink.error(response.decoderResult().cause()); } } if (msg instanceof LastHttpContent) { sink.complete(); } } }); channel.writeAndFlush(request); }); }
Example #10
Source File: NettyBroadcastService.java From atomix with Apache License 2.0 | 6 votes |
private CompletableFuture<Void> bootstrapServer() { Bootstrap serverBootstrap = new Bootstrap() .group(group) .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4)) .handler(new SimpleChannelInboundHandler<Object>() { @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // Nothing will be sent. } }) .option(ChannelOption.IP_MULTICAST_IF, iface) .option(ChannelOption.SO_REUSEADDR, true); CompletableFuture<Void> future = new CompletableFuture<>(); serverBootstrap.bind(localAddress).addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { serverChannel = f.channel(); future.complete(null); } else { future.completeExceptionally(f.cause()); } }); return future; }
Example #11
Source File: DatagramUnicastTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@SuppressWarnings("deprecation") private Channel setupServerChannel(Bootstrap sb, final byte[] bytes, final CountDownLatch latch) throws Throwable { sb.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() { @Override public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { ByteBuf buf = msg.content(); assertEquals(bytes.length, buf.readableBytes()); for (byte b : bytes) { assertEquals(b, buf.readByte()); } latch.countDown(); } }); } }); return sb.bind(newSocketAddress()).sync().channel(); }
Example #12
Source File: NettyUnicastService.java From atomix with Apache License 2.0 | 6 votes |
private CompletableFuture<Void> bootstrap() { Bootstrap serverBootstrap = new Bootstrap() .group(group) .channel(NioDatagramChannel.class) .handler(new SimpleChannelInboundHandler<DatagramPacket>() { @Override protected void channelRead0(ChannelHandlerContext context, DatagramPacket packet) throws Exception { byte[] payload = new byte[packet.content().readInt()]; packet.content().readBytes(payload); Message message = SERIALIZER.decode(payload); Map<BiConsumer<Address, byte[]>, Executor> listeners = NettyUnicastService.this.listeners.get(message.subject()); if (listeners != null) { listeners.forEach((consumer, executor) -> executor.execute(() -> consumer.accept(message.source(), message.payload()))); } } }) .option(ChannelOption.RCVBUF_ALLOCATOR, new DefaultMaxBytesRecvByteBufAllocator()) .option(ChannelOption.SO_BROADCAST, true) .option(ChannelOption.SO_REUSEADDR, true); return bind(serverBootstrap); }
Example #13
Source File: SimpleSipStack.java From sipstack with MIT License | 6 votes |
private ServerBootstrap createTCPListeningPoint(final SimpleChannelInboundHandler<SipMessageEvent> handler) { final ServerBootstrap b = new ServerBootstrap(); b.group(this.bossGroup, this.workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("decoder", new SipMessageStreamDecoder()); pipeline.addLast("encoder", new SipMessageEncoder()); pipeline.addLast("handler", handler); } }) .option(ChannelOption.SO_BACKLOG, 128) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.TCP_NODELAY, true); return b; }
Example #14
Source File: HttpServerLiveTest.java From tutorials with MIT License | 6 votes |
@Before public void setup() throws Exception { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec()); p.addLast(new HttpContentDecompressor()); p.addLast(new SimpleChannelInboundHandler<HttpObject>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { response = prepareResponse(ctx, msg, response); } }); } }); channel = b.connect(HOST, PORT) .sync() .channel(); }
Example #15
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #16
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #17
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #18
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #19
Source File: NettyServerUtil.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #20
Source File: NettyServerUtil.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static void newHttpServerBootstrap(String ip, int port, SimpleChannelInboundHandler<? extends FullHttpRequest> handler){ ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("aggregator", new HttpObjectAggregator(65536)); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("chunkedWriter", new ChunkedWriteHandler()); p.addLast("handler", handler ); } }; newHttpServerBootstrap(ip, port, channelInitializer); }
Example #21
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #22
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #23
Source File: PipelineRegistryTest.java From crate with Apache License 2.0 | 5 votes |
private static PipelineRegistry.ChannelPipelineItem channelPipelineItem(String base, String name) { return new PipelineRegistry.ChannelPipelineItem(base, name, (f) -> new SimpleChannelInboundHandler() { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { } }); }
Example #24
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #25
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #26
Source File: BootstrapTemplate.java From netty-cookbook with Apache License 2.0 | 5 votes |
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){ return new Bootstrap().group(loopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(handler) .bind(port); }
Example #27
Source File: NettyIT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void listenerTest() throws Exception { final CountDownLatch awaitLatch = new CountDownLatch(1); Bootstrap bootstrap = client(); Channel channel = bootstrap.connect(webServer.getHostname(), webServer.getListeningPort()).sync().channel(); channel.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) { awaitLatch.countDown(); } }); HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); channel.writeAndFlush(request); boolean await = awaitLatch.await(3000, TimeUnit.MILLISECONDS); Assert.assertTrue(await); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event("NETTY", Bootstrap.class.getMethod("connect", SocketAddress.class), annotation("netty.address", webServer.getHostAndPort()))); verifier.verifyTrace(event("NETTY", "io.netty.channel.DefaultChannelPipeline.writeAndFlush(java.lang.Object)")); verifier.verifyTrace(event("ASYNC", "Asynchronous Invocation")); verifier.verifyTrace(event("NETTY_HTTP", "io.netty.handler.codec.http.HttpObjectEncoder.encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)", annotation("http.url", "/"))); }
Example #28
Source File: NettyIT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void writeTest() throws Exception { final CountDownLatch awaitLatch = new CountDownLatch(1); Bootstrap bootstrap = client(); bootstrap.connect(webServer.getHostname(), webServer.getListeningPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { Channel channel = future.channel(); channel.pipeline().addLast(new SimpleChannelInboundHandler() { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { awaitLatch.countDown(); } }); HttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); future.channel().writeAndFlush(request); } } }); boolean await = awaitLatch.await(3000, TimeUnit.MILLISECONDS); Assert.assertTrue(await); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event("NETTY", Bootstrap.class.getMethod("connect", SocketAddress.class), annotation("netty.address", webServer.getHostAndPort()))); verifier.verifyTrace(event("NETTY", "io.netty.channel.DefaultChannelPromise.addListener(io.netty.util.concurrent.GenericFutureListener)")); verifier.verifyTrace(event("ASYNC", "Asynchronous Invocation")); verifier.verifyTrace(event("NETTY_INTERNAL", "io.netty.util.concurrent.DefaultPromise.notifyListenersNow()")); verifier.verifyTrace(event("NETTY_INTERNAL", "io.netty.util.concurrent.DefaultPromise.notifyListener0(io.netty.util.concurrent.Future, io.netty.util.concurrent.GenericFutureListener)")); verifier.verifyTrace(event("NETTY", "io.netty.channel.DefaultChannelPipeline.writeAndFlush(java.lang.Object)")); verifier.verifyTrace(event("NETTY_HTTP", "io.netty.handler.codec.http.HttpObjectEncoder.encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)", annotation("http.url", "/"))); }
Example #29
Source File: HttpCacheClientTest.java From bazel with Apache License 2.0 | 5 votes |
@Test public void uploadResponseTooLarge() throws Exception { ServerChannel server = null; try { server = testServer.start( new SimpleChannelInboundHandler<FullHttpRequest>() { @Override protected void channelRead0( ChannelHandlerContext channelHandlerContext, FullHttpRequest request) { ByteBuf longMessage = channelHandlerContext.alloc().buffer(50000).writerIndex(50000); DefaultFullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, longMessage); channelHandlerContext .writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); } }); Credentials credentials = newCredentials(); HttpCacheClient blobStore = createHttpBlobStore(server, /* timeoutSeconds= */ 1, credentials); ByteString data = ByteString.copyFrom("File Contents", Charsets.US_ASCII); IOException e = assertThrows( IOException.class, () -> getFromFuture( blobStore.uploadBlob(DIGEST_UTIL.compute(data.toByteArray()), data))); assertThat(e.getCause()).isInstanceOf(TooLongFrameException.class); } finally { testServer.stop(server); } }
Example #30
Source File: HttpCacheClientTest.java From bazel with Apache License 2.0 | 5 votes |
@Test public void testDownloadFailsOnDigestMismatch() throws Exception { // Test that the download fails when a blob/file has a different content hash than expected. ServerChannel server = null; try { server = testServer.start( new SimpleChannelInboundHandler<FullHttpRequest>() { @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) { ByteBuf data = ctx.alloc().buffer(); ByteBufUtil.writeUtf8(data, "bar"); DefaultFullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, data); HttpUtil.setContentLength(response, data.readableBytes()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } }); Credentials credentials = newCredentials(); HttpCacheClient blobStore = createHttpBlobStore( server, /* timeoutSeconds= */ 1, /* remoteVerifyDownloads= */ true, credentials); Digest fooDigest = DIGEST_UTIL.compute("foo".getBytes(Charsets.UTF_8)); try (OutputStream out = new ByteArrayOutputStream()) { IOException e = assertThrows( IOException.class, () -> getFromFuture(blobStore.downloadBlob(fooDigest, out))); assertThat(e).hasMessageThat().contains(fooDigest.getHash()); assertThat(e).hasMessageThat().contains(DIGEST_UTIL.computeAsUtf8("bar").getHash()); } } finally { testServer.stop(server); } }