Search in sources :

Example 81 with WebApplicationContext

use of org.springframework.web.context.WebApplicationContext in project spring-framework by spring-projects.

the class WebApplicationContextUtils method findWebApplicationContext.

/**
	 * Find a unique {@code WebApplicationContext} for this web app: either the
	 * root web app context (preferred) or a unique {@code WebApplicationContext}
	 * among the registered {@code ServletContext} attributes (typically coming
	 * from a single {@code DispatcherServlet} in the current web application).
	 * <p>Note that {@code DispatcherServlet}'s exposure of its context can be
	 * controlled through its {@code publishContext} property, which is {@code true}
	 * by default but can be selectively switched to only publish a single context
	 * despite multiple {@code DispatcherServlet} registrations in the web app.
	 * @param sc ServletContext to find the web application context for
	 * @return the desired WebApplicationContext for this web app, or {@code null} if none
	 * @since 4.2
	 * @see #getWebApplicationContext(ServletContext)
	 * @see ServletContext#getAttributeNames()
	 */
public static WebApplicationContext findWebApplicationContext(ServletContext sc) {
    WebApplicationContext wac = getWebApplicationContext(sc);
    if (wac == null) {
        Enumeration<String> attrNames = sc.getAttributeNames();
        while (attrNames.hasMoreElements()) {
            String attrName = attrNames.nextElement();
            Object attrValue = sc.getAttribute(attrName);
            if (attrValue instanceof WebApplicationContext) {
                if (wac != null) {
                    throw new IllegalStateException("No unique WebApplicationContext found: more than one " + "DispatcherServlet registered with publishContext=true?");
                }
                wac = (WebApplicationContext) attrValue;
            }
        }
    }
    return wac;
}
Also used : WebApplicationContext(org.springframework.web.context.WebApplicationContext) ConfigurableWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext)

Example 82 with WebApplicationContext

use of org.springframework.web.context.WebApplicationContext in project spring-framework by spring-projects.

the class WebApplicationObjectSupport method getServletContext.

/**
	 * Return the current ServletContext.
	 * @throws IllegalStateException if not running within a ServletContext
	 */
protected final ServletContext getServletContext() throws IllegalStateException {
    if (this.servletContext != null) {
        return this.servletContext;
    }
    WebApplicationContext wac = getWebApplicationContext();
    if (wac == null) {
        return null;
    }
    ServletContext servletContext = wac.getServletContext();
    if (servletContext == null && isContextRequired()) {
        throw new IllegalStateException("WebApplicationObjectSupport instance [" + this + "] does not run within a ServletContext. Make sure the object is fully configured!");
    }
    return servletContext;
}
Also used : ServletContext(javax.servlet.ServletContext) WebApplicationContext(org.springframework.web.context.WebApplicationContext)

Example 83 with WebApplicationContext

use of org.springframework.web.context.WebApplicationContext in project spring-framework by spring-projects.

the class OpenEntityManagerInViewFilter method lookupEntityManagerFactory.

/**
	 * Look up the EntityManagerFactory that this filter should use.
	 * <p>The default implementation looks for a bean with the specified name
	 * in Spring's root application context.
	 * @return the EntityManagerFactory to use
	 * @see #getEntityManagerFactoryBeanName
	 */
protected EntityManagerFactory lookupEntityManagerFactory() {
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    String emfBeanName = getEntityManagerFactoryBeanName();
    String puName = getPersistenceUnitName();
    if (StringUtils.hasLength(emfBeanName)) {
        return wac.getBean(emfBeanName, EntityManagerFactory.class);
    } else if (!StringUtils.hasLength(puName) && wac.containsBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
        return wac.getBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME, EntityManagerFactory.class);
    } else {
        // Includes fallback search for single EntityManagerFactory bean by type.
        return EntityManagerFactoryUtils.findEntityManagerFactory(wac, puName);
    }
}
Also used : EntityManagerFactory(javax.persistence.EntityManagerFactory) WebApplicationContext(org.springframework.web.context.WebApplicationContext)

Example 84 with WebApplicationContext

use of org.springframework.web.context.WebApplicationContext in project spring-framework by spring-projects.

the class AbstractGenericWebContextLoader method configureWebResources.

