package jp.cssj.cti.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * 転送先の内容をキャプチャーしてCSSJに送るためのリクエスト・ラッパーです。
 * 
 * @author <a href="mailto:miyabe at gnn.co.jp">MIYABE Tatsuhiko </a>
 * @version $Id: CSSJHttpServletResponseWrapper.java,v 1.1 2005/02/25 04:13:50
 *          harumanx Exp $
 */
public class CSSJHttpServletResponseWrapper extends HttpServletResponseWrapper {
	private final OutputStream out;

	private final String encoding;

	private ServletOutputStream servletOut = null;

	private PrintWriter writer = null;

	public class CSSJServletOutputStream extends ServletOutputStream {
		public CSSJServletOutputStream() {
		}

		public void write(int b) throws IOException {
			CSSJHttpServletResponseWrapper.this.out.write(b);
		}

		public void write(byte[] b) throws IOException {
			CSSJHttpServletResponseWrapper.this.out.write(b);
		}

		public void write(byte[] b, int off, int len) throws IOException {
			CSSJHttpServletResponseWrapper.this.out.write(b, off, len);
		}
	};

	public CSSJHttpServletResponseWrapper(HttpServletResponse response,
			OutputStream out, String encoding) {
		super(response);
		this.out = out;
		this.encoding = encoding;
	}

	public void setContentLength(int contentLength) {
		// ignore
	}

	public void setContentType(String contentType) {
		// ignore
	}

	public void setCharacterEncoding(String encoding) {
		// ignore
	}

	public ServletOutputStream getOutputStream() {
		if (this.servletOut == null) {
			this.servletOut = new CSSJServletOutputStream();
		}
		return this.servletOut;
	}

	public PrintWriter getWriter() throws IOException {
		if (this.writer == null) {
			this.writer = new PrintWriter(new OutputStreamWriter(this
					.getOutputStream(), this.encoding));
		}
		return this.writer;
	}

	public void flushBuffer() throws IOException {
		if (this.writer != null) {
			this.writer.flush();
		} else if (this.servletOut != null) {
			this.servletOut.flush();
		}
	}

	public void close() throws IOException {
		try {
			if (this.writer != null) {
				this.writer.close();
			} else if (this.servletOut != null) {
				this.servletOut.flush();
			}
		} finally {
			this.out.close();
		}
	}
}