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.http;
17  
18  import io.netty.channel.ChannelHandlerContext;
19  import io.netty.channel.embedded.EmbeddedChannel;
20  import io.netty.handler.codec.compression.ZlibCodecFactory;
21  import io.netty.handler.codec.compression.ZlibWrapper;
22  
23  /**
24   * Compresses an {@link HttpMessage} and an {@link HttpContent} in {@code gzip} or
25   * {@code deflate} encoding while respecting the {@code "Accept-Encoding"} header.
26   * If there is no matching encoding, no compression is done.  For more
27   * information on how this handler modifies the message, please refer to
28   * {@link HttpContentEncoder}.
29   */
30  public class HttpContentCompressor extends HttpContentEncoder {
31  
32      private final int compressionLevel;
33      private final int windowBits;
34      private final int memLevel;
35      private ChannelHandlerContext ctx;
36  
37      /**
38       * Creates a new handler with the default compression level (<tt>6</tt>),
39       * default window size (<tt>15</tt>) and default memory level (<tt>8</tt>).
40       */
41      public HttpContentCompressor() {
42          this(6);
43      }
44  
45      /**
46       * Creates a new handler with the specified compression level, default
47       * window size (<tt>15</tt>) and default memory level (<tt>8</tt>).
48       *
49       * @param compressionLevel
50       *        {@code 1} yields the fastest compression and {@code 9} yields the
51       *        best compression.  {@code 0} means no compression.  The default
52       *        compression level is {@code 6}.
53       */
54      public HttpContentCompressor(int compressionLevel) {
55          this(compressionLevel, 15, 8);
56      }
57  
58      /**
59       * Creates a new handler with the specified compression level, window size,
60       * and memory level..
61       *
62       * @param compressionLevel
63       *        {@code 1} yields the fastest compression and {@code 9} yields the
64       *        best compression.  {@code 0} means no compression.  The default
65       *        compression level is {@code 6}.
66       * @param windowBits
67       *        The base two logarithm of the size of the history buffer.  The
68       *        value should be in the range {@code 9} to {@code 15} inclusive.
69       *        Larger values result in better compression at the expense of
70       *        memory usage.  The default value is {@code 15}.
71       * @param memLevel
72       *        How much memory should be allocated for the internal compression
73       *        state.  {@code 1} uses minimum memory and {@code 9} uses maximum
74       *        memory.  Larger values result in better and faster compression
75       *        at the expense of memory usage.  The default value is {@code 8}
76       */
77      public HttpContentCompressor(int compressionLevel, int windowBits, int memLevel) {
78          if (compressionLevel < 0 || compressionLevel > 9) {
79              throw new IllegalArgumentException(
80                      "compressionLevel: " + compressionLevel +
81                      " (expected: 0-9)");
82          }
83          if (windowBits < 9 || windowBits > 15) {
84              throw new IllegalArgumentException(
85                      "windowBits: " + windowBits + " (expected: 9-15)");
86          }
87          if (memLevel < 1 || memLevel > 9) {
88              throw new IllegalArgumentException(
89                      "memLevel: " + memLevel + " (expected: 1-9)");
90          }
91          this.compressionLevel = compressionLevel;
92          this.windowBits = windowBits;
93          this.memLevel = memLevel;
94      }
95  
96      @Override
97      public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
98          this.ctx = ctx;
99      }
100 
101     @Override
102     protected Result beginEncode(HttpResponse headers, String acceptEncoding) throws Exception {
103             String contentEncoding = headers.headers().get(HttpHeaders.Names.CONTENT_ENCODING);
104         if (contentEncoding != null) {
105             // Content-Encoding was set, either as something specific or as the IDENTITY encoding
106             // Therefore, we should NOT encode here
107             return null;
108         }
109 
110         ZlibWrapper wrapper = determineWrapper(acceptEncoding);
111         if (wrapper == null) {
112             return null;
113         }
114 
115         String targetContentEncoding;
116         switch (wrapper) {
117         case GZIP:
118             targetContentEncoding = "gzip";
119             break;
120         case ZLIB:
121             targetContentEncoding = "deflate";
122             break;
123         default:
124             throw new Error();
125         }
126 
127         return new Result(
128                 targetContentEncoding,
129                 new EmbeddedChannel(ctx.channel().metadata().hasDisconnect(),
130                         ctx.channel().config(), ZlibCodecFactory.newZlibEncoder(
131                         wrapper, compressionLevel, windowBits, memLevel)));
132     }
133 
134     @SuppressWarnings("FloatingPointEquality")
135     protected ZlibWrapper determineWrapper(String acceptEncoding) {
136         float starQ = -1.0f;
137         float gzipQ = -1.0f;
138         float deflateQ = -1.0f;
139         for (String encoding : acceptEncoding.split(",")) {
140             float q = 1.0f;
141             int equalsPos = encoding.indexOf('=');
142             if (equalsPos != -1) {
143                 try {
144                     q = Float.parseFloat(encoding.substring(equalsPos + 1));
145                 } catch (NumberFormatException e) {
146                     // Ignore encoding
147                     q = 0.0f;
148                 }
149             }
150             if (encoding.contains("*")) {
151                 starQ = q;
152             } else if (encoding.contains("gzip") && q > gzipQ) {
153                 gzipQ = q;
154             } else if (encoding.contains("deflate") && q > deflateQ) {
155                 deflateQ = q;
156             }
157         }
158         if (gzipQ > 0.0f || deflateQ > 0.0f) {
159             if (gzipQ >= deflateQ) {
160                 return ZlibWrapper.GZIP;
161             } else {
162                 return ZlibWrapper.ZLIB;
163             }
164         }
165         if (starQ > 0.0f) {
166             if (gzipQ == -1.0f) {
167                 return ZlibWrapper.GZIP;
168             }
169             if (deflateQ == -1.0f) {
170                 return ZlibWrapper.ZLIB;
171             }
172         }
173         return null;
174     }
175 }