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.apache.archiva.webdav.RepositoryServletSecurityTest.java

@Before
@Override/*from w  w  w  . j ava  2 s  .co  m*/
public void setUp() throws Exception {

    super.setUp();

    String appserverBase = System.getProperty("appserver.base",
            new File("target/appserver-base").getAbsolutePath());

    File testConf = new File("src/test/resources/repository-archiva.xml");
    File testConfDest = new File(appserverBase, "conf/archiva.xml");
    FileUtils.copyFile(testConf, testConfDest);

    Configuration config = archivaConfiguration.getConfiguration();
    // clear managed repository
    List<ManagedRepositoryConfiguration> f1 = new ArrayList<>(config.getManagedRepositories());
    for (ManagedRepositoryConfiguration f : f1) {
        config.removeManagedRepository(f);
    }
    assertEquals(0, config.getManagedRepositories().size());
    // add internal repo
    config.addManagedRepository(
            createManagedRepository(REPOID_INTERNAL, "Internal Test Repo", repoRootInternal.getRoot()));

    saveConfiguration(archivaConfiguration);

    CacheManager.getInstance().clearAll();

    servletAuthControl = EasyMock.createControl();

    servletAuth = servletAuthControl.createMock(ServletAuthenticator.class);

    httpAuthControl = EasyMock.createControl();

    httpAuth = httpAuthControl.createMock(HttpAuthenticator.class);

    davSessionProvider = new ArchivaDavSessionProvider(servletAuth, httpAuth);

    final MockServletContext mockServletContext = new MockServletContext();

    WebApplicationContext webApplicationContext = new AbstractRepositoryServletTestCase.TestWebapplicationContext(
            applicationContext, mockServletContext);

    mockServletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
            webApplicationContext);

    MockServletConfig mockServletConfig = new MockServletConfig() {
        @Override
        public ServletContext getServletContext() {
            return mockServletContext;
        }
    };

    servlet = new RepositoryServlet();

    servlet.init(mockServletConfig);
}

From source file:org.apache.pluto.driver.PortalStartupListener.java

/**
 * Receives the startup notification and subsequently starts up the portal
 * driver. The following are done in this order:
 * <ol>/* w ww.jav  a 2  s.  c o  m*/
 * <li>Retrieve the ResourceConfig File</li>
 * <li>Parse the ResourceConfig File into ResourceConfig Objects</li>
 * <li>Create a Portal Context</li>
 * <li>Create the ContainerServices implementation</li>
 * <li>Create the Portlet Container</li>
 * <li>Initialize the Container</li>
 * <li>Bind the configuration to the ServletContext</li>
 * <li>Bind the container to the ServletContext</li>
 * <ol>
 *
 * @param event the servlet context event.
 */
public void contextInitialized(ServletContextEvent event) {
    LOG.info("Starting up Pluto Portal Driver. . .");

    ServletContext servletContext = event.getServletContext();

    WebApplicationContext springContext = null;

    try {
        springContext = (WebApplicationContext) servletContext
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    } catch (RuntimeException ex) {
        String msg = "Problem getting Spring context: " + ex.getMessage();
        LOG.error(msg, ex);
        throw ex;
    }

    LOG.debug(" [1a] Loading DriverConfiguration. . . ");
    DriverConfiguration driverConfiguration = (DriverConfiguration) springContext
            .getBean("DriverConfiguration");

    driverConfiguration.init(servletContext);

    LOG.debug(" [1b] Registering DriverConfiguration. . .");
    servletContext.setAttribute(DRIVER_CONFIG_KEY, driverConfiguration);

    LOG.debug(" [2a] Loading Optional AdminConfiguration. . .");
    AdminConfiguration adminConfiguration = (AdminConfiguration) springContext.getBean("AdminConfiguration");

    if (adminConfiguration != null) {
        LOG.debug(" [2b] Registering Optional AdminConfiguration");
        servletContext.setAttribute(ADMIN_CONFIG_KEY, adminConfiguration);
    } else {
        LOG.info("Optional AdminConfiguration not found. Ignoring.");
    }

    //        LOG.debug(" [3a] Loading VWBConfiguration. . .");
    //        VWBConfiguration vwbconfig = (VWBConfiguration)springContext.getBean("VWBConfiguration");
    //        vwbconfig.init(servletContext);

    //        LOG.debug(" [3b] Registering VWBConfiguration. . .");
    //        servletContext.setAttribute(VWB_CONFIG_KEY, vwbconfig);
    //        PortalSessionServiceImpl.init(vwbconfig);

    initContainer(servletContext);

    LOG.info("********** Pluto Portal Driver Started **********\n\n");
}

