List of usage examples for io.netty.channel ChannelPipeline addAfter
ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler);
From source file:io.netty.example.http2.helloworld.frame.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *//*from w ww .j a v a 2 s . c o 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(); pipeline.addAfter(ctx.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:io.netty.example.http2.helloworld.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *///from w w w. j a v a2s .c o m private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); final HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory); final CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler = new CleartextHttp2ServerUpgradeHandler( sourceCodec, upgradeHandler, new HelloWorldHttp2HandlerBuilder().build()); p.addLast(cleartextHttp2ServerUpgradeHandler); 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(); pipeline.addAfter(ctx.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:io.reactivex.netty.protocol.http.sse.SseChannelHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse) { /**//from w w w . j ava 2s . c o m * Since SSE is an endless stream, we can never reuse a connection and hence as soon as SSE traffic is * received, the connection is marked as discardable on close. */ ctx.channel().attr(ClientRequestResponseConverter.DISCARD_CONNECTION).set(true); // SSE traffic should always discard connection on close. ChannelPipeline pipeline = ctx.channel().pipeline(); if (!HttpHeaders.isTransferEncodingChunked((HttpResponse) msg)) { pipeline.addFirst(SSE_DECODER_HANDLER_NAME, new ServerSentEventDecoder()); /* * If there are buffered messages in the previous handler at the time this message is read, we would * not be able to convert the content into an SseEvent. For this reason, we also add the decoder after * this handler, so that we can handle the buffered messages. * See the class level javadoc for more details. */ pipeline.addAfter(NAME, SSE_DECODER_POST_INBOUND_HANDLER, new ServerSentEventDecoder()); } else { pipeline.addAfter(NAME, SSE_DECODER_HANDLER_NAME, new ServerSentEventDecoder()); } ctx.fireChannelRead(msg); } else if (msg instanceof LastHttpContent) { LastHttpContent lastHttpContent = (LastHttpContent) msg; /** * The entire pipeline is set based on the assumption that LastHttpContent signals the end of the stream. * Since, here we are only passing the content to the rest of the pipeline, it becomes imperative to * also pass LastHttpContent as such. * For this reason, we send the LastHttpContent again in the pipeline. For this event sent, the content * buffer will already be read and hence will not be read again. This message serves as only containing * the trailing headers. * However, we need to increment the ref count of the content so that the assumptions down the line of the * ByteBuf always being released by the last pipeline handler will not break (as ServerSentEventDecoder releases * the ByteBuf after read). */ lastHttpContent.content().retain(); // pseudo retain so that the last handler of the pipeline can release it. if (lastHttpContent.content().isReadable()) { ctx.fireChannelRead(lastHttpContent.content()); } ctx.fireChannelRead(msg); // Since the content is already consumed above (by the SSEDecoder), this is just // as sending just trailing headers. This is critical to mark the end of stream. } else if (msg instanceof HttpContent) { ctx.fireChannelRead(((HttpContent) msg).content()); } else { ctx.fireChannelRead(msg); } }
From source file:io.reactivex.netty.protocol.http.sse.SSEInboundHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse) { ChannelPipeline pipeline = ctx.channel().pipeline(); if (!HttpHeaders.isTransferEncodingChunked((HttpResponse) msg)) { pipeline.addFirst(SSE_DECODER_HANDLER_NAME, new ServerSentEventDecoder()); /*//w ww . j a v a2 s .com * If there are buffered messages in the previous handler at the time this message is read, we would * not be able to convert the content into an SseEvent. For this reason, we also add the decoder after * this handler, so that we can handle the buffered messages. * See the class level javadoc for more details. */ pipeline.addAfter(NAME, SSE_DECODER_POST_INBOUND_HANDLER, new ServerSentEventDecoder()); } else { pipeline.addAfter(NAME, SSE_DECODER_HANDLER_NAME, new ServerSentEventDecoder()); } ctx.fireChannelRead(msg); } else if (msg instanceof LastHttpContent) { LastHttpContent lastHttpContent = (LastHttpContent) msg; /** * The entire pipeline is set based on the assumption that LastHttpContent signals the end of the stream. * Since, here we are only passing the content to the rest of the pipeline, it becomes imperative to * also pass LastHttpContent as such. * For this reason, we send the LastHttpContent again in the pipeline. For this event sent, the content * buffer will already be read and hence will not be read again. This message serves as only containing * the trailing headers. * However, we need to increment the ref count of the content so that the assumptions down the line of the * ByteBuf always being released by the last pipeline handler will not break (as ServerSentEventDecoder releases * the ByteBuf after read). */ lastHttpContent.content().retain(); // pseudo retain so that the last handler of the pipeline can release it. if (lastHttpContent.content().isReadable()) { ctx.fireChannelRead(lastHttpContent.content()); } ctx.fireChannelRead(msg); // Since the content is already consumed above (by the SSEDecoder), this is just // as sending just trailing headers. This is critical to mark the end of stream. } else if (msg instanceof HttpContent) { ctx.fireChannelRead(((HttpContent) msg).content()); } else { ctx.fireChannelRead(msg); } }
From source file:io.reactivex.netty.protocol.http.websocket.WebSocketClientHandler.java
License:Apache License
private void finishHandshake(ChannelHandlerContext ctx, FullHttpResponse msg, Channel ch) { try {/*from w ww. j a v a 2 s . co m*/ handshaker.finishHandshake(ch, msg); } catch (WebSocketHandshakeException e) { eventsSubject.onEvent(WebSocketClientMetricsEvent.HANDSHAKE_FAILURE, Clock.onEndMillis(handshakeStartTime)); handshakeFuture.setFailure(e); ctx.close(); return; } eventsSubject.onEvent(WebSocketClientMetricsEvent.HANDSHAKE_SUCCESS, Clock.onEndMillis(handshakeStartTime)); ChannelPipeline p = ctx.pipeline(); ChannelHandlerContext nettyDecoderCtx = p.context(WebSocketFrameDecoder.class); p.addAfter(nettyDecoderCtx.name(), "websocket-read-metrics", new ClientReadMetricsHandler(eventsSubject)); ChannelHandlerContext nettyEncoderCtx = p.context(WebSocketFrameEncoder.class); p.addAfter(nettyEncoderCtx.name(), "websocket-write-metrics", new ClientWriteMetricsHandler(eventsSubject)); if (messageAggregation) { p.addAfter("websocket-read-metrics", "websocket-frame-aggregator", new WebSocketFrameAggregator(maxFramePayloadLength)); } p.remove(HttpObjectAggregator.class); p.remove(this); handshakeFuture.setSuccess(); }
From source file:io.reactivex.netty.protocol.http.websocket.WebSocketServerHandler.java
License:Apache License
private void updatePipeline(ChannelHandlerContext ctx) { ChannelPipeline p = ctx.pipeline(); ChannelHandlerContext nettyEncoderCtx = p.context(WebSocketFrameEncoder.class); p.addAfter(nettyEncoderCtx.name(), "websocket-write-metrics", new ServerWriteMetricsHandler(eventsSubject)); ChannelHandlerContext nettyDecoderCtx = p.context(WebSocketFrameDecoder.class); p.addAfter(nettyDecoderCtx.name(), "websocket-read-metrics", new ServerReadMetricsHandler(eventsSubject)); if (messageAggregator) { p.addAfter("websocket-read-metrics", "websocket-frame-aggregator", new WebSocketFrameAggregator(maxFramePayloadLength)); }//from w ww . j a v a 2s .c om p.remove(this); }
From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java
License:Apache License
@Override public ServerBootstrap getServerBootstrap(EventLoopGroup parentGroup, EventLoopGroup childGroup, ChannelHandler handler) {//ww w.ja v a 2 s . co m if (this.uri.getScheme().equals("wss")) { if (keyCertChainFile == null) { log.warn("No certificate provided for WSS endpoint - will use self-signed"); try { SelfSignedCertificate certificate = new SelfSignedCertificate(); keyCertChainFile = certificate.certificate(); keyFile = certificate.privateKey(); usingSelfSignedCertificate = true; } catch (CertificateException e) { throw new RuntimeException(e); } } try { serverSslContext = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword).build(); } catch (SSLException e) { throw new RuntimeException(e); } } else if (!this.uri.getScheme().equals("ws")) { throw new IllegalArgumentException("Invalid scheme '" + uri.getScheme() + "' for web socket endpoint"); } ServerBootstrap server = new ServerBootstrap(); server.group(parentGroup, childGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (serverSslContext != null) { pipeline.addLast(serverSslContext.newHandler(ch.alloc())); } pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); // pipeline.addLast(new WebSocketServerCompressionHandler()); pipeline.addLast("websocket", new WebSocketServerProtocolHandler("/")); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { ChannelPipeline pipeline = ctx.channel().pipeline(); pipeline.addAfter("websocket", "ws-decoder-xx", new MessageToMessageDecoder<BinaryWebSocketFrame>() { @Override protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame msg, List<Object> out) throws Exception { out.add(msg.content().retain()); } }); pipeline.addAfter("websocket", "ws-encoder-xx", new MessageToMessageEncoder<ByteBuf>() { @Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { out.add(new BinaryWebSocketFrame(msg).retain()); } }); } super.userEventTriggered(ctx, evt); } }); pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter()); pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter()); pipeline.addLast(handler); } }); server.bind(uri.getPort()); return server; }
From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java
License:Apache License
@Override public IClient getClient(EventLoopGroup eventLoopGroup, ChannelHandler handler) { SslContext sslContext;/*from www . j a va2 s. c o m*/ if (this.uri.getScheme().equals("wss")) { try { SslContextBuilder builder = SslContextBuilder.forClient(); if (bypassCertificateChecks || usingSelfSignedCertificate) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } sslContext = builder.build(); } catch (SSLException e) { throw new RuntimeException(e); } } else { sslContext = null; } Bootstrap bootstrap = new Bootstrap(); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()); bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), uri.getPort())); } pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(1 << 30)); pipeline.addLast("websocket", new WebSocketClientProtocolHandler(handshaker)); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) { ChannelPipeline pipeline = ctx.channel().pipeline(); pipeline.addAfter("websocket", "ws-decoder-xx", new MessageToMessageDecoder<BinaryWebSocketFrame>() { @Override protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame msg, List<Object> out) throws Exception { out.add(msg.content().retain()); } }); pipeline.addAfter("websocket", "ws-encoder-xx", new MessageToMessageEncoder<ByteBuf>() { @Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { out.add(new BinaryWebSocketFrame(msg).retain()); } }); } super.userEventTriggered(ctx, evt); } }); pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter()); pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter()); pipeline.addLast(handler); } }); return () -> bootstrap.connect(uri.getHost(), uri.getPort()); }
From source file:jj.http.server.HttpRequestListeningHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception { this.request = request; if (request.getDecoderResult().isFailure()) { // respond with BAD_REQUEST and close the connection // (unless we are being proxied and the connection is keep-alive, that is) BAD_REQUEST.writeAndFlush(ctx).addListener(ChannelFutureListener.CLOSE); } else if (methodHandlers.containsKey(request.getMethod())) { HttpMethodHandler methodHandler = methodHandlers.get(request.getMethod()).get(); methodHandler.request(request);/*from w ww .j a va 2 s . c o m*/ ChannelPipeline p = ctx.pipeline(); p.addAfter(name, "method handler", methodHandler); ctx.fireChannelRead(request); } else { // respond with NOT_IMPLEMENTED // unless we are being proxied and the connection is keep-alive NOT_IMPLEMENTED.writeAndFlush(ctx).addListener(ChannelFutureListener.CLOSE); } }
From source file:me.netty.http.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 */// w ww.jav a2 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. ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new Http1Handler()); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }