/*
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, either express or implied. See the License for the specific
 * language governing rights and limitations under the License.
 * 
 * The Original Code is the Venice Web Communities System.
 * 
 * The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
 * for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
 * Copyright (C) 2002-03 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.dynamo.servlet;

import java.io.*;
import java.util.Locale;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * A dummy <CODE>HttpServletResponse</CODE> which is used to generate the proper response to the HEAD HTTP
 * method.  The {@link com.silverwrist.dynamo.servlet.ServletBase ServletBase} servlet wraps the
 * <CODE>HttpServletResponse</CODE> passed to it in one of these objects, and changes the method to GET,
 * allowing HEAD to return the correct Content-Length header no matter whether or not it was explicitly set.
 *
 * @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
 * @version X
 */
class NullResponse extends HttpServletResponseWrapper
{
  /*--------------------------------------------------------------------------------
   * Internal class implementing the output stream
   *--------------------------------------------------------------------------------
   */

  private static class NullStream extends ServletOutputStream
  {
    /*====================================================================
     * Attributes
     *====================================================================
     */

    private int m_length = 0;  // the length of the output data

    /*====================================================================
     * Constructor
     *====================================================================
     */

    NullStream()
    { // do nothing
    } // end constructor

    /*====================================================================
     * Overrides from class ServletOutputStream
     *====================================================================
     */

    public void write(int b)
    {
      m_length++;

    } // end write

    public void write(byte buf[], int offset, int len) throws IOException
    {
      if (len>=0)
	m_length += len;
      else
	throw new IOException("NullStream: negative length");

    } // end write

    /*====================================================================
     * External operations
     *====================================================================
     */

    int getOutputLength()
    {
      return m_length;

    } // end getOutputLength

  } // end class NullStream

  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private NullStream m_stm;               // stream that dumps its output
  private PrintWriter m_wr = null;        // PrintWriter that goes through stream
  private boolean m_binary = false;       // binary mode flag
  private boolean m_length_set = false;   // has the length been set?

  /*--------------------------------------------------------------------------------
   * Constructor
   *--------------------------------------------------------------------------------
   */

  /**
   * Creates a new instance of this object.
   *
   * @param inner The <CODE>HttpServletResponse</CODE> to be wrapped by this object.
   */
  public NullResponse(HttpServletResponse inner)
  {
    super(inner);
    m_stm = new NullStream();

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Overrides from class HttpServletResponseWrapper
   *--------------------------------------------------------------------------------
   */

  /**
   * Returns a <CODE>ServletOutputStream</CODE> suitable for writing binary data in the response. The
   * servlet container does not encode the binary data.  
   * <p>Calling <CODE>flush()</CODE> on the <CODE>ServletOutputStream</CODE> commits the response.
   * Either this method or {@link #getWriter() getWriter()} may  be called to write the body, not both.
   *
   * @return a <CODE>ServletOutputStream</CODE> for writing binary data	
   * @exception java.lang.IllegalStateException if the <code>getWriter</code> method has been
   *            called on this response
   * @exception java.io.IOException if an input or output exception occurred
   * @see #getWriter
   */
  public synchronized ServletOutputStream getOutputStream() throws IOException
  {
    if (m_wr!=null)
      throw new IllegalStateException("NullResponse: text mode already selected");
    m_binary = true;
    return m_stm;

  } // end getOutputStream

  /**
   * Returns a <code>PrintWriter</code> object that  can send character text to the client. 
   * The character encoding used is the one specified in the <code>charset=</code> property
   * of the <CODE>setContentType</CODE> method, which must be called <i>before</i> calling this
   * method for the charset to take effect. 
   * <p>If necessary, the MIME type of the response is modified to reflect the character
   * encoding used.
   * <p>Calling flush() on the PrintWriter commits the response.
   * <p>Either this method or {@link #getOutputStream() getOutputStream} may be called to write the body, not
   * both.
   * 
   * @return a <code>PrintWriter</code> object that can return character data to the client
   * @exception java.lang.UnsupportedEncodingException if the charset specified in
   *            <code>setContentType</code> cannot be used
   * @exception java.lang.IllegalStateException if the <code>getOutputStream</code> method
   *            has already been called for this response object
   * @exception java.io.IOException if an input or output exception occurred
   *
   * @see #getOutputStream
   */
  public synchronized PrintWriter getWriter() throws UnsupportedEncodingException
  {
    if (m_binary)
      throw new IllegalStateException("NullResponse: binary mode already selected");
    if (m_wr==null)
    { // create the PrintWriter we need to fake the output
      OutputStreamWriter wr = new OutputStreamWriter(m_stm,super.getCharacterEncoding());
      m_wr = new PrintWriter(wr);

    } // end if

    return m_wr;

  } // end getWriter

  /**
   * Sets the length of the content body in the response.  In HTTP servlets, this method sets
   * the HTTP Content-Length header.
   *
   * @param len an integer specifying the length of the content being returned to the client;
   *            sets the Content-Length header
   */
  public void setContentLength(int len)
  {
    if (!m_length_set)
    { // pass through to inner class if not already set
      super.setContentLength(len);
      m_length_set = true;

    } // end if

  } // end setContentLength

  /*--------------------------------------------------------------------------------
   * External operations
   *--------------------------------------------------------------------------------
   */

  /**
   * Causes the proper content length to be set on the encapsulated <CODE>HttpServletResponse</CODE>.
   */
  public void fixupContentLength()
  {
    if (!m_length_set)
    { // pass through to inner class if not already set
      super.setContentLength(m_stm.getOutputLength());
      m_length_set = true;

    } // end if

  } // end fixupContentLength

} // end class NullResponse
