package cn.myapps.runtime.excutor.async;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.myapps.common.util.SpringApplicationContextUtil;

/**
 * 异步处理拦截器，在线程变量中初始化批量提交RuntimeDaoCommandGroup，RuntimeDaoCommand加入到RuntimeDaoCommandGroup中，在afterHandle中统一提交。
 * 如果没有线程变量中没有注册RuntimeDaoCommandGroup，则不采用异步方式提交。
 * 
 * @author Jarod
 *
 */
public class AsyncHandlerInterceptor extends HandlerInterceptorAdapter {

	private static final Logger log = LoggerFactory.getLogger(AsyncHandlerInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		log.debug("Create RuntimeDaoCommandGroup");
		RuntimeDaoCommandDispatch.initAsync();
		return true;
	}
	
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    	RuntimeDaoCommandDispatch executor = SpringApplicationContextUtil.getBean(RuntimeDaoCommandDispatch.class);
    	executor.kickOffAndClean();
    	log.debug("Kick-off and Clear RuntimeDaoCommandGroup");
    }


}
