/*******************************************************************************
 * Copyright (c), 2001, 2002 N2 Broadband, Inc.  All Rights Reserved.
 *
 * This module contains unpublished, confidential, proprietary
 * material.  The use and dissemination of this material are
 * governed by a license.  The above copyright notice does not
 * evidence any actual or intended publication of this material.
 *
 * Author:  Drake H. Henderson, kmatsuoka
 * Created:  11-12-01
 *
 ******************************************************************************/

package com.n2bb.plugins;

import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletException;

import com.n2bb.util.N2bbSettings;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

/**
 * Loads a properties file into an application-scoped properties object.
 */
public final class PropertiesPlugIn implements PlugIn {

    private Log n2bbLog = LogFactory.getLog(N2bbSettings.N2BB_LOG);

    private ActionServlet servlet = null;

    private String pathname = "";
    private String key = "";

    /**
     * Sets the path to the properties file.
     *
     * @param pathname path to the properties file
     */

    public void setPathname(String pathname) {
        this.pathname = pathname;
    }

    /**
     * Sets the key used to store the application-scoped properties object.
     *
     * @param key key for the application-scoped properties object
     */
    public void setKey(String key) {
        this.key = key;
    }

    public void init(ActionServlet servlet, ModuleConfig config) throws ServletException {

        if (key.equals("")) {
            n2bbLog.error("No key specified for properties file '" + pathname + "'");
            return;
        }

        this.servlet = servlet;

        Properties props = new Properties();
        InputStream is = servlet.getServletContext().getResourceAsStream(pathname);

        if (is == null) {
            n2bbLog.error("Properties file '" + pathname + "' not found");
        }
        else {
            try {
                props.load(is);
            }
            catch (Exception e) {
                n2bbLog.error("Error loading properties from file '" + pathname + "'", e);
            }
        }

        servlet.getServletContext().setAttribute(key, props);
    }

    public void destroy() {
        servlet.getServletContext().removeAttribute(key);
    }

}

