KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > core > filters > GZIPResponseStream


1 /*
2  * Copyright 2003 Jayson Falkner (jayson@jspinsider.com)
3  * This code is from "Servlets and JavaServer pages; the J2EE Web Tier",
4  * http://www.jspbook.com. You may freely use the code both commercially
5  * and non-commercially. If you like the code, please pick up a copy of
6  * the book and help support the authors, development of more free code,
7  * and the JSP/Servlet/J2EE community.
8  */

9 package com.sslexplorer.core.filters;
10
11 import java.io.ByteArrayOutputStream JavaDoc;
12 import java.io.IOException JavaDoc;
13 import java.util.zip.GZIPOutputStream JavaDoc;
14
15 import javax.servlet.ServletOutputStream JavaDoc;
16 import javax.servlet.http.HttpServletResponse JavaDoc;
17
18 public class GZIPResponseStream extends ServletOutputStream JavaDoc {
19   protected ByteArrayOutputStream JavaDoc baos = null;
20   protected GZIPOutputStream JavaDoc gzipstream = null;
21   protected boolean closed = false;
22   protected HttpServletResponse JavaDoc response = null;
23   protected ServletOutputStream JavaDoc output = null;
24
25   public GZIPResponseStream(HttpServletResponse JavaDoc response) throws IOException JavaDoc {
26     super();
27     closed = false;
28     this.response = response;
29     this.output = response.getOutputStream();
30     baos = new ByteArrayOutputStream JavaDoc();
31     gzipstream = new GZIPOutputStream JavaDoc(baos);
32   }
33
34   public void close() throws IOException JavaDoc {
35     if (closed) {
36       throw new IOException JavaDoc("This output stream has already been closed");
37     }
38     gzipstream.finish();
39
40     byte[] bytes = baos.toByteArray();
41
42
43     response.setHeader("Content-Length",
44                        Integer.toString(bytes.length));
45     response.setHeader("Content-Encoding", "gzip");
46     output.write(bytes);
47     output.flush();
48     output.close();
49     closed = true;
50   }
51
52   public void flush() throws IOException JavaDoc {
53     if (closed) {
54       throw new IOException JavaDoc("Cannot flush a closed output stream");
55     }
56     gzipstream.flush();
57   }
58
59   public void write(int b) throws IOException JavaDoc {
60     if (closed) {
61       throw new IOException JavaDoc("Cannot write to a closed output stream");
62     }
63     gzipstream.write((byte)b);
64   }
65
66   public void write(byte b[]) throws IOException JavaDoc {
67     write(b, 0, b.length);
68   }
69
70   public void write(byte b[], int off, int len) throws IOException JavaDoc {
71     if (closed) {
72       throw new IOException JavaDoc("Cannot write to a closed output stream");
73     }
74     gzipstream.write(b, off, len);
75   }
76
77   public boolean closed() {
78     return (this.closed);
79   }
80   
81   public void reset() {
82     //noop
83
}
84 }
85
Popular Tags