package it.mice.voila.runtime.springmvc.flashmap;

import java.io.IOException;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.OncePerRequestFilter;
/**
 * @deprecated since 1.1-SNAPSHOT
 */
public class FlashMapFilter extends OncePerRequestFilter {

	@Override
	@SuppressWarnings("unchecked")
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		Map<String, ?> flash = null;
		if (session != null) {
			flash = (Map<String, ?>) session.getAttribute(FlashMap.FLASH_MAP_ATTRIBUTE);
			if (flash != null) {
				for (Map.Entry<String, ?> entry : flash.entrySet()) {
					Object currentValue = request.getAttribute(entry.getKey());
					if (currentValue == null) {
						request.setAttribute(entry.getKey(), entry.getValue());
					}					
				}
			}
		}
		try {
			filterChain.doFilter(request, response);
		} finally {
			if (flash != null) {
				try {
					session.removeAttribute(FlashMap.FLASH_MAP_ATTRIBUTE);
				} catch (Exception e) {
				}
			}
		}
	}
}
