KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > net > filter > GZIPResponseWrapper


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 org.snipsnap.net.filter;
10
11 import javax.servlet.ServletOutputStream JavaDoc;
12 import javax.servlet.http.HttpServletResponse JavaDoc;
13 import javax.servlet.http.HttpServletResponseWrapper JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.io.OutputStreamWriter JavaDoc;
16 import java.io.PrintWriter JavaDoc;
17
18 public class GZIPResponseWrapper extends HttpServletResponseWrapper JavaDoc {
19   protected HttpServletResponse JavaDoc origResponse = null;
20   protected ServletOutputStream JavaDoc stream = null;
21   protected PrintWriter JavaDoc writer = null;
22
23   public GZIPResponseWrapper(HttpServletResponse JavaDoc response) {
24     super(response);
25     origResponse = response;
26   }
27
28   public ServletOutputStream JavaDoc createOutputStream() throws IOException JavaDoc {
29     return (new GZIPResponseStream(origResponse));
30   }
31
32   public void finishResponse() {
33     try {
34       if (writer != null) {
35         writer.flush();
36         writer.close();
37       } else {
38         if (stream != null) {
39           stream.flush();
40           stream.close();
41         }
42       }
43     } catch (IOException JavaDoc e) {
44     }
45   }
46
47   public void flushBuffer() throws IOException JavaDoc {
48     if (writer != null) {
49       writer.flush();
50     } else {
51       if (stream != null) {
52         stream.flush();
53       }
54     }
55   }
56
57   public ServletOutputStream JavaDoc getOutputStream() throws IOException JavaDoc {
58     if (writer != null) {
59       throw new IllegalStateException JavaDoc("getWriter() has already been called!");
60     }
61
62     if (stream == null) {
63       stream = createOutputStream();
64     }
65     return (stream);
66   }
67
68   public PrintWriter JavaDoc getWriter() throws IOException JavaDoc {
69     if (writer != null) {
70       return (writer);
71     }
72
73     if (stream != null) {
74       throw new IllegalStateException JavaDoc("getOutputStream() has already been called!");
75     }
76
77     stream = createOutputStream();
78     writer = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(stream, "UTF-8"));
79     return (writer);
80   }
81
82   public void setContentLength(int length) {
83   }
84
85   public void setContentType(String JavaDoc s) {
86     origResponse.setContentType(s);
87   }
88 }
89
Popular Tags