Example usage for org.springframework.web.context WebApplicationContext ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE

List of usage examples for org.springframework.web.context WebApplicationContext ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE

Introduction

In this page you can find the example usage for org.springframework.web.context WebApplicationContext ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE.

Prototype

String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE

To view the source code for org.springframework.web.context WebApplicationContext ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE.

Click Source Link

Document

Context attribute to bind root WebApplicationContext to on successful startup.

Usage

From source file:org.springframework.boot.legacy.context.web.NonEmbeddedWebApplicationContext.java

/**
 * Prepare the {@link WebApplicationContext} with the given fully loaded
 * {@link ServletContext}. This method is usually called from
 * {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the
 * functionality usually provided by a {@link ContextLoaderListener}.
 * @param servletContext the operational servlet context
 *//*  ww  w  . j ava  2s. c  o  m*/
protected void prepareWebApplicationContext(ServletContext servletContext) {
    Object rootContext = servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (rootContext != null) {
        if (rootContext == this) {
            throw new IllegalStateException(
                    "Cannot initialize context because there is already a root application context present - "
                            + "check whether you have multiple ServletContextInitializers!");
        } else {
            return;
        }
    }
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring embedded WebApplicationContext");
    WebApplicationContextUtils.registerWebApplicationScopes(getBeanFactory(), getServletContext());
    WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), getServletContext());
    try {
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this);
        if (logger.isDebugEnabled()) {
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name ["
                    + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
        }
        if (logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - getStartupDate();
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
        }
    } catch (RuntimeException ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    } catch (Error ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    }
}

From source file:org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.java

/**
 * Prepare the {@link WebApplicationContext} with the given fully loaded
 * {@link ServletContext}. This method is usually called from
 * {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the
 * functionality usually provided by a {@link ContextLoaderListener}.
 * @param servletContext the operational servlet context
 *//*from  w  ww  .  j  a va2  s. c om*/
protected void prepareWebApplicationContext(ServletContext servletContext) {
    Object rootContext = servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (rootContext != null) {
        if (rootContext == this) {
            throw new IllegalStateException(
                    "Cannot initialize context because there is already a root application context present - "
                            + "check whether you have multiple ServletContextInitializers!");
        }
        return;
    }
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring embedded WebApplicationContext");
    try {
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this);
        if (logger.isDebugEnabled()) {
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name ["
                    + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
        }
        setServletContext(servletContext);
        if (logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - getStartupDate();
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
        }
    } catch (RuntimeException | Error ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    }
}

From source file:org.springframework.boot.web.servlet.support.SpringBootServletInitializer.java

protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
    SpringApplicationBuilder builder = createSpringApplicationBuilder();
    builder.main(getClass());//from www  . j a v a 2  s.c  o  m
    ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
    if (parent != null) {
        this.logger.info("Root context already created (using as parent).");
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
        builder.initializers(new ParentContextApplicationContextInitializer(parent));
    }
    builder.initializers(new ServletContextApplicationContextInitializer(servletContext));
    builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class);
    builder = configure(builder);
    builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext));
    SpringApplication application = builder.build();
    if (application.getAllSources().isEmpty()
            && AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) {
        application.addPrimarySources(Collections.singleton(getClass()));
    }
    Assert.state(!application.getAllSources().isEmpty(),
            "No SpringApplication sources have been defined. Either override the "
                    + "configure method or add an @Configuration annotation");
    // Ensure error pages are registered
    if (this.registerErrorPageFilter) {
        application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class));
    }
    return run(application);
}

From source file:org.springframework.boot.web.SpringBootServletInitializer.java

protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
    ApplicationContext parent = null;//www  . jav  a2 s . c o m
    Object object = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (object instanceof ApplicationContext) {
        this.logger.info("Root context already created (using as parent).");
        parent = (ApplicationContext) object;
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
    }
    SpringApplicationBuilder application = new SpringApplicationBuilder();
    if (parent != null) {
        application.initializers(new ParentContextApplicationContextInitializer(parent));
    }
    application.initializers(new ServletContextApplicationContextInitializer(servletContext));
    application.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
    application = configure(application);
    return (WebApplicationContext) application.run();
}

From source file:org.springframework.boot.web.SpringServletInitializer.java

protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
    ApplicationContext parent = null;/*from w  w  w . j a v  a  2  s. c  o  m*/
    Object object = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (object instanceof ApplicationContext) {
        this.logger.info("Root context already created (using as parent).");
        parent = (ApplicationContext) object;
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
    }
    SpringApplication application = new SpringApplication((Object[]) getConfigClasses());
    AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext();
    context.setParent(parent);
    context.setServletContext(servletContext);
    application.setApplicationContext(context);
    return (WebApplicationContext) application.run();
}

From source file:org.springframework.boot.web.support.SpringBootServletInitializer.java

protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
    SpringApplicationBuilder builder = createSpringApplicationBuilder();
    builder.main(getClass());//from www .j  a  v a 2  s .c o  m
    ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
    if (parent != null) {
        this.logger.info("Root context already created (using as parent).");
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
        builder.initializers(new ParentContextApplicationContextInitializer(parent));
    }
    builder.initializers(new ServletContextApplicationContextInitializer(servletContext));
    builder.listeners(new ServletContextApplicationListener(servletContext));
    builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
    builder = configure(builder);
    SpringApplication application = builder.build();
    if (application.getSources().isEmpty()
            && AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) {
        application.getSources().add(getClass());
    }
    Assert.state(!application.getSources().isEmpty(),
            "No SpringApplication sources have been defined. Either override the "
                    + "configure method or add an @Configuration annotation");
    // Ensure error pages are registered
    if (this.registerErrorPageFilter) {
        application.getSources().add(ErrorPageFilterConfiguration.class);
    }
    return run(application);
}

From source file:org.springframework.extensions.webscripts.portlet.WebScriptPortlet.java

public void init(PortletConfig config) throws PortletException {
    initScriptUrl = config.getInitParameter("scriptUrl");
    PortletContext portletCtx = config.getPortletContext();
    WebApplicationContext context = (WebApplicationContext) portletCtx
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    container = (RuntimeContainer) context.getBean("webscripts.container");

    // retrieve authenticator factory via servlet initialisation parameter
    String authenticatorId = config.getInitParameter("authenticator");
    if (authenticatorId != null && authenticatorId.length() > 0) {
        Object bean = context.getBean(authenticatorId);
        if (bean == null || !(bean instanceof PortletAuthenticatorFactory)) {
            throw new PortletException(
                    "Initialisation parameter 'authenticator' does not refer to a portlet authenticator factory ("
                            + authenticatorId + ")");
        }//from  w ww . j  av a 2s.c  om
        authenticatorFactory = (PortletAuthenticatorFactory) bean;
    }
}

From source file:org.springframework.test.context.support.AbstractGenericWebContextLoader.java

/**
 * TODO [SPR-9864] Document configureWebResources().
 *///from   ww  w. j  a v a2  s. c o m
protected void configureWebResources(GenericWebApplicationContext context,
        WebMergedContextConfiguration webMergedConfig) {

    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);
}

From source file:org.springframework.test.context.support.WebApplicationContextLoader.java

private void prepareContext(GenericWebApplicationContext context) {
    MockServletContext servletContext = new MockServletContext();
    context.setServletContext(servletContext);
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
}

From source file:org.springframework.test.context.web.AbstractGenericWebContextLoader.java

/**
 * 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).//from   www. j av  a  2  s .  co  m
 * <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();

    // If the WebApplicationContext has no parent or the parent is not a WebApplicationContext,
    // set the current context as the root WebApplicationContext:
    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 WebApplicationContext
        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);
    }
}