package com.perforce.listeners;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import org.apache.log4j.Logger;
import com.perforce.ApplicationException;
import com.perforce.Constants;
import com.perforce.P4Helper;
import com.perforce.ServletContextHolder;
/**
* Application Lifecycle Listener implementation class P4SelfServiceListener
*
*/
public class P4SelfServiceListener implements ServletContextListener {
static Logger logger = Logger.getLogger(P4SelfServiceListener.class.getName());
/**
* Default constructor.
*/
public P4SelfServiceListener() {
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent evt) {
logger.debug("### APPLICATION INITIALIZED");
try {
ServletContext context = evt.getServletContext();
ServletContextHolder.getInstance().setServletContext(context);
context.setAttribute(Constants.CONFIGURED, false);
String configFilePath = System.getProperty(Constants.CONFIGURATION_FILE_SYSTEM_PROPERTY);
if(configFilePath == null) {
configFilePath = Constants.CONFIGURATION_FILE_DEFAULT;
}
// remove file: specifier from beginning of path, if it exists
if (configFilePath.startsWith("file:")) {
configFilePath = configFilePath.substring(5);
}
Properties props = new Properties();
File configFile = new File(configFilePath);
if(!configFile.exists()) {
throw new RuntimeException("configuration file does not exist: " + configFilePath);
}
if(!configFile.canRead()) {
throw new RuntimeException("configuration file is not readable: " + configFilePath);
}
props.load(new FileInputStream(configFile));
Enumeration<?> enumeration = props.propertyNames();
while(enumeration.hasMoreElements()) {
String key = (String)enumeration.nextElement();
context.setAttribute(key, props.getProperty(key));
}
logger.debug("LOADED CONFIGURATION");
context.setAttribute(Constants.CONFIGURED, true);
P4Helper helper = new P4Helper();
helper.configServer();
Properties appSettings = helper.getApplicationSettings();
if(appSettings.size() > 0) {
enumeration = appSettings.propertyNames();
while(enumeration.hasMoreElements()) {
String key = (String)enumeration.nextElement();
context.setAttribute(key, props.getProperty(key));
}
}
} catch (ApplicationException ae) {
logger.error(ae.getMessage());
} catch (Exception ex) {
logger.error(ex.getMessage());
throw new RuntimeException(ex);
}
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent evt) {
logger.debug("### APPLICATION DESTROYED");
}
}