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      @Override
45      public synchronized void write(byte[] buf, int off, int len) throws IOException
46      {
47          super.write(buf,off,len);
48          _crc.update(buf,off,len);
49      }
50  
51      @Override
52      public synchronized void finish() throws IOException
53      {
54          if (!def.finished())
55          {
56              super.finish();
57              byte[] trailer = new byte[8];
58              writeInt((int)_crc.getValue(),trailer,0);
59              writeInt(def.getTotalIn(),trailer,4);
60              out.write(trailer);
61          }
62      }
63      
64      @Override 
65      public synchronized void close() throws IOException
66      {
67          super.close();
68      }
69      
70      
71  
72      private void writeInt(int i, byte[] buf, int offset)
73      {
74          int o = offset;
75          buf[o++] = (byte)(i & 0xFF);
76          buf[o++] = (byte)((i >>> 8) & 0xFF);
77          buf[o++] = (byte)((i >>> 16) & 0xFF);
78          buf[o++] = (byte)((i >>> 24) & 0xFF);
79      }
80  
81  }