package com.heckmansoft.surjey.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * Filter the request path.
 */
public class RequestPathFilter implements Filter
{
    private FilterConfig filterConfig;

    Logger log = Logger.getLogger(RequestPathFilter.class);

    /**
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig)
        throws ServletException
    {
        this.filterConfig = filterConfig;
    }

    /**
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,javax.servlet.ServletResponse,javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException
    {
        // Set the action parameter from the request path
        if (request.getAttribute("action") == null) {
            // Get the request path
            String path = ((HttpServletRequest) request).getPathInfo();

            // Strip leading slash if it exists
            if (path.length() > 0) {
                if (path.substring(0,1).equals("/")) {
                    path = path.substring(1);
                }
            }

            // Store as action attribute
            request.setAttribute("action",path);
        }

        // Forward to next filter
        chain.doFilter(request,response);
    }

    /**
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {
        this.filterConfig = null;
    }

}



