View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2014 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  
26  /**
27   * Reimplementation of {@link java.util.zip.GZIPOutputStream} that supports reusing a {@link Deflater} instance.
28   */
29  public class GzipOutputStream extends DeflatedOutputStream
30  {
31  
32      private final static byte[] GZIP_HEADER = new byte[]
33      { (byte)0x1f, (byte)0x8b, Deflater.DEFLATED, 0, 0, 0, 0, 0, 0, 0 };
34  
35      private final CRC32 _crc = new CRC32();
36  
37      public GzipOutputStream(OutputStream out, Deflater deflater, byte[] buffer) throws IOException
38      {
39          super(out,deflater,buffer);
40          out.write(GZIP_HEADER);
41      }
42  
43      @Override
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      @Override
51      public synchronized void finish() throws IOException
52      {
53          if (!_def.finished())
54          {
55              super.finish();
56              byte[] trailer = new byte[8];
57              writeInt((int)_crc.getValue(),trailer,0);
58              writeInt(_def.getTotalIn(),trailer,4);
59              out.write(trailer);
60          }
61      }
62  
63      private void writeInt(int i, byte[] buf, int offset)
64      {
65          int o = offset;
66          buf[o++] = (byte)(i & 0xFF);
67          buf[o++] = (byte)((i >>> 8) & 0xFF);
68          buf[o++] = (byte)((i >>> 16) & 0xFF);
69          buf[o++] = (byte)((i >>> 24) & 0xFF);
70      }
71  
72  }