// JigsawServletOutputStream.java
// $Id: JigsawServletOutputStream.java,v 1.9 1999/04/12 09:58:18 ylafon Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package org.w3c.jigsaw.servlet;

import java.io.*;

import javax.servlet.*;

import org.w3c.jigsaw.http.Reply;

/**
 * This is certainly not a good implementation, it's enough though.
 * (more buffering, better buffering, although the Client output stream
 * will usually come with its own buffering.
 *  @author Alexandre Rafalovitch <alex@access.com.au>
 *  @author Anselm Baird-Smith <abaird@w3.org>
 *  @author Benoît Mahé <bmahe@w3.org>
 */

class JigsawServletOutputStream extends ServletOutputStream {
    DataOutputStream          out   = null;
    JigsawHttpServletResponse resp  = null;
    Reply                     reply = null;

    /**
     * Check that the stream is open, if not open it and send 
     * the headers.
     */
    private void check() 
	throws IOException
    {
	if (out == null) {
	    if (reply != null)
		out = new DataOutputStream(reply.getOutputStream());
	}
    }

    public void print(int i)
	throws IOException
    {
	check();
	out.writeBytes(Integer.toString(i));
    }

    public void print(double i)
	throws IOException
    {
	check();
	out.writeBytes(Double.toString(i));
    }

    public void print(long l)
	throws IOException
    {
	check();
	out.writeBytes(Long.toString(l));
    }

    public void print(String s) 
	throws IOException 
    {
	check();
	out.writeBytes(s);
    }

    public void println() 
	throws IOException
    {
	check();
	out.writeBytes("\r\n");
    }

    public void println(int i)
	throws IOException
    {
	print(i); println();
    }

    public void println(double i)
	throws IOException
    {
	print(i); println();
    }

    public void println(long l) 
	throws IOException
    {
	print(l); println();
    }

    public void println(String s)
	throws IOException
    {
	print(s); println();
    }

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

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

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

    public void flush() 
	throws IOException 
    {
	check();
	out.flush();
    }

    public void close() 
	throws IOException 
    {
	check();
	out.close();
    }

    JigsawServletOutputStream(JigsawHttpServletResponse resp,
			      DataOutputStream out) 
    {
	this.out  = out;
	this.resp = resp;
    }

    JigsawServletOutputStream(JigsawHttpServletResponse resp, Reply reply) {
	this.resp = resp;
	this.reply = reply;
    }

}

