package com.ylcm.sys.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.ylcm.sys.common.InjectCheckUtil;
import com.ylcm.sys.common.Util;

public class ParamFilter implements Filter {
	
	private static Logger logger = Logger.getLogger(ParamFilter.class);
	
	private final static String[] INT_PARAMS = {/*"page", */"pageIndex", "pageSize", "count"};
	
	private final static String[] HTML_PARAMS = {"content"};
	
	private final static Set<String> HTML_EXCLUDE_PATHS = new HashSet<String>();

	private static Pattern pattern = Pattern.compile("([0-9]+)");
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
	
	private String validateInt(String intParam){
		String i = "1";
		if (!StringUtils.isBlank(intParam)) {
			int page = 1;
			
			Matcher matcher = pattern.matcher(intParam);
			
			if(matcher.find()) 
				page = Integer.parseInt(matcher.group());
			i = page + "";
		}
		return i;
	}
	
	private String validateHtml(String stringParam){
		String i = "";
		if (!StringUtils.isBlank(stringParam)) {
			i = Util.filter(stringParam);
			i = StringEscapeUtils.escapeSql(i);
		}
		return i;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		/**
		 * 过滤 page pageIndex count pageSize
		 * 和content
		 */
		if (request instanceof HttpServletRequest) {
				HttpServletRequest httpRequest = (HttpServletRequest) request;
				Map newParams = new HashMap(request.getParameterMap()); 
				String path = httpRequest.getServletPath();
				//sql注入防止
				Map map = httpRequest.getParameterMap();
				for(Iterator it = map.keySet().iterator();it.hasNext();) {
					String content = ((String[]) map.get(it.next()))[0];
					if(InjectCheckUtil.filterInject(content)) {
						logger.error("url" + httpRequest.getRequestURI());
						logger.error("content: " + content);
						logger.error("ip: " + Util.getIpAddr(httpRequest) + " sql注入");

						throw new ServletException("有sql注入危险");
					}
				}
				
				if (!HTML_EXCLUDE_PATHS.contains(path)) {
					for (int i = HTML_PARAMS.length - 1; i >= 0; i--) {
						String page = httpRequest.getParameter(HTML_PARAMS[i]); 
						if (!StringUtils.isBlank(page)) {
							newParams.put(HTML_PARAMS[i], validateHtml(page));
						}
					}
				}
				
				
				for (int i = INT_PARAMS.length - 1; i >= 0; i--) {
					String page = httpRequest.getParameter(INT_PARAMS[i]); 
					if (!StringUtils.isBlank(page)) {
						newParams.put(INT_PARAMS[i], validateInt(page));
					}
				}
				
				// process the chain
				chain.doFilter(new ParameterRequestWrapper(httpRequest, newParams), response);
		}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	
}
