View Javadoc
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty.example.http2.helloworld.frame.server;
18  
19  import io.netty.channel.ChannelHandlerContext;
20  import io.netty.channel.ChannelInboundHandlerAdapter;
21  import io.netty.channel.ChannelInitializer;
22  import io.netty.channel.ChannelPipeline;
23  import io.netty.channel.SimpleChannelInboundHandler;
24  import io.netty.channel.socket.SocketChannel;
25  import io.netty.example.http2.helloworld.server.HelloWorldHttp1Handler;
26  import io.netty.handler.codec.http.HttpMessage;
27  import io.netty.handler.codec.http.HttpObjectAggregator;
28  import io.netty.handler.codec.http.HttpServerCodec;
29  import io.netty.handler.codec.http.HttpServerUpgradeHandler;
30  import io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodec;
31  import io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodecFactory;
32  import io.netty.handler.codec.http2.Http2CodecUtil;
33  import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
34  import io.netty.handler.codec.http2.Http2ServerUpgradeCodec;
35  import io.netty.handler.ssl.SslContext;
36  import io.netty.util.AsciiString;
37  import io.netty.util.ReferenceCountUtil;
38  
39  /**
40   * Sets up the Netty pipeline for the example server. Depending on the endpoint config, sets up the
41   * pipeline for NPN or cleartext HTTP upgrade to HTTP/2.
42   */
43  public class Http2ServerInitializer extends ChannelInitializer<SocketChannel> {
44  
45      private static final UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() {
46          @Override
47          public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
48              if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
49                  return new Http2ServerUpgradeCodec(
50                          Http2FrameCodecBuilder.forServer().build(), new HelloWorldHttp2Handler());
51              } else {
52                  return null;
53              }
54          }
55      };
56  
57      private final SslContext sslCtx;
58      private final int maxHttpContentLength;
59  
60      public Http2ServerInitializer(SslContext sslCtx) {
61          this(sslCtx, 16 * 1024);
62      }
63  
64      public Http2ServerInitializer(SslContext sslCtx, int maxHttpContentLength) {
65          if (maxHttpContentLength < 0) {
66              throw new IllegalArgumentException("maxHttpContentLength (expected >= 0): " + maxHttpContentLength);
67          }
68          this.sslCtx = sslCtx;
69          this.maxHttpContentLength = maxHttpContentLength;
70      }
71  
72      @Override
73      public void initChannel(SocketChannel ch) {
74          if (sslCtx != null) {
75              configureSsl(ch);
76          } else {
77              configureClearText(ch);
78          }
79      }
80  
81      /**
82       * Configure the pipeline for TLS NPN negotiation to HTTP/2.
83       */
84      private void configureSsl(SocketChannel ch) {
85          ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler());
86      }
87  
88      /**
89       * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
90       */
91      private void configureClearText(SocketChannel ch) {
92          final ChannelPipeline p = ch.pipeline();
93          final HttpServerCodec sourceCodec = new HttpServerCodec();
94  
95          p.addLast(sourceCodec);
96          p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
97          p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
98              @Override
99              protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
100                 // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
101                 System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)");
102                 ChannelPipeline pipeline = ctx.pipeline();
103                 ChannelHandlerContext thisCtx = pipeline.context(this);
104                 pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted."));
105                 pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
106                 ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
107             }
108         });
109 
110         p.addLast(new UserEventLogger());
111     }
112 
113     /**
114      * Class that logs any User Events triggered on this channel.
115      */
116     private static class UserEventLogger extends ChannelInboundHandlerAdapter {
117         @Override
118         public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
119             System.out.println("User Event Triggered: " + evt);
120             ctx.fireUserEventTriggered(evt);
121         }
122     }
123 }