1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
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 }