View Javadoc
1   /*
2    * Copyright 2015 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.tiles;
18  
19  import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
20  import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;
21  import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE;
22  import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
23  import io.netty.channel.ChannelFutureListener;
24  import io.netty.channel.ChannelHandlerContext;
25  import io.netty.handler.codec.http.DefaultFullHttpResponse;
26  import io.netty.handler.codec.http.FullHttpRequest;
27  import io.netty.handler.codec.http.FullHttpResponse;
28  import io.netty.handler.codec.http.HttpUtil;
29  import io.netty.handler.codec.http.HttpHeaderValues;
30  
31  import java.util.concurrent.TimeUnit;
32  
33  /**
34   * Handles the requests for the tiled image using HTTP 1.x as a protocol.
35   */
36  public final class Http1RequestHandler extends Http2RequestHandler {
37  
38      @Override
39      protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
40          if (HttpUtil.is100ContinueExpected(request)) {
41              ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
42          }
43          super.channelRead0(ctx, request);
44      }
45  
46      @Override
47      protected void sendResponse(final ChannelHandlerContext ctx, String streamId, int latency,
48              final FullHttpResponse response, final FullHttpRequest request) {
49          HttpUtil.setContentLength(response, response.content().readableBytes());
50          ctx.executor().schedule(new Runnable() {
51              @Override
52              public void run() {
53                  if (isKeepAlive(request)) {
54                      response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
55                      ctx.writeAndFlush(response);
56                  } else {
57                      ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
58                  }
59              }
60          }, latency, TimeUnit.MILLISECONDS);
61      }
62  }