package tvark;

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;
import javax.servlet.http.HttpServletResponse;

public class RedirectFilter implements Filter {

	private String mPrefix;
	
	public void destroy() {

	}

	public void doFilter(ServletRequest pRequest, ServletResponse pResponse,
            FilterChain pChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) pRequest;
        HttpServletResponse resp = (HttpServletResponse) pResponse;

		
		
		String uri = req.getRequestURI().substring(req.getContextPath().length());
		if (!uri.startsWith(mPrefix)) {
			String newUri = req.getContextPath() + mPrefix + uri;
			resp.sendRedirect(newUri);
		} else {
			pChain.doFilter(req, resp);
		}
	}

	public void init(FilterConfig pConfig) throws ServletException {
		mPrefix = pConfig.getInitParameter("prefix");
		if (mPrefix == null || mPrefix.trim().length() == 0) {
			mPrefix = "/jsf";
		}
	}

}
