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.embedded.EmbeddedChannel;
19  import io.netty.handler.codec.compression.ZlibCodecFactory;
20  import io.netty.handler.codec.compression.ZlibWrapper;
21  import io.netty.util.internal.StringUtil;
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  
36      /**
37       * Creates a new handler with the default compression level (<tt>6</tt>),
38       * default window size (<tt>15</tt>) and default memory level (<tt>8</tt>).
39       */
40      public HttpContentCompressor() {
41          this(6);
42      }
43  
44      /**
45       * Creates a new handler with the specified compression level, default
46       * window size (<tt>15</tt>) and default memory level (<tt>8</tt>).
47       *
48       * @param compressionLevel
49       *        {@code 1} yields the fastest compression and {@code 9} yields the
50       *        best compression.  {@code 0} means no compression.  The default
51       *        compression level is {@code 6}.
52       */
53      public HttpContentCompressor(int compressionLevel) {
54          this(compressionLevel, 15, 8);
55      }
56  
57      /**
58       * Creates a new handler with the specified compression level, window size,
59       * and memory level..
60       *
61       * @param compressionLevel
62       *        {@code 1} yields the fastest compression and {@code 9} yields the
63       *        best compression.  {@code 0} means no compression.  The default
64       *        compression level is {@code 6}.
65       * @param windowBits
66       *        The base two logarithm of the size of the history buffer.  The
67       *        value should be in the range {@code 9} to {@code 15} inclusive.
68       *        Larger values result in better compression at the expense of
69       *        memory usage.  The default value is {@code 15}.
70       * @param memLevel
71       *        How much memory should be allocated for the internal compression
72       *        state.  {@code 1} uses minimum memory and {@code 9} uses maximum
73       *        memory.  Larger values result in better and faster compression
74       *        at the expense of memory usage.  The default value is {@code 8}
75       */
76      public HttpContentCompressor(int compressionLevel, int windowBits, int memLevel) {
77          if (compressionLevel < 0 || compressionLevel > 9) {
78              throw new IllegalArgumentException(
79                      "compressionLevel: " + compressionLevel +
80                      " (expected: 0-9)");
81          }
82          if (windowBits < 9 || windowBits > 15) {
83              throw new IllegalArgumentException(
84                      "windowBits: " + windowBits + " (expected: 9-15)");
85          }
86          if (memLevel < 1 || memLevel > 9) {
87              throw new IllegalArgumentException(
88                      "memLevel: " + memLevel + " (expected: 1-9)");
89          }
90          this.compressionLevel = compressionLevel;
91          this.windowBits = windowBits;
92          this.memLevel = memLevel;
93      }
94  
95      @Override
96      protected Result beginEncode(HttpResponse headers, CharSequence acceptEncoding) throws Exception {
97          CharSequence contentEncoding = headers.headers().get(HttpHeaderNames.CONTENT_ENCODING);
98          if (contentEncoding != null &&
99              !HttpHeaderValues.IDENTITY.equalsIgnoreCase(contentEncoding)) {
100             return null;
101         }
102 
103         ZlibWrapper wrapper = determineWrapper(acceptEncoding);
104         if (wrapper == null) {
105             return null;
106         }
107 
108         String targetContentEncoding;
109         switch (wrapper) {
110         case GZIP:
111             targetContentEncoding = "gzip";
112             break;
113         case ZLIB:
114             targetContentEncoding = "deflate";
115             break;
116         default:
117             throw new Error();
118         }
119 
120         return new Result(
121                 targetContentEncoding,
122                 new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(
123                         wrapper, compressionLevel, windowBits, memLevel)));
124     }
125 
126     @SuppressWarnings("FloatingPointEquality")
127     protected ZlibWrapper determineWrapper(CharSequence acceptEncoding) {
128         float starQ = -1.0f;
129         float gzipQ = -1.0f;
130         float deflateQ = -1.0f;
131         for (String encoding: StringUtil.split(acceptEncoding.toString(), ',')) {
132             float q = 1.0f;
133             int equalsPos = encoding.indexOf('=');
134             if (equalsPos != -1) {
135                 try {
136                     q = Float.valueOf(encoding.substring(equalsPos + 1));
137                 } catch (NumberFormatException e) {
138                     // Ignore encoding
139                     q = 0.0f;
140                 }
141             }
142             if (encoding.contains("*")) {
143                 starQ = q;
144             } else if (encoding.contains("gzip") && q > gzipQ) {
145                 gzipQ = q;
146             } else if (encoding.contains("deflate") && q > deflateQ) {
147                 deflateQ = q;
148             }
149         }
150         if (gzipQ > 0.0f || deflateQ > 0.0f) {
151             if (gzipQ >= deflateQ) {
152                 return ZlibWrapper.GZIP;
153             } else {
154                 return ZlibWrapper.ZLIB;
155             }
156         }
157         if (starQ > 0.0f) {
158             if (gzipQ == -1.0f) {
159                 return ZlibWrapper.GZIP;
160             }
161             if (deflateQ == -1.0f) {
162                 return ZlibWrapper.ZLIB;
163             }
164         }
165         return null;
166     }
167 }