package org.yacos.web.system.session;

import java.io.IOException;

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;

/**
 * Filter to initialize the SessionService singleton
 * @author christiancorsano
 *
 */
public class SessionServiceFilter implements Filter {
	/**
	 * Inits the filter, and set the servletContext for this session service
	 */
	public void init(FilterConfig config) throws ServletException {
		SessionService.servletContext = config.getServletContext();
	}

	/**
	 * Puts the request object into SessionService and tells it to init
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if(request instanceof HttpServletRequest){
			SessionService.request = (HttpServletRequest) request;
			SessionService.getInstance().init();
		}
		
		// Continue the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * Clean the static attributes
	 */
	public void destroy() {
		SessionService.servletContext = null;
		SessionService.request = null;
	}
}