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