1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.talika.tarsis.filters.gzip;
24
25 import javax.servlet.ServletOutputStream;
26 import java.util.zip.GZIPOutputStream;
27 import java.io.BufferedOutputStream;
28 import java.io.OutputStream;
29 import java.io.IOException;
30
31 /**
32 * <code>ServletOutputStream</code> wrapper that allows us to compress response.
33 *
34 * @author Jose M. Palomar
35 * @version $Revision: 122 $
36 */
37 public final class GZIPServletOutputStream extends ServletOutputStream {
38
39
40 /**
41 * Wrapped <code>ServletOutputStream</code>.
42 */
43 private OutputStream out;
44
45
46 /**
47 * Creates an output stream adaptor wrapping the given output stream.
48 *
49 * @param out ServletOutputStream output stream to be wrapped.
50 * @throws IOException if an input or output exception occurs.
51 */
52 public GZIPServletOutputStream(ServletOutputStream out) throws IOException {
53 this(out, -1);
54 }
55
56 /**
57 * Creates an output stream adaptor wrapping the given output stream and buffer
58 * size.
59 *
60 * @param out ServletOutputStream output stream to be wrapped.
61 * @param size int buffer size.
62 * @throws IOException if an input or output exception occurs.
63 */
64 public GZIPServletOutputStream(ServletOutputStream out, int size) throws IOException {
65
66 if (size > 0) {
67 this.out = new BufferedOutputStream(new GZIPOutputStream(out));
68 }
69 else {
70 this.out = new BufferedOutputStream(new GZIPOutputStream(out), size);
71 }
72
73 }
74
75 /**
76 * Writes <code>len</code> bytes from the specified byte array starting at offset
77 * <code>off</code> to this output stream.
78 *
79 * @param data byte[] the data.
80 * @param off int the start offset in the data.
81 * @param len int the number of bytes to write.
82 * @throws IOException if an input or output exception occurs.
83 */
84 public void write(byte[] data, int off, int len) throws IOException {
85 out.write(data, off, len);
86 }
87
88 /**
89 * Writes the specified byte to this output stream.
90 *
91 * @param data int the byte.
92 * @throws IOException if an input or output exception occurs.
93 */
94 public void write(int data) throws IOException {
95 out.write(data);
96 }
97
98 /**
99 * Closes this output stream and releases any system resources associated with
100 * this stream.
101 *
102 * @throws IOException if an input or output exception occurs.
103 */
104 public void close() throws IOException {
105 out.flush();
106 out.close();
107 }
108
109 /**
110 * Flushes this output stream and forces any buffered output bytes to be written
111 * out.
112 *
113 * @throws IOException if an input or output exception occurs.
114 */
115 public void flush() throws IOException {
116 out.flush();
117 }
118
119 }