/*
 * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.web;

import com.arsdigita.util.Assert;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;

/**
 *
 *
 * @author Justin Ross &lt;<a href="mailto:jross@redhat.com">jross@redhat.com</a>&gt;
 * @version $Id: //core-platform/dev/src/com/arsdigita/web/PrefixerServlet.java#6 $
 */
public class PrefixerServlet extends HttpServlet {
    public static final String versionId =
        "$Id: //core-platform/dev/src/com/arsdigita/web/PrefixerServlet.java#6 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

    private static final Logger s_log = Logger.getLogger(PrefixerServlet.class);

    public static final String PREFIX_PARAMETER = "prefix";

    private String m_prefix = null;

    public final void init() throws ServletException {
        final ServletConfig config = getServletConfig();

        m_prefix = config.getInitParameter(PREFIX_PARAMETER);

        Assert.assertNotNull(m_prefix, "String m_prefix");
        Assert.assertTrue(m_prefix.startsWith("/"),
                          "The target prefix must start with a '/'");
    }

    protected final void service(final HttpServletRequest sreq, 
                                 final HttpServletResponse sresp)
            throws IOException, ServletException {
        final StringBuffer buffer = new StringBuffer();

        buffer.append(sreq.getContextPath());
        buffer.append(m_prefix);
        buffer.append(sreq.getServletPath());

        final String pathInfo = sreq.getPathInfo();

        if (pathInfo != null) {
            buffer.append(pathInfo);
        }

        final String queryString = sreq.getQueryString();

        if (queryString != null) {
            buffer.append("?");
            buffer.append(queryString);
        }

        final String result = sresp.encodeRedirectURL(buffer.toString());

        sresp.sendRedirect(result);
    }

    public final void destroy() {
        m_prefix = null;
    }
}
