/*
 * Copyright (C) 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 javax.servlet.http.HttpServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

/**
 * <p>
 * Every application running in its own webapp should
 * declare an instance of this servlet in their web.xml,
 * marking it to load on startup. This is a work around
 * for bz 114688 - Tomcat ServletContext#getContext(String)
 * always returns the ROOT context in releases < 4.1.20
 * Map into your web.xml as follows:
 * </p>
 * <pre>
 * &lt;servlet&gt;
 *   &lt;servlet-name&gt;reg&lt;/servlet-name&gt;
 *   &lt;servlet-class&gt;com.arsdigita.web.ContextRegistrationServlet&lt;/servlet-class&gt;
 *   &lt;init-param&gt;
 *     &lt;param-name&gt;uri&lt;/param-name&gt;
 *     &lt;param-value&gt;/ccm-ldn-theme/&lt;/param-value&gt;
 *   &lt;/init-param&gt;
 *   &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
 * &lt;/servlet&gt;
 *
 * &lt;servlet-mapping&gt;
 *   &lt;servlet-name&gt;reg&lt;/servlet-name&gt;
 *   &lt;url-pattern&gt;/__ccm__/null/reg/*&lt;/url-pattern&gt;
 * &lt;/servlet-mapping&gt;
 *</pre>
 *<p>
 * The value of the init-param should be the same as the 
 * @name attribute on ccm:application tag in application.xml
 *</p>
 */
public class ContextRegistrationServlet extends HttpServlet {
    
    private String m_uri;

    public void init(final ServletConfig sconfig) throws ServletException {
        m_uri = sconfig.getInitParameter("uri");
        Assert.exists(m_uri, String.class);
        Assert.truth(m_uri.startsWith("/"), "uri starts with /");
        Assert.truth(m_uri.endsWith("/"), "uri ends with /");

        Web.registerServletContext(m_uri,
                                   sconfig.getServletContext());
    }

    public void destroy() {
        Web.unregisterServletContext(m_uri);
    }
}
