package org.itscool.commons.request;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * Filterからサーブレットに引き渡すダミーのHttpServletResponseインスタンスです
 * @author KANO
 */
public class CustomPageResponseWrapper extends HttpServletResponseWrapper{
    private ByteArrayOutputStream byteStream;
    private ServletOutputStream servStream;
    private PrintWriter prWriter;
    private String localContentType = null;
    
//add 2006/11/28 kano start
    /**
     * ContentTypeをセットします
     * @param contentType コンテントタイプ
     */
    public void setContentType(String contentType){
    	super.setContentType(contentType);
    	this.localContentType = contentType;
//    	System.out.println("CustomPageResponseWrapper" + getContentType());
    }
    
    /**
     * ContentTypeを取得します
     * @return コンテントタイプ
     */
    public String getContentType(){
    	return localContentType;
    }
    
//add 2006/11/28 kano end
    
    public CustomPageResponseWrapper(HttpServletResponse res ) throws IOException{
        super(res);
        
        byteStream = new ByteArrayOutputStream();
        servStream = new MyJspOutputStream(byteStream);
        prWriter = new PrintWriter(byteStream);
    }
    
    //偽のOutputStreamを返すようにしておく
    public ServletOutputStream getOutputStream() throws IOException{
        return servStream;
    }
    
    //偽のOutputWriterを返すようにしておく
    public PrintWriter getWriter() throws IOException{
        return prWriter;
    }
    
    public void flushBuffer() throws IOException{
    }
    /**
     * @return ByteStreamインスタンスを返します
     */
    public ByteArrayOutputStream getByteStream() {
        return byteStream;
    }

}

//本物のServletOutputStreamの変わりにバッファに溜め込んでしまう
//偽のServletOutputStream
class MyJspOutputStream extends ServletOutputStream{
    private ByteArrayOutputStream byteStream;
    
    public MyJspOutputStream(ByteArrayOutputStream byteStream){
        this.byteStream = byteStream;
    }
    
    public void close() throws IOException{
        byteStream.close();
    }
    
    public void flush() throws IOException{
        byteStream.flush();
    }
    
    public void write(byte[] b) throws IOException{
        byteStream.write(b);
    }
    
    public void write(byte[] b, int offset, int len) throws IOException{
        byteStream.write(b, offset, len);
    }
    
    public void write(int b) throws IOException{
        byteStream.write(b);
    }
    /**
     * @return
     */
    public ByteArrayOutputStream getByteStream() {
        return byteStream;
    }

    /**
     * @param stream
     */
    public void setByteStream(ByteArrayOutputStream stream) {
        byteStream = stream;
    }

}
