List of usage examples for io.netty.channel SimpleChannelInboundHandler SimpleChannelInboundHandler
protected SimpleChannelInboundHandler()
From source file:c5db.control.SimpleControlClient.java
License:Apache License
public ListenableFuture<CommandReply> sendRequest(CommandRpcRequest<?> request, InetSocketAddress remoteAddress) { SettableFuture<CommandReply> replyMessageFuture = SettableFuture.create(); ChannelFuture connectFuture = client.connect(remoteAddress); connectFuture.addListener(new ChannelFutureListener() { @Override//from ww w. j av a 2s. c om public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().pipeline().addLast(new SimpleChannelInboundHandler<CommandReply>() { @Override protected void channelRead0(ChannelHandlerContext ctx, CommandReply msg) throws Exception { replyMessageFuture.set(msg); ctx.channel().close(); } }); // connected is fine, flush message: future.channel().writeAndFlush(request); } else { replyMessageFuture.setException(future.cause()); future.channel().close(); } } }); return replyMessageFuture; }
From source file:chat.viska.xmpp.NettyTcpSession.java
License:Apache License
@SchedulerSupport(SchedulerSupport.CUSTOM) @Override/*from w w w . j a v a 2s. c om*/ protected Completable openConnection(final Compression connectionCompression, final Compression tlsCompression) { final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(nettyEventLoopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws SSLException { if (getConnection().getTlsMethod() == Connection.TlsMethod.DIRECT) { tlsHandler = TLS_CONTEXT_BUILDER.build().newHandler(channel.alloc()); channel.pipeline().addLast(PIPE_TLS, tlsHandler); } else { channel.pipeline().addLast(PIPE_TLS, new ChannelDuplexHandler()); } channel.pipeline().addLast(PIPE_COMPRESSOR, new ChannelDuplexHandler()); channel.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_STANZA_SIZE_BYTE, false, false, Unpooled.wrappedBuffer(">".getBytes(StandardCharsets.UTF_8)))); channel.pipeline().addLast(new StreamClosingDetector()); channel.pipeline().addLast(PIPE_DECODER_XML, new XmlDecoder()); channel.pipeline().addLast(new SimpleChannelInboundHandler<XmlDocumentStart>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final XmlDocumentStart msg) throws Exception { if (!"UTF-8".equalsIgnoreCase(msg.encoding())) { sendError(new StreamErrorException(StreamErrorException.Condition.UNSUPPORTED_ENCODING, "Only UTF-8 is supported in XMPP stream.")); } } }); channel.pipeline().addLast(new StreamOpeningDetector()); channel.pipeline().addLast(new XmlFrameDecoder(MAX_STANZA_SIZE_BYTE)); channel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8)); channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final String msg) throws Exception { try { feedXmlPipeline(preprocessInboundXml(msg)); } catch (SAXException ex) { sendError(new StreamErrorException(StreamErrorException.Condition.BAD_FORMAT)); } } }); channel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8)); channel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) { } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { if (cause instanceof Exception) { triggerEvent(new ExceptionCaughtEvent(NettyTcpSession.this, (Exception) cause)); } else { throw new RuntimeException(cause); } } }); } }); final ChannelFuture channelFuture = bootstrap.connect(getConnection().getDomain(), getConnection().getPort()); return Completable.fromFuture(channelFuture).andThen(Completable.fromAction(() -> { this.nettyChannel = (SocketChannel) channelFuture.channel(); nettyChannel.closeFuture().addListener(it -> changeStateToDisconnected()); })); }
From source file:com.example.grpc.server.PrometheusServer.java
License:Apache License
public void start() { final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w ww . j a v a2 s . c o m*/ protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("prometheus", new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception { if (!(o instanceof HttpRequest)) { return; } HttpRequest request = (HttpRequest) o; if (!"/metrics".equals(request.uri())) { final FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); return; } if (!HttpMethod.GET.equals(request.method())) { final FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_ACCEPTABLE); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); return; } ByteBuf buf = Unpooled.buffer(); ByteBufOutputStream os = new ByteBufOutputStream(buf); OutputStreamWriter writer = new OutputStreamWriter(os); TextFormat.write004(writer, registry.metricFamilySamples()); writer.close(); os.close(); final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, TextFormat.CONTENT_TYPE_004); channelHandlerContext.writeAndFlush(response) .addListener(ChannelFutureListener.CLOSE); } }); } }); try { this.channel = bootstrap.bind(this.port).sync().channel(); } catch (InterruptedException e) { // do nothing } }
From source file:com.flysoloing.learning.network.netty.http2.helloworld.multiplex.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *//*from ww w . ja va 2 s . c om*/ private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java
License:Open Source License
@Test(expected = ReadTimeoutException.class, timeout = 30000) public void timeoutShouldWork_read() throws Exception { ServerSocketChannel server = null; try {/*from w w w . j av a 2 s . c o m*/ server = startServer(new SimpleChannelInboundHandler<FullHttpRequest>() { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) { // Don't respond and force a client timeout. } }); int serverPort = server.localAddress().getPort(); Credentials credentials = newCredentials(); HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 5, credentials); blobStore.get("key", new ByteArrayOutputStream()); fail("Exception expected"); } finally { closeServerChannel(server); } }
From source file:com.graylog.splunk.output.senders.TCPSender.java
License:Open Source License
protected void createBootstrap(final EventLoopGroup workerGroup) { final Bootstrap bootstrap = new Bootstrap(); final SplunkSenderThread senderThread = new SplunkSenderThread(queue); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) .remoteAddress(new InetSocketAddress(hostname, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override//from ww w. j a va 2 s .com protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringEncoder()); ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { // we only send data, never read on the socket } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { senderThread.start(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { LOG.info("Channel disconnected."); senderThread.stop(); scheduleReconnect(ctx.channel().eventLoop()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.error("Exception caught", cause); } }); } }); bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOG.info("Connected."); } else { LOG.error("Connection failed: {}", future.cause().getMessage()); scheduleReconnect(future.channel().eventLoop()); } } }); }
From source file:com.hop.hhxx.example.http2.helloworld.multiplex.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *//*from w ww.j a va 2 s . co m*/ private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(msg); } }); p.addLast(new UserEventLogger()); }
From source file:com.navercorp.pinpoint.plugin.netty.NettyIT.java
License:Apache License
@Test public void listenerTest() throws Exception { final CountDownLatch awaitLatch = new CountDownLatch(1); Bootstrap bootstrap = client();/*from w w w . j a va 2 s.com*/ Channel channel = bootstrap.connect(webServer.getHostname(), webServer.getListeningPort()).sync().channel(); channel.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { 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", "/"))); }
From source file:com.navercorp.pinpoint.plugin.netty.NettyIT.java
License:Apache License
@Test public void writeTest() throws Exception { final CountDownLatch awaitLatch = new CountDownLatch(1); Bootstrap bootstrap = client();/*from w w w. j av a 2 s . c o m*/ 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) throws Exception { 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", "/"))); }
From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClientSession.java
License:Apache License
@Override protected void initChannel(final Channel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override/*from ww w . j av a 2 s. co m*/ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { bumpTimeout(ctx); ctx.fireChannelRead(msg); } }); // first four bytes are length prefix of message, strip first four bytes. pipeline.addLast(new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast(new NativeRpcDecoder()); pipeline.addLast(new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof NativeRpcError) { final NativeRpcError error = (NativeRpcError) msg; if (log.isTraceEnabled()) { log.trace("[{}] remote error: {}", ctx.channel(), error.getMessage()); } future.fail(new NativeRpcRemoteException(address, error.getMessage())); ctx.channel().close(); return; } if (msg instanceof NativeRpcResponse) { if (log.isTraceEnabled()) { log.trace("[{}] response: cancelling heartbeat", ctx.channel()); } try { handleResponse((NativeRpcResponse) msg); } catch (Exception e) { future.fail(new Exception("Failed to handle response", e)); } return; } if (msg instanceof NativeRpcHeartBeat) { if (log.isTraceEnabled()) { log.trace("[{}] heartbeat: delaying timeout by {}ms", ctx.channel(), heartbeatInterval); } bumpTimeout(ctx); return; } throw new IllegalArgumentException("unable to handle type: " + msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { future.fail(cause); ctx.channel().close(); } }); pipeline.addLast(new LengthFieldPrepender(4)); pipeline.addLast(new NativeRpcEncoder()); }