View Javadoc
1   /*
2    * Copyright 2014 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    *   https://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.server;
18  
19  import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
20  
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.channel.ChannelInboundHandlerAdapter;
23  import io.netty.channel.ChannelInitializer;
24  import io.netty.channel.ChannelPipeline;
25  import io.netty.channel.SimpleChannelInboundHandler;
26  import io.netty.channel.socket.SocketChannel;
27  import io.netty.handler.codec.http.HttpMessage;
28  import io.netty.handler.codec.http.HttpObjectAggregator;
29  import io.netty.handler.codec.http.HttpServerCodec;
30  import io.netty.handler.codec.http.HttpServerUpgradeHandler;
31  import io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodec;
32  import io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodecFactory;
33  import io.netty.handler.codec.http2.CleartextHttp2ServerUpgradeHandler;
34  import io.netty.handler.codec.http2.Http2CodecUtil;
35  import io.netty.handler.codec.http2.Http2ServerUpgradeCodec;
36  import io.netty.handler.ssl.SslContext;
37  import io.netty.util.AsciiString;
38  import io.netty.util.ReferenceCountUtil;
39  
40  /**
41   * Sets up the Netty pipeline for the example server. Depending on the endpoint config, sets up the
42   * pipeline for NPN or cleartext HTTP upgrade to HTTP/2.
43   */
44  public class Http2ServerInitializer extends ChannelInitializer<SocketChannel> {
45  
46      private static final UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() {
47          @Override
48          public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
49              if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
50                  return new Http2ServerUpgradeCodec(new HelloWorldHttp2HandlerBuilder().build());
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          this.sslCtx = sslCtx;
66          this.maxHttpContentLength = checkPositiveOrZero(maxHttpContentLength, "maxHttpContentLength");
67      }
68  
69      @Override
70      public void initChannel(SocketChannel ch) {
71          if (sslCtx != null) {
72              configureSsl(ch);
73          } else {
74              configureClearText(ch);
75          }
76      }
77  
78      /**
79       * Configure the pipeline for TLS NPN negotiation to HTTP/2.
80       */
81      private void configureSsl(SocketChannel ch) {
82          ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler());
83      }
84  
85      /**
86       * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
87       */
88      private void configureClearText(SocketChannel ch) {
89          final ChannelPipeline p = ch.pipeline();
90          final HttpServerCodec sourceCodec = new HttpServerCodec();
91          final HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory);
92          final CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler =
93                  new CleartextHttp2ServerUpgradeHandler(sourceCodec, upgradeHandler,
94                                                         new HelloWorldHttp2HandlerBuilder().build());
95  
96          p.addLast(cleartextHttp2ServerUpgradeHandler);
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                 pipeline.addAfter(ctx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted."));
104                 pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
105                 ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
106             }
107         });
108 
109         p.addLast(new UserEventLogger());
110     }
111 
112     /**
113      * Class that logs any User Events triggered on this channel.
114      */
115     private static class UserEventLogger extends ChannelInboundHandlerAdapter {
116         @Override
117         public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
118             System.out.println("User Event Triggered: " + evt);
119             ctx.fireUserEventTriggered(evt);
120         }
121     }
122 }