/**
 * Dragon - SOA Governance Platform.
 * Copyright (c) 2008 EBM Websourcing, http://www.ebmwebsourcing.com/
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * -------------------------------------------------------------------------
 * SpringUtil.java
 * -------------------------------------------------------------------------
 */

package org.ow2.dragon.util;

import javax.servlet.ServletContext;

import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;

/**
 * An util class to ease Spring integration
 * 
 * @author ofabre - eBM WebSourcing
 * 
 */
public class SpringUtil {

    /**
     * Find the root WebApplicationContext for this web application, which is
     * typically loaded via ContextLoaderListener or ContextLoaderServlet.
     * <p>
     * Will rethrow an exception that happened on root context startup, to
     * differentiate between a failed context startup and no context at all.
     * 
     * @param sc
     *            ServletContext to find the web application context for
     * @return the root WebApplicationContext for this web app, or
     *         <code>null</code> if none
     * @see org.springframework.web.context.WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
     */
    public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
        Assert.notNull(sc, "ServletContext must not be null");
        Object attr = sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        if (attr == null) {
            return null;
        }
        if (attr instanceof RuntimeException) {
            throw (RuntimeException) attr;
        }
        if (attr instanceof Error) {
            throw (Error) attr;
        }
        if (!(attr instanceof WebApplicationContext)) {
            throw new IllegalStateException(
                    "Root context attribute is not of type WebApplicationContext: " + attr);
        }
        return (WebApplicationContext) attr;
    }

}
