package com.iamberry.common.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
/**
 * @author:何秀刚
 * @description: 设置跨域请求
 * @createDate:2016年5月26日
 */
public class SimpleCORSFilter implements Filter {
	
	public static List<String> origins = new ArrayList<String>(14);
	
	static {
		origins.add("h5.iamberry.com");
		origins.add("test.iamberry.com");
		origins.add("view.iamberry.com");
		origins.add("m.iamberry.com");
		origins.add("www.iamberry.com");
		origins.add("www.watero.cn");
		origins.add("m.watero.cn");
		origins.add("static.watero.cn");
		origins.add("static.iamberry.com");
		origins.add("s.iamberry.com");
		origins.add("w.iamberry.com:8848");
		origins.add("test.iamberry.com:8848");
		origins.add("rst.iamberry.com:8848");
		origins.add("static.iamberry.com:8848");
	}
    public void init(FilterConfig filterConfig) throws ServletException {}
    public void doFilter(ServletRequest servletRequest, ServletResponse
            servletResponse, FilterChain filterChain) throws IOException, ServletException {
		// CORS 跨域请求：允许当前域名，并设置语序的请求方式，一级在Ajax时，需要传递Cookie信息
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestOrigin = request.getHeader("Origin");
        String temp = requestOrigin == null ? null : (StringUtils.replace(StringUtils.replace(requestOrigin, "http://", ""), "https://", ""));
        if (temp != null && origins.contains(temp)) {
			response.setHeader("Access-Control-Allow-Origin", requestOrigin);
			response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
			response.setHeader("Access-Control-Max-Age", "3600");
			response.setHeader("Access-Control-Allow-Credentials", "true");
			response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
    public void destroy() {}
}
