package org.maachang.util;

import java.io.IOException;
import java.io.OutputStream;

/**
 * DebugOutputStream.
 * 
 * @version 2007/10/18
 * @author masahito suzuki
 * @since MaachangDao 1.00
 */
public class DebugOutputStream extends OutputStream {

    /**
     * 出力キャラクタセット.
     */
    private static final String CHARSET = "UTF8";

    /**
     * 出力オブジェクト.
     */
    private OutputStream outputStream = null;

    /**
     * コンストラクタ.
     */
    private DebugOutputStream() {

    }

    /**
     * コンストラクタ. <BR>
     * <BR>
     * 条件を設定してオブジェクトを生成します. <BR>
     * 
     * @param outputStream
     *            出力対象オブジェクトを設定します.
     * @exception Exception
     *                例外.
     */
    public DebugOutputStream(OutputStream outputStream) throws Exception {
        if (outputStream == null) {
            throw new IllegalArgumentException("引数は不正です");
        }
        this.outputStream = outputStream;
    }

    /**
     * デストラクタ.
     */
    protected void finalize() throws Exception {
        this.close();
    }

    public void close() throws IOException {
        this.flush();
        outputStream.close();
    }

    public void flush() throws IOException {
        outputStream.flush();
    }

    public void write(int b) throws IOException {
        System.out.println("###[stream]:"
                + new String(new byte[] { (byte) b }, CHARSET));
        outputStream.write(b);
    }

    public void write(byte b[]) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        }
        write(b, 0, b.length);
    }

    public void write(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if ((off < 0) || (off > b.length) || (len < 0)
                || ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        System.out.println("###[stream]:" + new String(b, off, len, CHARSET));
        outputStream.write(b, off, len);
    }
}
