/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.web.tomcat7;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.catalina.Valve;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;

/**
 * This class allows to wrap an http filter into a Tomcat valve.
 * @author Florent Benoit
 */
public class FilterValveWrapper extends ValveBase {

    /**
     * Wrapped filter.
     */
    private Filter filter = null;

    /**
     * Default constructor wrapping the given filter.
     * @param filter the given filter
     */
    public FilterValveWrapper(final Filter filter) {
        super(true);
        this.filter = filter;
    }


    /**
     * Remove the current authenticated user by setting the anonymous user.
     * @param request The servlet request to be processed
     * @param response The servlet response to be created
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    @Override
    public void invoke(final Request request, final Response response) throws IOException, ServletException {
        filter.doFilter(request, response, new ValveFilterChain(getNext(), request, response));
    }


}


class ValveFilterChain implements FilterChain {

    private Valve valve = null;

    private Request request;
    private Response response;

    public ValveFilterChain(final Valve valve, final Request request, final Response response) {
        this.valve = valve;
        this.request = request;
        this.response = response;
    }

    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse) throws IOException, ServletException {
        valve.invoke(request, response);
    }



}
