package +zoccolo+.web.listener;

import +zoccolo+.web.sanitizer.XssSanitizer;

import java.io.InputStream;

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

import org.apache.log4j.Logger;
import org.owasp.validator.html.PolicyException;

public class AntiSamyListener 
	implements ServletContextListener {

	public static final String POLICY_FILE_PATH = "policy_file_path";
	public static final String ANTISAMY_SANITIZER = "sanitizer";

	static Logger log = Logger.getLogger(AntiSamyListener.class);

	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		log.info("Context destroyed");
	}

	public void contextInitialized(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();
		String policyFilePath = (String) servletContext.getInitParameter(POLICY_FILE_PATH);
		if (policyFilePath == null) {
			throw new RuntimeException(
					"Policy file path is null. Please set it up in web.xml!!!");
		}
		log.info("XSS Policy file path read.");

		InputStream is = getClass().getClassLoader().getResourceAsStream(
				policyFilePath);
		try {
			is.available();
			log.info("XSS Policy file loaded.");
		} catch (Exception e) {
			throw new RuntimeException("Policy file " + policyFilePath
					+ " does not exists!");
		}

		try {
			XssSanitizer sanitizer = new XssSanitizer(policyFilePath);
			log.info("XSS Sanitizer created.");
			servletContext.setAttribute(ANTISAMY_SANITIZER, sanitizer);
			log.info("XSS bound in Servlet Context as: " + ANTISAMY_SANITIZER);
		} catch (PolicyException pex) {
			throw new RuntimeException("Policy exception: " + pex.getMessage());
		}
	}
	/* screwdriver_knife */
}
