001: /*
002: * @(#)ResponseWriter.java 1.2 04/12/06
003: *
004: * Copyright (c) 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package pnuts.servlet;
010:
011: import pnuts.lang.*;
012: import java.io.*;
013: import javax.servlet.*;
014:
015: class ResponseWriter extends Writer {
016:
017: private ServletResponse response;
018: private Context context;
019: private Writer writer;
020: private ByteArrayOutputStream bout;
021: private boolean buffering;
022:
023: public ResponseWriter(ServletResponse response, Context context,
024: boolean buffering) {
025: this .response = response;
026: this .context = context;
027: this .buffering = buffering;
028: }
029:
030: private Writer getWriter() throws IOException {
031: Writer w = (Writer) context.get(PnutsServlet.SERVLET_WRITER);
032: if (w == null) {
033: if (buffering) {
034: this .bout = new ByteArrayOutputStream();
035: w = new BufferedWriter(new OutputStreamWriter(
036: this .bout, response.getCharacterEncoding()));
037: } else {
038: w = response.getWriter();
039: }
040: context.set(PnutsServlet.SERVLET_WRITER, w);
041: }
042: return w;
043: }
044:
045: public void write(int c) throws IOException {
046: if (writer == null) {
047: writer = getWriter();
048: }
049: writer.write(c);
050: }
051:
052: public void write(char cbuf[]) throws IOException {
053: if (writer == null) {
054: writer = getWriter();
055: }
056: writer.write(cbuf);
057: }
058:
059: public void write(char cbuf[], int off, int len) throws IOException {
060: if (writer == null) {
061: writer = getWriter();
062: }
063: writer.write(cbuf, off, len);
064: }
065:
066: public void write(String str) throws IOException {
067: if (writer == null) {
068: writer = getWriter();
069: }
070: writer.write(str);
071: }
072:
073: public void write(String str, int off, int len) throws IOException {
074: if (writer == null) {
075: writer = getWriter();
076: }
077: writer.write(str, off, len);
078: }
079:
080: public void flush() throws IOException {
081: if (writer != null) {
082: writer.flush();
083: }
084: }
085:
086: public void close() throws IOException {
087: if (writer != null) {
088: writer.close();
089: }
090: }
091:
092: public void flushBuffer() throws IOException {
093: if (buffering && bout != null) {
094: int size = bout.size();
095: if (size > 0) {
096: response.setContentLength(bout.size());
097: OutputStream out = response.getOutputStream();
098: bout.writeTo(out);
099: bout.reset();
100: }
101: }
102: }
103: }
|