package com.dpd.general.tapestry;

import com.dpd.general.services.Service;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.FileInputStream;
import java.util.Iterator;

/**
 *  @version $Id$
 *  @author
 *
 **/

public class ApplicationServlet extends net.sf.tapestry.ApplicationServlet
{
    protected String realApplicationPath = null;
    Log logger = LogFactory.getLog(this.getClass());

    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
        setApplicationPath(config);
        initServices(config);
    }

    /**
     * sets the real groupware path variable
     * @param config
     * @throws ServletException
     */
    protected void setApplicationPath(ServletConfig config) throws ServletException
    {
        realApplicationPath = config.getServletContext().getRealPath("/");
    }

    /**
     * gets the real groupware path
     * @return realApplicationPath
     */
    protected String getApplicationPath()
    {
        return realApplicationPath;
    }

    /**
     * initialze the external configrued services<br>
     * @param config
     * @throws ServletException
     */
    protected void initServices(ServletConfig config) throws ServletException
    {
        FileInputStream input = null;
        String parameter = config.getInitParameter("properties");
        if (parameter == null)
            throw new ServletException("there was no properties-file set in web.xml");

        String propertiesFile = getApplicationPath() + "/" + parameter;

        PropertiesConfiguration conf = new PropertiesConfiguration();
        try
        {
            input = new FileInputStream(propertiesFile);
            conf.load(input);
            Iterator iter = conf.subset("services.classname").getKeys();
            while (iter.hasNext())
            {
                String className = conf.getString("services.classname." + (String) iter.next());
                Service service = (Service) Class.forName(className).newInstance();
                logger.info("initialize service " + className);
                service.init(conf);
            }
        }
        catch (Exception e)
        {
            throw new ServletException(e);
        }
    }

    /**
     * do nothing, we have our own logging mechanism
     * @throws ServletException
     */
    protected void setupLogging() throws ServletException
    {
    }
}
