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