From source file:org.apache.pluto.driver.PortalStartupListener.java

/**
 * Initializes the portlet container. This method constructs and initializes
 * the portlet container, and saves it to the servlet context scope.
 *
 * @param servletContext the servlet context.
 *//*  w  w  w. j  av a2  s.  c  o m*/
private void initContainer(ServletContext servletContext) {

    WebApplicationContext springContext = (WebApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    // Retrieve the driver configuration from servlet context.
    DriverConfiguration driverConfig = (DriverConfiguration) servletContext.getAttribute(DRIVER_CONFIG_KEY);

    try {
        LOG.info("Initializing Portlet Container. . .");

        LOG.debug(" [1] Loading RequiredContainerServices. . .");
        RequiredContainerServices required = (RequiredContainerServices) springContext
                .getBean("RequiredContainerServices");

        LOG.debug(" [2] Loading OptionalContainerServices. . .");
        OptionalContainerServices optional = (OptionalContainerServices) springContext
                .getBean("OptionalContainerServices");

        // Create portlet container.
        LOG.debug(" [3] Creating portlet container...");
        PortletContainerFactory factory = PortletContainerFactory.getInstance();
        PortletContainer container = factory.createContainer(driverConfig.getContainerName(), required,
                optional);

        // Initialize portlet container.
        LOG.debug(" [4] Initializing portlet container...");
        container.init();

        // Save portlet container to the servlet context scope.
        servletContext.setAttribute(CONTAINER_KEY, container);
        LOG.info("Pluto portlet container started.");

    } catch (DriverConfigurationException ex) {
        LOG.error("Unable to retrieve driver configuration " + "due to configuration error: " + ex.getMessage(),
                ex);
    } catch (PortletContainerException ex) {
        LOG.error("Unable to start up portlet container: " + ex.getMessage(), ex);
    }
}

From source file:org.apache.struts2.spring.StrutsSpringObjectFactory.java

/**
 * Constructs the spring object factory//  w  ww.  j av a2  s.  c  o m
 * @param autoWire The type of autowiring to use
 * @param alwaysAutoWire Whether to always respect the autowiring or not
 * @param useClassCacheStr Whether to use the class cache or not
 * @param servletContext The servlet context
 * @since 2.1.3
 */
@Inject
public StrutsSpringObjectFactory(
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE, required = false) String autoWire,
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE_ALWAYS_RESPECT, required = false) String alwaysAutoWire,
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_USE_CLASS_CACHE, required = false) String useClassCacheStr,
        @Inject ServletContext servletContext, @Inject(StrutsConstants.STRUTS_DEVMODE) String devMode,
        @Inject Container container) {

    super();
    boolean useClassCache = "true".equals(useClassCacheStr);
    if (LOG.isInfoEnabled()) {
        LOG.info("Initializing Struts-Spring integration...");
    }

    Object rootWebApplicationContext = servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    if (rootWebApplicationContext instanceof RuntimeException) {
        RuntimeException runtimeException = (RuntimeException) rootWebApplicationContext;
        LOG.fatal(runtimeException.getMessage());
        return;
    }

    ApplicationContext appContext = (ApplicationContext) rootWebApplicationContext;
    if (appContext == null) {
        // uh oh! looks like the lifecycle listener wasn't installed. Let's inform the user
        String message = "********** FATAL ERROR STARTING UP STRUTS-SPRING INTEGRATION **********\n"
                + "Looks like the Spring listener was not configured for your web app! \n"
                + "Nothing will work until WebApplicationContextUtils returns a valid ApplicationContext.\n"
                + "You might need to add the following to web.xml: \n" + "    <listener>\n"
                + "        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>\n"
                + "    </listener>";
        LOG.fatal(message);
        return;
    }

    String watchList = container.getInstance(String.class, "struts.class.reloading.watchList");
    String acceptClasses = container.getInstance(String.class, "struts.class.reloading.acceptClasses");
    String reloadConfig = container.getInstance(String.class, "struts.class.reloading.reloadConfig");

    if ("true".equals(devMode) && StringUtils.isNotBlank(watchList)
            && appContext instanceof ClassReloadingXMLWebApplicationContext) {
        //prevent class caching
        useClassCache = false;

        ClassReloadingXMLWebApplicationContext reloadingContext = (ClassReloadingXMLWebApplicationContext) appContext;
        reloadingContext.setupReloading(watchList.split(","), acceptClasses, servletContext,
                "true".equals(reloadConfig));
        if (LOG.isInfoEnabled()) {
            LOG.info("Class reloading is enabled. Make sure this is not used on a production environment!",
                    watchList);
        }

        setClassLoader(reloadingContext.getReloadingClassLoader());

        //we need to reload the context, so our isntance of the factory is picked up
        reloadingContext.refresh();
    }

    this.setApplicationContext(appContext);

    int type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; // default
    if ("name".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
    } else if ("type".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
    } else if ("auto".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
    } else if ("constructor".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
    } else if ("no".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_NO;
    }
    this.setAutowireStrategy(type);

    this.setUseClassCache(useClassCache);

    this.setAlwaysRespectAutowireStrategy("true".equalsIgnoreCase(alwaysAutoWire));

    if (LOG.isInfoEnabled()) {
        LOG.info("... initialized Struts-Spring integration successfully");
    }
}

