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