package com.iamberry.common.web;

import java.io.IOException;
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 {
		
	public static List<String> origins = new Vector<String>(6);
	
	static {
		origins.add("http://h5.iamberry.com");
		origins.add("http://test.iamberry.com");
		origins.add("http://m.iamberry.com");
		origins.add("http://www.iamberry.com");
		origins.add("http://www.watero.cn");
		origins.add("http://m.watero.cn");
		origins.add("http://static.watero.cn");
		origins.add("http://static.iamberry.com");
	}
	
    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");
        if (requestOrigin != null && origins.contains(requestOrigin)) {
			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-Headers", "x-requested-with");
			response.setHeader("Access-Control-Allow-Credentials", "true");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {

    }
}
