package moreservlets.listeners;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Listener that looks up the name of the company when
 *  the Web application is first loaded. Stores this
 *  name in the companyName servlet context attribute.
 *  Various servlets and JSP pages will extract it
 *  from that location.
 *  <P>
 *  Also looks up and stores the former company name and
 *  stores it in the formerCompanyName attribute.
 *  <P>
 *  Taken from More Servlets and JavaServer Pages
 *  from Prentice Hall and Sun Microsystems Press,
 *  http://www.moreservlets.com/.
 *  &copy; 2002 Marty Hall; may be freely used or adapted.
 */

public class InitialCompanyNameListener
    implements ServletContextListener {
  private static final String DEFAULT_NAME =
    "MISSING-COMPANY-NAME";

  /** Looks up the companyName and formerCompanyName
   *  init parameters and puts them into the servlet context.
   */
  
  public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    setInitialAttribute(context,
                        "companyName",
                        DEFAULT_NAME);
    setInitialAttribute(context,
                        "formerCompanyName",
                        "");
  }

  public void contextDestroyed(ServletContextEvent event) {}

  // Looks for a servlet context init parameter with a
  // given name. If it finds it, it puts the value into
  // a servlet context attribute with the same name. If
  // the init parameter is missing, it puts a default
  // value into the servlet context attribute.
  
  private void setInitialAttribute(ServletContext context,
                                   String initParamName,
                                   String defaultValue) {
    String initialValue =
      context.getInitParameter(initParamName);
    if (initialValue != null) {
      context.setAttribute(initParamName, initialValue);
    } else {
      context.setAttribute(initParamName, defaultValue);
    }
  }

  /** Static method that returns the servlet context
   *  attribute named "companyName" if it is available.
   *  Returns a default value if the attribute is
   *  unavailable.
   */
  
  public static String getCompanyName(ServletContext context) {
    String name =
      (String)context.getAttribute("companyName");
    if (name == null) {
      name = DEFAULT_NAME;
    }
    return(name);
  }

  /** Static method that returns the servlet context
   *  attribute named "formerCompanyName" if it is available.
   *  Returns an empty string if the attribute is
   *  unavailable.
   */

  public static String getFormerCompanyName
                                     (ServletContext context) {
    String name =
      (String)context.getAttribute("formerCompanyName");
    if (name == null) {
      name = "";
    }
    return(name);
  }
}
