01: /* This software is published under the terms of the OpenSymphony Software
02: * License version 1.1, of which a copy has been included with this
03: * distribution in the LICENSE.txt file. */
04: package com.opensymphony.module.sitemesh.filter;
05:
06: import com.opensymphony.module.sitemesh.Page;
07: import com.opensymphony.module.sitemesh.PageParser;
08: import com.opensymphony.module.sitemesh.util.FastByteArrayOutputStream;
09:
10: import javax.servlet.ServletOutputStream;
11: import java.io.CharArrayWriter;
12: import java.io.IOException;
13: import java.io.PrintWriter;
14:
15: /**
16: * When SiteMesh is activated for a request, the contents of the response are stored in this buffer, where they can
17: * later be accessed as a parsed Page object.
18: *
19: * @author Joe Walnes
20: * @version $Revision: 1.3 $
21: */
22: public class Buffer {
23:
24: private final PageParser pageParser;
25: private final String encoding;
26: private final static TextEncoder TEXT_ENCODER = new TextEncoder();
27:
28: private CharArrayWriter bufferedWriter;
29: private FastByteArrayOutputStream bufferedStream;
30: private PrintWriter exposedWriter;
31: private ServletOutputStream exposedStream;
32:
33: public Buffer(PageParser pageParser, String encoding) {
34: this .pageParser = pageParser;
35: this .encoding = encoding;
36: }
37:
38: public char[] getContents() throws IOException {
39: if (bufferedWriter != null) {
40: return bufferedWriter.toCharArray();
41: } else if (bufferedStream != null) {
42: return TEXT_ENCODER.encode(bufferedStream.toByteArray(),
43: encoding);
44: } else {
45: return new char[0];
46: }
47: }
48:
49: public Page parse() throws IOException {
50: return pageParser.parse(getContents());
51: }
52:
53: public PrintWriter getWriter() {
54: if (bufferedWriter == null) {
55: if (bufferedStream != null) {
56: throw new IllegalStateException(
57: "response.getWriter() called after response.getOutputStream()");
58: }
59: bufferedWriter = new CharArrayWriter(128);
60: exposedWriter = new PrintWriter(bufferedWriter);
61: }
62: return exposedWriter;
63: }
64:
65: public ServletOutputStream getOutputStream() {
66: if (bufferedStream == null) {
67: if (bufferedWriter != null) {
68: throw new IllegalStateException(
69: "response.getOutputStream() called after response.getWriter()");
70: }
71: bufferedStream = new FastByteArrayOutputStream();
72: exposedStream = new ServletOutputStream() {
73: public void write(int b) {
74: bufferedStream.write(b);
75: }
76: };
77: }
78: return exposedStream;
79: }
80:
81: public boolean isUsingStream() {
82: return bufferedStream != null;
83: }
84: }
|