//
// $Id$
//

package res.test;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.*;
import javax.servlet.http.*;

import res.log.Logger;
import res.log.FileLogDevice;


/**
 * <p>A servlet that provides an HTTP-based messaging service.</p>
 *
 * @version $Revision$, $Date$
 * @author Richard E. Sansom
 */
public class TestServlet
    extends HttpServlet
{

    //-------------------------------------------------------- public constants
    
    public static final String CRLF = "\r\n";
    
    public static final String DEFAULT_LOG_FILENAME = "log.txt";
    public static final String DEFAULT_ERROR_LOG_FILENAME = "error.txt";
    
    public static final String PARAM_LOG_FILENAME = "logFilename";
    public static final String PARAM_ERROR_LOG_FILENAME = "errorLogFilename";
    
    public static final String PREAMBLE = "<res>";
    public static final String POSTAMBLE = "</res>";
    

    //------------------------------------------------------- private constants

    private static final String INFO_NAME = "HttpMessageServlet";
    private static final String INFO_DESC = "HTTP Message Service";
    private static final String INFO_VERSION = "$Revision$";
    private static final String INFO_COPY = "Copyright (c) 2000 RES, " +
                                            "All Rights Reserved";

    //--------------------------------------------------- private member fields

    private boolean destroyed = false;
    private ServletConfig myConfig = null;
    private Logger myLogger = null;
    private FileLogDevice logFileDevice = null;
    private FileLogDevice errorLogFileDevice = null;


    //---------------------------------------------------------- public methods

    /**
     * <p>Called when the servlet is destroyed.</p>
     */
    public void destroy() {
        destroyed = true;
        myConfig = null;
        myLogger = null;
        logFileDevice = null;
        errorLogFileDevice = null;
    }

    /**
     * <p>Returns servlet info blurb.</p>
     *
     * @return <code>String</code>
     */
    public String getServletInfo() {
        return(INFO_NAME + ": " + INFO_DESC + " - Version: " + 
               INFO_VERSION + " (" + INFO_COPY + ")");
    }

    /**
     * <p>Initializes the servlet.</p>
     *
     * @param config <code>ServletConfig</code>
     * @exception <code>ServletException</code>
     */
    public void init(
        ServletConfig config
    ) throws ServletException {

        super.init(config);

        myConfig = config;
        destroyed = false;

        String lfn = myConfig.getInitParameter(PARAM_LOG_FILENAME);
        if (lfn == null) {
            lfn = DEFAULT_LOG_FILENAME;
        }

        String elfn = myConfig.getInitParameter(PARAM_ERROR_LOG_FILENAME);
        if (elfn == null) {
            elfn = DEFAULT_ERROR_LOG_FILENAME;
        }

        try {
            logFileDevice = new FileLogDevice(lfn);
            errorLogFileDevice = new FileLogDevice(elfn);
            myLogger = new Logger(logFileDevice, errorLogFileDevice);
            myLogger.setTimestampFlag(true);
        } catch (Exception e) {
            System.err.println("init: exception: " + e);
            e.printStackTrace();
            throw new ServletException("Fatal: cannot create logger");
        }
    }

    /**
     * <p>Handles an individual POST request.</p>
     *
     * @param request <code>HttpServletRequest</code>
     * @param response <code>HttpServletResponse</code>
     * @exception ServletException
     */
    public void doPost(
        HttpServletRequest request,
        HttpServletResponse response
    ) throws ServletException {

        try {
            //
            // get or create the session for this request
            //
            //HttpSession session = request.getSession(true);
            //if (session.isNew()) {
            //    session.putValue("created", new Date().toString());
            //    myLogger.log("new session");
            //} else {
            //    session.putValue("updated", new Date().toString());
            //}

            //
            // process the request and get our reply
            //
            String reply = processRequest(request, response);
            if (reply != null) {
                sendReply(response, reply);
            }

            //
            // we may want to do some additional object
            // management on the serviceResponse here at some point...
            //
            
        } catch (Exception e) {
            myLogger.error("service: exception: " + e);
        }

    }

    //----------------------------------------------------- private methods

    //
    // This method reads an individual request and extracts the incoming
    // message.  It then builds and returns the reply message.
    //
    private String processRequest(
        HttpServletRequest request, 
        HttpServletResponse response
    ) throws Exception {
        BufferedInputStream bis = new BufferedInputStream(
            request.getInputStream()
        );
        int i = 0;
        int n = 0;
        int contentLength = request.getContentLength();
        byte[] buffer = new byte[contentLength];
        for (n = 0; (n < contentLength) && ((i = bis.read()) >= 0) ; n++) {
            buffer[n] = (byte) i;
        }
        bis.close();
        return new String(buffer);
    }
    
    //
    // This method sends our reply message and sends it back to the
    // requesting client.
    //
    private void sendReply(
        HttpServletResponse response,
        String reply
    ) {
        try {
            StringBuffer sb = new StringBuffer(PREAMBLE);
            sb.append(CRLF);
            sb.append(reply);
            sb.append(CRLF);
            sb.append(POSTAMBLE);
            sb.append(CRLF);
            response.setContentLength(sb.length());
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.print(sb.toString());
            out.flush();
        } catch (IOException e) {
            myLogger.error("sendResponseMessage: exception: " + e);
        }
    }

}

//
// $Log$
//