/**
	 * Configures web resources for the supplied web application context (WAC).
	 *
	 * <h4>Implementation Details</h4>
	 *
	 * <p>If the supplied WAC has no parent or its parent is not a WAC, the
	 * supplied WAC will be configured as the Root WAC (see "<em>Root WAC
	 * Configuration</em>" below).
	 *
	 * <p>Otherwise the context hierarchy of the supplied WAC will be traversed
	 * to find the top-most WAC (i.e., the root); and the {@link ServletContext}
	 * of the Root WAC will be set as the {@code ServletContext} for the supplied
	 * WAC.
	 *
	 * <h4>Root WAC Configuration</h4>
	 *
	 * <ul>
	 * <li>The resource base path is retrieved from the supplied
	 * {@code WebMergedContextConfiguration}.</li>
	 * <li>A {@link ResourceLoader} is instantiated for the {@link MockServletContext}:
	 * if the resource base path is prefixed with "{@code classpath:}", a
	 * {@link DefaultResourceLoader} will be used; otherwise, a
	 * {@link FileSystemResourceLoader} will be used.</li>
	 * <li>A {@code MockServletContext} will be created using the resource base
	 * path and resource loader.</li>
	 * <li>The supplied {@link GenericWebApplicationContext} is then stored in
	 * the {@code MockServletContext} under the
	 * {@link WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} key.</li>
	 * <li>Finally, the {@code MockServletContext} is set in the
	 * {@code WebApplicationContext}.</li>
	 *
	 * @param context the web application context for which to configure the web
	 * resources
	 * @param webMergedConfig the merged context configuration to use to load the
	 * web application context
	 */
protected void configureWebResources(GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {
    ApplicationContext parent = context.getParent();
    // the Root WAC:
    if (parent == null || (!(parent instanceof WebApplicationContext))) {
        String resourceBasePath = webMergedConfig.getResourceBasePath();
        ResourceLoader resourceLoader = resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX) ? new DefaultResourceLoader() : new FileSystemResourceLoader();
        ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
        context.setServletContext(servletContext);
    } else {
        ServletContext servletContext = null;
        // find the Root WAC
        while (parent != null) {
            if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) {
                servletContext = ((WebApplicationContext) parent).getServletContext();
                break;
            }
            parent = parent.getParent();
        }
        Assert.state(servletContext != null, "Failed to find Root WebApplicationContext in the context hierarchy");
        context.setServletContext(servletContext);
    }
}
Also used : ResourceLoader(org.springframework.core.io.ResourceLoader) FileSystemResourceLoader(org.springframework.core.io.FileSystemResourceLoader) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) WebApplicationContext(org.springframework.web.context.WebApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) FileSystemResourceLoader(org.springframework.core.io.FileSystemResourceLoader) ServletContext(javax.servlet.ServletContext) MockServletContext(org.springframework.mock.web.MockServletContext) MockServletContext(org.springframework.mock.web.MockServletContext) WebApplicationContext(org.springframework.web.context.WebApplicationContext) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader)

Example 85 with WebApplicationContext

use of org.springframework.web.context.WebApplicationContext in project spring-framework by spring-projects.

the class ServletTestExecutionListener method setUpRequestContextIfNecessary.

private void setUpRequestContextIfNecessary(TestContext testContext) {
    if (!isActivated(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
        return;
    }
    ApplicationContext context = testContext.getApplicationContext();
    if (context instanceof WebApplicationContext) {
        WebApplicationContext wac = (WebApplicationContext) context;
        ServletContext servletContext = wac.getServletContext();
        Assert.state(servletContext instanceof MockServletContext, () -> String.format("The WebApplicationContext for test context %s must be configured with a MockServletContext.", testContext));
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.", testContext));
        }
        MockServletContext mockServletContext = (MockServletContext) servletContext;
        MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
        request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE);
        MockHttpServletResponse response = new MockHttpServletResponse();
        ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
        RequestContextHolder.setRequestAttributes(servletWebRequest);
        testContext.setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
        testContext.setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
        if (wac instanceof ConfigurableApplicationContext) {
            @SuppressWarnings("resource") ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac;
            ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory();
            bf.registerResolvableDependency(MockHttpServletResponse.class, response);
            bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest);
        }
    }
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) WebApplicationContext(org.springframework.web.context.WebApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ServletContext(javax.servlet.ServletContext) MockServletContext(org.springframework.mock.web.MockServletContext) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MockServletContext(org.springframework.mock.web.MockServletContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) WebApplicationContext(org.springframework.web.context.WebApplicationContext)

Aggregations

WebApplicationContext (org.springframework.web.context.WebApplicationContext)103 Test (org.junit.Test)32 ServletContext (javax.servlet.ServletContext)17 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)15 MockHttpServletResponse (org.springframework.mock.web.test.MockHttpServletResponse)13 ApplicationContext (org.springframework.context.ApplicationContext)11 GenericWebApplicationContext (org.springframework.web.context.support.GenericWebApplicationContext)11 HashMap (java.util.HashMap)9 StaticWebApplicationContext (org.springframework.web.context.support.StaticWebApplicationContext)9 MockServletContext (org.springframework.mock.web.test.MockServletContext)8 ConfigurableWebApplicationContext (org.springframework.web.context.ConfigurableWebApplicationContext)7 Filter (javax.servlet.Filter)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 AnnotationConfigWebApplicationContext (org.springframework.web.context.support.AnnotationConfigWebApplicationContext)6 Binding (groovy.lang.Binding)5 BeanBuilder (hudson.util.spring.BeanBuilder)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 DispatcherServlet (org.springframework.web.servlet.DispatcherServlet)5 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)4 ConfigurableApplicationContext (org.springframework.context.ConfigurableApplicationContext)4