package +zoccolo+.web.servlet;

import +zoccolo+.web.listener.AntiSamyListener;

import +zoccolo+.web.sanitizer.XssSanitizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;

public class HttpRequestWrapper extends HttpServletRequestWrapper {	
	
	private XssSanitizer sanitizer;
	
	public HttpRequestWrapper(HttpServletRequest servletRequest) {
		super(servletRequest);
		this.sanitizer = (XssSanitizer)
			this.getSession().getServletContext().
				getAttribute(AntiSamyListener.ANTISAMY_SANITIZER);
		if(this.sanitizer == null)
			throw new RuntimeException("Antisamy is not bound in ServletContext");
	}
	
	@Override
	public String[] getParameterValues(String parameter) {
		String[] retVal = null;
		String[] values = super.getParameterValues(parameter);
		if(values != null)
		{		
			retVal = new String[values.length];
			for(int i = 0; i < values.length; i++)
			{
				if(values[i] != null)					
					retVal[i] = this.cleanXss(values[i]);					
				else
					retVal[i] = values[i];
			}			
		}		
		return retVal;
	}
	
	@Override
	public String getParameter(String parameter) {	
		String paramValue = super.getParameter(parameter);
		if(paramValue != null)
			return this.cleanXss(paramValue);
		else
			return null;
	}
	
	@Override
	public String getHeader(String name) {		
		String value = super.getHeader(name);
		if(value != null)
			return this.cleanXss(value);
		else		
			return null;
	}
	
	private String cleanXss(String parameterValue){
		String retVal = null;		
		if(parameterValue != null) {
			try 
			{
				CleanResults cr = this.sanitizer.scan(parameterValue);
				retVal = cr.getCleanHTML();
			} 
			catch (ScanException e) 
			{			
				throw new RuntimeException("ScanException: "+e.getMessage());
			} 
			catch (PolicyException e) 
			{			
				throw new RuntimeException("ScanException: "+e.getMessage());
			}		
		}		
		return retVal;
	}
	/* screwdriver_knife */
}
