package com.iamberry.common.web;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

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;
/**
 * @author:何秀刚
 * @description: 设置跨域请求
 * @createDate:2016年5月26日
 */
public class SimpleCORSFilter implements Filter {
	private static Logger logger = Logger.getLogger(SimpleCORSFilter.class);

	public static List<String> origins = new ArrayList<String>(10);
	
	static {
		origins.add("h5.iamberry.com");
		origins.add("test.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("www.aiberletech.com");
		origins.add("h5.iamberry.com:801");
		origins.add("h5.iamberry.com:8848");
		origins.add("test.iamberry.com:8848");
	}
	
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse
            servletResponse, FilterChain filterChain) throws IOException, ServletException {
        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() {}

}