From source file:org.broadleafcommerce.test.BroadleafGenericGroovyXmlWebContextLoader.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   w ww  .ja  v  a  2 s . c o  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 MergeXmlWebApplicationContext} is then stored in
 * the {@code MockServletContext} under the
 * {@link MergeXmlWebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} key.</li>
 * <li>Finally, the {@code MockServletContext} is set in the
 * {@code MergeXmlWebApplicationContext}.</li>
 *
 * @param context the merge xml web application context for which to configure the web
 * resources
 * @param webMergedConfig the merged context configuration to use to load the
 * merge xml web application context
 */
protected void configureWebResources(MergeXmlWebApplicationContext context,
        WebMergedContextConfiguration webMergedConfig) {

    ApplicationContext parent = context.getParent();

    // if the WAC has no parent or the parent is not a WAC, set the WAC as
    // 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 MergeXmlWebApplicationContext in the context hierarchy");
        context.setServletContext(servletContext);
    }
}

From source file:org.codehaus.groovy.grails.web.context.GrailsConfigUtils.java

public static void configureServletContextAttributes(ServletContext servletContext,
        GrailsApplication application, GrailsPluginManager pluginManager, WebApplicationContext webContext) {
    servletContext.setAttribute(ApplicationAttributes.PLUGIN_MANAGER, pluginManager);
    // use config file locations if available
    servletContext.setAttribute(ApplicationAttributes.PARENT_APPLICATION_CONTEXT, webContext.getParent());
    servletContext.setAttribute(GrailsApplication.APPLICATION_ID, application);

    servletContext.setAttribute(ApplicationAttributes.APPLICATION_CONTEXT, webContext);
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext);
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPagesServlet.java

public GroovyPagesServlet() {
    // use the root web application context always
    setContextAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
}

From source file:org.dataconservancy.ui.stripes.AddCollectionActionBeanTest.java

