package com.infogain.DOG.logging.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.log4j.*;
import com.infogain.DOG.logging.*;

public class Log4jServlet extends HttpServlet {

   static Category c = null; 
  
  	public void init(ServletConfig config) throws ServletException {
     	super.init(config);
    
     	ServletContext context = config.getServletContext();

		log("#$#$ Context is " + context);

		String baseCategory = config.getInitParameter( Keys.BASE_CATEGORY );
		String basePriority = config.getInitParameter( Keys.BASE_PRIORITY );
      String initConfig = config.getInitParameter( Keys.WLPI_LOG4J_CONF );

      log( "WLPI_LOG4J_CONF = " + initConfig );

      if( initConfig == null )
         throw new ServletException( "Need an init-config provided by parameter " + Keys.WLPI_LOG4J_CONF );
      
      Properties props = new Properties();
      try {
			log("getting log4j properties file");
			InputStream is = context.getResourceAsStream(initConfig);
         log("got log4j properties file");
			props.load(is);
			log("loaded config file into properties object");
         is.close();

		/******
         // manipulate what needs to be manipulated :-)
			props.setProperty("log4j.appender.stdlog.File",
			getServletContext().getRealPath(messages.getMessage("Log.Qwickrate")) );
			props.setProperty("log4j.appender.ddrlog.File",
			getServletContext().getRealPath(messages.getMessage("Log.DDR"))  );
		*******/
            
			// configure the logging device
      	PropertyConfigurator.configure(props);

			if (baseCategory != null && basePriority != null) {
   			c = Category.getInstance(baseCategory);
				if (basePriority.equalsIgnoreCase("debug") ) 
   				c.setPriority(Priority.DEBUG);
				else if (basePriority.equalsIgnoreCase("info") ) 
   				c.setPriority(Priority.INFO);			
				else if (basePriority.equalsIgnoreCase("warn") ) 
   				c.setPriority(Priority.WARN);	
				else if (basePriority.equalsIgnoreCase("error") ) 
   				c.setPriority(Priority.ERROR);	
				else if (basePriority.equalsIgnoreCase("fatal") ) 
   				c.setPriority(Priority.FATAL);	
				else 
					c.setPriority(Priority.DEBUG);
			
				if(c.isDebugEnabled())  
					c.debug("Log4jServlet inited to priority: " + c.getPriority() );	
			}
      } catch (IOException io) {
          System.out.println(io.getMessage());
      }
  	}
  



  /**
   * A very simple implementation of the service method, in
   * which we output the contents of a static html page
   */
  	public void service(HttpServletRequest req, HttpServletResponse res)
       throws IOException {
    	// Must set the content type first
    	res.setContentType("text/html");
    	// Now we can obtain a PrintWriter
    	PrintWriter out = res.getWriter();
    
    	out.println("<html><head><title>Log4j Servlet</title></head>");
    	out.println("<body><h1>The Log4j Servlet is up and running</h1></body></html>");
  }
}
