package com.house365.web.interceptor;

import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * 对外接口公共必传参数校验拦截器
 *
 * @author zhaodeshan
 * @version [版本号, 2015年5月7日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class CommonParamsInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        if (request.getRequestURI().contains("/rest/interface")) {
            String commonParams = MemoryPropertyPlaceholderConfigurer.getContextProperty("rest.commonParams");
            String[] paramNames = commonParams.split(",");
            for (String paramName : paramNames) {
                if (StringUtils.isBlank(request.getParameter(paramName))) {
                    throw new IllegalServiceParameterException("业务入口参数异常：" + paramName + "参数为空!");
                }
            }
        }

        return true;
    }
}
