package eu.dnetlib.utils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

/**
 * A simple context listener that reads the servlet context and sets the context
 * path as a system property. 
 * 
 * @author antleb
 *
 */
public class ContextPathReader implements ServletContextListener {
	private static Logger logger = Logger.getLogger(ContextPathReader.class);

	public void contextDestroyed(ServletContextEvent arg0) {
		// doing nothing
	}

	public void contextInitialized(ServletContextEvent event) {
		try {
			String propertyName = event.getServletContext().getInitParameter("applicationContextProperty");
			String path = event.getServletContext().getContextPath();
			
			if (propertyName == null)
				propertyName = "driver.service.context";
			
			logger.debug("Web application path: " + path + " (in property '" + propertyName + "')");
			
			if (path.startsWith("/"))
				path = path.substring(1);
			
			System.setProperty("driver.service.context", path);
		} catch (Exception e) {
			logger.error("Error reading application context path", e);
		}
	}
}
