View Javadoc

1   /*
2    * Copyright 2012 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  package io.netty.handler.codec.spdy;
17  
18  import io.netty.channel.ChannelHandlerContext;
19  import io.netty.handler.codec.MessageToMessageCodec;
20  import io.netty.handler.codec.http.HttpMessage;
21  import io.netty.util.ReferenceCountUtil;
22  
23  import java.util.LinkedList;
24  import java.util.List;
25  import java.util.Queue;
26  
27  /**
28   * {@link MessageToMessageCodec} that takes care of adding the right {@link SpdyHttpHeaders.Names#STREAM_ID} to the
29   * {@link HttpMessage} if one is not present. This makes it possible to just re-use plan handlers current used
30   * for HTTP.
31   */
32  public class SpdyHttpResponseStreamIdHandler extends
33          MessageToMessageCodec<Object, HttpMessage> {
34      private static final Integer NO_ID = -1;
35      private final Queue<Integer> ids = new LinkedList<Integer>();
36  
37      @Override
38      public boolean acceptInboundMessage(Object msg) throws Exception {
39          return msg instanceof HttpMessage || msg instanceof SpdyRstStreamFrame;
40      }
41  
42      @Override
43      protected void encode(ChannelHandlerContext ctx, HttpMessage msg, List<Object> out) throws Exception {
44          Integer id = ids.poll();
45          if (id != null && id.intValue() != NO_ID && !msg.headers().contains(SpdyHttpHeaders.Names.STREAM_ID)) {
46              SpdyHttpHeaders.setStreamId(msg, id);
47          }
48  
49          out.add(ReferenceCountUtil.retain(msg));
50      }
51  
52      @Override
53      protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
54          if (msg instanceof HttpMessage) {
55              boolean contains = ((HttpMessage) msg).headers().contains(SpdyHttpHeaders.Names.STREAM_ID);
56              if (!contains) {
57                  ids.add(NO_ID);
58              } else {
59                  ids.add(SpdyHttpHeaders.getStreamId((HttpMessage) msg));
60              }
61          } else if (msg instanceof SpdyRstStreamFrame) {
62              ids.remove(((SpdyRstStreamFrame) msg).streamId());
63          }
64  
65          out.add(ReferenceCountUtil.retain(msg));
66      }
67  }