package com.jware.base.boot;

import java.io.IOException;
import java.util.Enumeration;
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.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Jrmt
 *  
 */
public class EncodingFilter implements Filter {

	/**
	 * Commons Logging instance.
	*/
	private Log log = LogFactory.getLog(this.getClass().getName());

    private String encoding = null;
    private String[] exceptions = new String[0];

    public void init(FilterConfig config) throws ServletException {

        encoding = config.getInitParameter("encoding");
        if( encoding.equalsIgnoreCase( "shift-jis") || encoding.equalsIgnoreCase("sjis")){
        	encoding = "MS932";
        }
        String tmp = config.getInitParameter("exceptions");
        if( tmp != null ){
        	exceptions = tmp.split( "," );
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

    	HttpServletRequest req = (HttpServletRequest)request;
    	
    	String querystring =  req.getRequestURI();
    	String contextstring =  req.getContextPath();
    	if( contextstring != null && querystring != null ){
    		querystring = querystring.substring( contextstring.length() );
    	}
    	
    	for( int i=0; i<exceptions.length; i++ ){
    		String ptn = exceptions[i];
    		ptn = ptn.replaceAll( "[.]", "[.]" );
    		ptn = ptn.replaceAll( "[*]", ".*");
    		Pattern urlPattern = Pattern.compile(ptn);
    		Matcher urlMatcher = urlPattern.matcher( querystring );
    		if( urlMatcher.matches() ){
    	        chain.doFilter(request, response);
    			return;
    		}
    	}
    	
    	String request_encoding = req.getCharacterEncoding();
    	if( request_encoding == null || "".equals( request_encoding.trim())){
    		req.setCharacterEncoding(encoding);
    	}

    	/**
         *  GET method Japanese corruption problem fix on windows
         *  Java version : 1.4.2.07
         *  Tomcat version : 5.0.28
         */
    	String osname = System.getProperty( "os.name");
        if( "GET".equalsIgnoreCase( req.getMethod() )){
//      if( osname.startsWith( "Windows") && "GET".equalsIgnoreCase( req.getMethod() )){
        	
    		try {
//    			BufferedReader reader = req.getReader();  			
//    			String line=reader.readLine();
    			Enumeration values = req.getParameterNames();
    			while(values.hasMoreElements()) {
        			String name = (String)values.nextElement();
        			String value = req.getParameterValues(name)[0];
        			req.getParameterValues(name)[0] = new String(value.getBytes("ISO-8859-1"), encoding);
        			if( log.isDebugEnabled() ){
        				log.debug( "0. value=" + value );
        				log.debug( "1. value=" + new String(value.getBytes("ISO-8859-1"), encoding) );
        			}
    			}
    			
    		}catch(Exception e) {
    			;
    		}
        }
        
       	chain.doFilter( req, response );    
    }

    public void destroy() {

        encoding = null;
    }

}