View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.servlets.gzip;
20  
21  import java.io.IOException;
22  import java.io.OutputStream;
23  import java.util.zip.CRC32;
24  import java.util.zip.Deflater;
25  import java.util.zip.DeflaterOutputStream;
26  
27  /**
28   * Reimplementation of {@link java.util.zip.GZIPOutputStream} that supports reusing a {@link Deflater} instance.
29   */
30  public class GzipOutputStream extends DeflaterOutputStream
31  {
32  
33      private final static byte[] GZIP_HEADER = new byte[]
34      { (byte)0x1f, (byte)0x8b, Deflater.DEFLATED, 0, 0, 0, 0, 0, 0, 0 };
35  
36      private final CRC32 _crc = new CRC32();
37  
38      public GzipOutputStream(OutputStream out, Deflater deflater, int size) throws IOException
39      {
40          super(out,deflater,size);
41          out.write(GZIP_HEADER);
42      }
43  
44      public synchronized void write(byte[] buf, int off, int len) throws IOException
45      {
46          super.write(buf,off,len);
47          _crc.update(buf,off,len);
48      }
49  
50      public void finish() throws IOException
51      {
52          if (!def.finished())
53          {
54              super.finish();
55              byte[] trailer = new byte[8];
56              writeInt((int)_crc.getValue(),trailer,0);
57              writeInt(def.getTotalIn(),trailer,4);
58              out.write(trailer);
59          }
60      }
61  
62      private void writeInt(int i, byte[] buf, int offset)
63      {
64          int o = offset;
65          buf[o++] = (byte)(i & 0xFF);
66          buf[o++] = (byte)((i >>> 8) & 0xFF);
67          buf[o++] = (byte)((i >>> 16) & 0xFF);
68          buf[o++] = (byte)((i >>> 24) & 0xFF);
69      }
70  
71  }