View Javadoc
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License, version 2.0 (the
5    * "License"); you may not use this file except in compliance with the License. You may obtain a
6    * 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 distributed under the License
11   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing permissions and limitations under
13   * the License.
14   */
15  package io.netty5.example.http2.helloworld.multiplex.server;
16  
17  import io.netty5.channel.ChannelHandlerContext;
18  import io.netty5.example.http2.helloworld.server.HelloWorldHttp1Handler;
19  import io.netty5.handler.codec.http.HttpObjectAggregator;
20  import io.netty5.handler.codec.http.HttpServerCodec;
21  import io.netty5.handler.codec.http2.Http2FrameCodecBuilder;
22  import io.netty5.handler.codec.http2.Http2MultiplexHandler;
23  import io.netty5.handler.ssl.ApplicationProtocolNames;
24  import io.netty5.handler.ssl.ApplicationProtocolNegotiationHandler;
25  
26  /**
27   * Negotiates with the browser if HTTP2 or HTTP is going to be used. Once decided, the Netty
28   * pipeline is setup with the correct handlers for the selected protocol.
29   */
30  public class Http2OrHttpHandler extends ApplicationProtocolNegotiationHandler {
31  
32      private static final int MAX_CONTENT_LENGTH = 1024 * 100;
33  
34      protected Http2OrHttpHandler() {
35          super(ApplicationProtocolNames.HTTP_1_1);
36      }
37  
38      @Override
39      protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
40          if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
41              ctx.pipeline().addLast(Http2FrameCodecBuilder.forServer().build());
42              ctx.pipeline().addLast(new Http2MultiplexHandler(new HelloWorldHttp2Handler()));
43              return;
44          }
45  
46          if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
47              ctx.pipeline().addLast(new HttpServerCodec(),
48                                     new HttpObjectAggregator(MAX_CONTENT_LENGTH),
49                                     new HelloWorldHttp1Handler("ALPN Negotiation"));
50              return;
51          }
52  
53          throw new IllegalStateException("unknown protocol: " + protocol);
54      }
55  }