@Test
public void testPollExpirationOnDepositReturnsCorrectHttpErrorCodeAndMessage() throws Exception {

    // Construct our own ArchiveService instance; this is because Spring will return a Proxied instance
    // of ArchiveService, which Mockito won't be able to spy(...) on.
    final ArchiveService notProxiedArchiveService = new InMemoryArchiveServiceImpl(mockDatasetMapper,
            dataItemProfile, mockCollectionMapper, mockMetadataFileMapper, mockDatafileMapper,
            metadataFormatRegistryEntryMapper, mockDepositDocumentResolver, mockArchiveUtil, uiIdService, false,
            mockArchiveDepositInfoDAO);/*from   www  . j  a  v a  2 s.c  o  m*/

    // Create a mock ArchiveService that behaves like the real ArchiveService, except we override the
    // pollArchive() method to do nothing.  Effectively this means that deposit status will never be updated.
    final ArchiveService pollsForever = spy(notProxiedArchiveService);
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            log.debug("Invoking a mock ArchiveService.pollArchive(); impl is a no-op, so deposit statuses will "
                    + "never be updated.");
            return null;
        }
    }).when(pollsForever).pollArchive();

    // Inject the mocked archiveService into the spring context
    GenericWebApplicationContext springContext = (GenericWebApplicationContext) servletCtx
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    springContext.getBeanFactory().registerSingleton("archiveService", pollsForever);
    servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, springContext);

    // Fix up the collaborating Project
    Project project = new Project();
    project.setId("project:/2341");
    project.setStartDate(DateTime.now());
    project.setEndDate(DateTime.now());
    projectDao.insertProject(project);
    adminSession.setAttribute("projectId", project.getId());

    MockRoundtrip rt = new MockRoundtrip(servletCtx, AddCollectionActionBean.class, adminSession);

    rt.addParameter("collection.title", modifiedCollection.getTitle());
    rt.addParameter("collection.summary", modifiedCollection.getSummary());
    rt.addParameter("collection.citableLocator", modifiedCollection.getCitableLocator());
    rt.addParameter("collection.publicationDate", modifiedCollection.getPublicationDate().toString());
    rt.addParameter("collection.alternateIds[0]", (String) modifiedCollection.getAlternateIds().toArray()[0]);
    rt.addParameter("collection.alternateIds[1]", (String) modifiedCollection.getAlternateIds().toArray()[1]);
    rt.addParameter("collection.creators[0].prefixes", modifiedCollection.getCreators().get(0).getPrefixes());
    rt.addParameter("collection.creators[0].givenNames",
            modifiedCollection.getCreators().get(0).getGivenNames());
    rt.addParameter("collection.creators[0].middleNames",
            modifiedCollection.getCreators().get(0).getMiddleNames());
    rt.addParameter("collection.creators[0].familyNames",
            modifiedCollection.getCreators().get(0).getFamilyNames());
    rt.addParameter("collection.creators[0].suffixes", modifiedCollection.getCreators().get(0).getSuffixes());

    // Attempt to deposit the collection; this should fail because the pollForever archive service will never
    // update the deposit status.
    rt.execute("addCollection");

    final MockHttpServletResponse response = rt.getResponse();
    assertEquals(302, response.getStatus());
}

From source file:org.devproof.portal.test.MockContextLoader.java

@Override
public ConfigurableApplicationContext loadContext(String... locations) throws Exception {
    registerResource(CommonConstants.JNDI_MAIL_SESSION, Session.getDefaultInstance(new Properties()));
    registerResource(CommonConstants.JNDI_PROP_EMAIL_DISABLED, "true");
    registerResource(CommonConstants.JNDI_PROP_HIBERNATE_DIALECT, "org.hibernate.dialect.H2Dialect");
    registerResource(CommonConstants.JNDI_PROP_HIBERNATE_SECOND_LEVEL_CACHE, "false");
    registerResource(CommonConstants.JNDI_PROP_HIBERNATE_QUERY_CACHE, "false");
    ConfigurableWebApplicationContext context = new XmlWebApplicationContext();
    MockServletContext servletContext = new MockServletContext("") {
        @Override/*  ww  w.  j a v a  2 s .c o  m*/
        public String getRealPath(String arg0) {
            return System.getProperty("java.io.tmpdir");
        }
    };
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
    context.setServletContext(servletContext);
    String[] configLocations = PortalContextLoaderListener.locateConfigLocations(locations);
    context.setConfigLocations(configLocations);
    context.refresh();
    context.registerShutdownHook();
    return context;
}

From source file:org.esupportail.commons.batch.WebApplicationEnvironment.java

/**
 * Load context locations.//from w w  w  .ja  v a  2 s  .c om
 * @param locations : new String[]{ "classpath:properties/applicationContext.xml" } for example
 * @return the ApplicationContext loaded
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public ConfigurableApplicationContext loadContextLocations(final String[] locations) throws Exception {

    if (log.isInfoEnabled()) {
        log.info("Loading web application context for: " + StringUtils.arrayToCommaDelimitedString(locations));
    }

    XmlWebApplicationContext ctx = new XmlWebApplicationContext();
    ctx.setConfigLocations(locations);
    ctx.setServletContext(context);
    ctx.refresh();

    MockExternalContext externalContext = (MockExternalContext) facesContext.getExternalContext();
    Map applicationMap = new HashMap();
    applicationMap.put(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
    externalContext.setApplicationMap(applicationMap);

    context.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);

    ContextUtils.bindRequestAndContext(request, context);

    return ctx;
}