/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/

package gov.va.med.fw.ui;

import javax.servlet.ServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.struts.ContextLoaderPlugIn;

/**
 * @author DNS   LEV
 *
 */
public class DelegatingActionUtils extends
		org.springframework.web.struts.DelegatingActionUtils {

	/**
	 * Find most specific context available: check ContextLoaderPlugIn's
	 * WebApplicationContext first, fall back to root WebApplicationContext else.
	 * <p>When checking the ContextLoaderPlugIn context: checks for a module-specific
	 * context first, falling back to the context for the default module else.
	 * @param context the associated ServletContext
	 * @return the WebApplicationContext
	 * @throws IllegalStateException if no WebApplicationContext could be found
	 * @see #getWebApplicationContext
	 * @see org.springframework.web.context.support.WebApplicationContextUtils#getRequiredWebApplicationContext
	 */
	public static WebApplicationContext findRequiredWebApplicationContext( ServletContext context ) throws IllegalStateException {

		WebApplicationContext wac = (WebApplicationContext) 
			context.getAttribute( ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX );
		
		// If no Struts-specific context found, fall back to root context.
		if (wac == null) {
			wac = WebApplicationContextUtils.getRequiredWebApplicationContext( context );
		}
		return wac;
	}
}
