/**
 * 
 */
package com.ejweb.core.filter;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ejweb.conf.GConstants;
import com.ejweb.core.utils.LoadExceptions;


/**
 * 
 * @team IT Team
 * @author zhanglg
 * @version 1.0
 * @time  2016年11月7日
 */

public class URLInterceptor implements HandlerInterceptor {
    @SuppressWarnings("unchecked")
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {  
        
        long maxFileSize = Long.valueOf(GConstants.getValue("file.max.upload.size"));
        HttpServletRequest reqs = (HttpServletRequest)request;
       long fileSize =  reqs.getContentLength();
       
       if(fileSize > maxFileSize)
       {
           throw new LoadExceptions("文件大小超出限制，请改正！");
           
           
       }
        
        
        String returnUrl = request.getRequestURI();
        // 如果是自定义表单，则放行验证
        if(returnUrl.contains("verify/form/processor")||returnUrl.contains("airline/verify2type/save")
                ||returnUrl.contains("contact/contacts/save")||returnUrl.contains("/admin/contact/seat2/list")){
            return true;
        }
        Map<String, String[]> params = request.getParameterMap();  
        String queryString = "";  
       
        for (String key : params.keySet()) {
          if(("parentIds").equals(key))continue;
            String[] values = params.get(key);  
            for (int i = 0; i < values.length; i++) {  
                String value = values[i];  
                queryString += key + "=" + value ;
            }  
        }
        if(returnUrl.contains("admin/login")){
           
            queryString=returnUrl.replaceAll(";","")+queryString;
            
        }
        if(returnUrl.contains("contact/satellite/save")){
           
            queryString=queryString.replaceAll(",","");
            
        }
        queryString=queryString.replaceAll("selectIds","");
        
        String url=  queryString.toUpperCase();
        url=url.replaceAll("CREATEBY","");
        SAXReader reader = null;
        InputStream in = null;
        Document doc = null;
        Element root = null;
        Element entry = null;
        List<Element> items = null;
        ResourceLoader resourceLoader = null;
        Resource resource = null;
        resourceLoader = new DefaultResourceLoader();
        resource = resourceLoader.getResource("safe.xml");
        in = resource.getInputStream();
        in = new BufferedInputStream(in);
        
        reader = new SAXReader();
        reader.setValidation(false);
        doc = reader.read(in);
        root = doc.getRootElement();
        entry = root.element("exception");
      if (entry != null) {
            items = entry.elements("url");
            for (Element item : items) {
                if(returnUrl.contains(item.getText())){
                    return true;
                }
            }
          
        }
        
        entry = root.element("keywords1");

        if (entry != null) {
            items = entry.elements("keyword");
            for (Element item : items) {
                if(url.contains(item.getText())){
                    throw new LoadExceptions("参数传递过程中存在非法字符，请改正！");
                }
            }
          
        }
        entry = root.element("keywords2");

        if (entry != null) {
            items = entry.elements("keyword");
            for (Element item : items) {
                if(url.contains(item.getText())){
                    
                    throw new LoadExceptions("参数传递过程中存在非法字符，请改正！");
                }
            }
          
        }
        entry = root.element("keywords3");

        if (entry != null) {
            items = entry.elements("keyword");
            for (Element item : items) {
                if(queryString.contains(item.getText())){
                  if(",".equals(item.getText())&&(queryString.contains("menuIds")||queryString.contains("idsArr")
                          ||queryString.contains("user.name"))){
                      continue;
                  }
                    throw new LoadExceptions("参数传递过程中存在非法字符，请改正！");
                }
            }
          
        }
        entry = root.element("keywords4");

        if (entry != null) {
            items = entry.elements("keyword");
            for (Element item : items) {
                if(url.contains(item.getText())){
                    throw new LoadExceptions("参数传递过程中存在非法字符，请改正！");
                }
            }
          
        }
        entry = root.element("keywords5");

        if (entry != null) {
            items = entry.elements("keyword");
            for (Element item : items) {
                if(url.contains(item.getText())){
                    throw new LoadExceptions("参数传递过程中存在非法字符，请改正！");
                }
            }
          
        }
        return true;
    }

   
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        
    }

    /* (non-Javadoc)
     * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
        
    }
}
