/* 

	Purpose:
		
	Description:
		
	History:
		2014/4/21, Dennis

Copyright (C) 2010 Potix Corporation. All Rights Reserved.

*/
package org.zkoss.zss.jsf;

import java.io.IOException;
import java.io.Serializable;

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.HttpSession;

import org.zkoss.zss.jsf.ui.impl.ObjectHolderContext;
import org.zkoss.zss.jsf.ui.impl.ObjectHolder;
/**
 * Filter to help create a object holder for issue ZSS-641, and kick object holder to release object after timeout.
 * by default, the object is removed when next request and older than 6000ms, you can set 
 * the filter initial parameter <code>millisecondToRemove</code> to change it. 
 *  
 * @author Dennis
 * @since 3.5.0
 */
public class ObjectHolderFilter implements Filter, Serializable {
	private static final long serialVersionUID = 3007219598969201384L;
	
	int millisecondToRemove = 6000;

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
        HttpSession session = req.getSession(false);
        if(session!=null){
        	ObjectHolder holder = new ObjectHolder(session, millisecondToRemove);
        	ObjectHolderContext.setHolder(holder);
        	try{
        		chain.doFilter(request, response);
        	}finally{
        		holder.kick();//kick timeout object
        		ObjectHolderContext.removeHolder();
        	}
        }else{
        	chain.doFilter(request, response);
        }
	}

	public void init(FilterConfig config) throws ServletException {
		String arg = config.getInitParameter("millisecondToRemove");
		if(arg!=null){
			millisecondToRemove = Integer.parseInt(arg);
		}
	}

	public void destroy() {
		
	}
}
