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.geoserver.test.GeoServerAbstractTestSupport.java

/**
 * If subclasses override they *must* call super.setUp() first.
 *//*  w w w  .j  a v  a 2  s.  c  o m*/
@Override
protected void oneTimeSetUp() throws Exception {
    // do we need to reset the referencing subsystem and reorient it with lon/lat order?
    if (System.getProperty("org.geotools.referencing.forceXY") == null
            || !"http".equals(Hints.getSystemDefault(Hints.FORCE_AXIS_ORDER_HONORING))) {
        System.setProperty("org.geotools.referencing.forceXY", "true");
        Hints.putSystemDefault(Hints.FORCE_AXIS_ORDER_HONORING, "http");
        CRS.reset("all");
    }

    // reset security services
    //GeoserverServiceFactory.Singleton.reset();

    // set up test data 
    testData = buildTestData();
    testData.setUp();

    // setup quiet logging (we need to to this here because Data
    // is loaded before GoeServer has a chance to setup logging for good)
    try {
        Logging.ALL.setLoggerFactory(Log4JLoggerFactory.getInstance());
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Could not configure log4j logging redirection", e);
    }
    System.setProperty(LoggingUtils.RELINQUISH_LOG4J_CONTROL, "true");
    GeoServerResourceLoader loader = new GeoServerResourceLoader(testData.getDataDirectoryRoot());
    LoggingUtils.configureGeoServerLogging(loader, getClass().getResourceAsStream(getLogConfiguration()), false,
            true, null);

    //HACK: once we port tests to the new data directory, remove this
    GeoServerLoader.setLegacy(useLegacyDataDirectory());

    // if we have data, create a mock servlet context and start up the spring configuration
    if (testData.isTestDataAvailable()) {
        MockServletContext servletContext = new MockServletContext();
        servletContext.setInitParameter("GEOSERVER_DATA_DIR", testData.getDataDirectoryRoot().getPath());
        servletContext.setInitParameter("serviceStrategy", "PARTIAL-BUFFER2");

        //set up a fake WEB-INF directory
        if (testData.getDataDirectoryRoot().canWrite()) {
            File webinf = new File(testData.getDataDirectoryRoot(), "WEB-INF");
            webinf.mkdir();

            servletContext.setRealPath("WEB-INF", webinf.getAbsolutePath());
        }

        applicationContext = new GeoServerTestApplicationContext(getSpringContextLocations(), servletContext);
        applicationContext.setUseLegacyGeoServerLoader(useLegacyDataDirectory());
        applicationContext.refresh();
        applicationContext.publishEvent(new ContextLoadedEvent(applicationContext));

        // set the parameter after a refresh because it appears a refresh
        // wipes
        // out all parameters
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                applicationContext);
    }
}

From source file:org.geoserver.test.GeoServerSystemTestSupport.java

protected final void setUp(SystemTestData testData) throws Exception {
    // setup quiet logging (we need to to this here because Data
    // is loaded before GoeServer has a chance to setup logging for good)
    try {//  w  ww  . j av a2 s .c  om
        Logging.ALL.setLoggerFactory(Log4JLoggerFactory.getInstance());
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Could not configure log4j logging redirection", e);
    }
    System.setProperty(LoggingUtils.RELINQUISH_LOG4J_CONTROL, "true");
    GeoServerResourceLoader loader = new GeoServerResourceLoader(testData.getDataDirectoryRoot());
    LoggingUtils.configureGeoServerLogging(loader, getClass().getResourceAsStream(getLogConfiguration()), false,
            true, null);

    setUpTestData(testData);

    // put the mock http server in test mode
    TestHttpClientProvider.startTest();

    // if we have data, create a mock servlet context and start up the spring configuration
    if (testData.isTestDataAvailable()) {
        MockServletContext servletContext = new MockServletContext();
        servletContext.setInitParameter("GEOSERVER_DATA_DIR", testData.getDataDirectoryRoot().getPath());
        servletContext.setInitParameter("serviceStrategy", "PARTIAL-BUFFER2");

        //set up a fake WEB-INF directory
        if (testData.getDataDirectoryRoot().canWrite()) {
            File webinf = new File(testData.getDataDirectoryRoot(), "WEB-INF");
            webinf.mkdir();

            servletContext.setRealPath("WEB-INF", webinf.getAbsolutePath());
        }

        List<String> contexts = new ArrayList();
        setUpSpring(contexts);

        applicationContext = new GeoServerTestApplicationContext(contexts.toArray(new String[contexts.size()]),
                servletContext);
        applicationContext.setUseLegacyGeoServerLoader(false);
        applicationContext.refresh();
        applicationContext.publishEvent(new ContextLoadedEvent(applicationContext));

        // set the parameter after a refresh because it appears a refresh
        // wipes
        // out all parameters
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                applicationContext);

        onSetUp(testData);
    }
}

From source file:org.hdiv.AbstractHDIVTestCase.java

protected final void setUp() throws Exception {

    String[] files = { "/org/hdiv/config/hdiv-core-applicationContext.xml", "/org/hdiv/config/hdiv-config.xml",
            "/org/hdiv/config/hdiv-validations.xml", "/org/hdiv/config/applicationContext-test.xml",
            "/org/hdiv/config/applicationContext-extra.xml" };

    if (this.applicationContext == null) {
        this.applicationContext = new ClassPathXmlApplicationContext(files);
    }/*from  w  w  w. j  a  v  a2 s  . c  o  m*/

    // Servlet API mock
    HttpServletRequest request = (MockHttpServletRequest) this.applicationContext.getBean("mockRequest");
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    HDIVUtil.setHttpServletRequest(request);

    // Put Spring context on ServletContext
    StaticWebApplicationContext webApplicationContext = new StaticWebApplicationContext();
    webApplicationContext.setServletContext(servletContext);
    webApplicationContext.setParent(this.applicationContext);
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
            webApplicationContext);

    // Initialize config
    this.config = (HDIVConfig) this.applicationContext.getBean("config");

    InitListener initListener = new InitListener();
    // Initialize ServletContext
    ServletContextEvent servletContextEvent = new ServletContextEvent(servletContext);
    initListener.contextInitialized(servletContextEvent);
    // Initialize HttpSession
    HttpSessionEvent httpSessionEvent = new HttpSessionEvent(httpSession);
    initListener.sessionCreated(httpSessionEvent);
    // Initialize request
    ServletRequestEvent requestEvent = new ServletRequestEvent(servletContext, request);
    initListener.requestInitialized(requestEvent);

    if (log.isDebugEnabled()) {
        log.debug("Hdiv test context initialized");
    }

    onSetUp();
}

From source file:org.hdiv.hateoas.jackson.AbstractHDIVTestCase.java

protected void setUp() throws Exception {

    String[] files = { "/org/hdiv/config/hdiv-core-applicationContext.xml", "/org/hdiv/config/hdiv-config.xml",
            "/org/hdiv/config/hdiv-validations.xml", "/org/hdiv/config/applicationContext-test.xml",
            "/org/hdiv/config/applicationContext-extra.xml" };

    if (this.applicationContext == null) {
        this.applicationContext = new ClassPathXmlApplicationContext(files);
    }//from   ww  w  .j  ava 2  s.co  m

    // Servlet API mock
    HttpServletRequest request = (MockHttpServletRequest) this.applicationContext.getBean("mockRequest");
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    HDIVUtil.setHttpServletRequest(request);

    // Put Spring context on ServletContext
    StaticWebApplicationContext webApplicationContext = new StaticWebApplicationContext();
    webApplicationContext.setServletContext(servletContext);
    webApplicationContext.setParent(this.applicationContext);
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
            webApplicationContext);

    // Initialize config
    this.config = (HDIVConfig) this.applicationContext.getBean("config");

    InitListener initListener = new InitListener();
    // Initialize ServletContext
    ServletContextEvent servletContextEvent = new ServletContextEvent(servletContext);
    initListener.contextInitialized(servletContextEvent);
    // Initialize HttpSession
    HttpSessionEvent httpSessionEvent = new HttpSessionEvent(httpSession);
    initListener.sessionCreated(httpSessionEvent);
    // Initialize request
    ServletRequestEvent requestEvent = new ServletRequestEvent(servletContext, request);
    initListener.requestInitialized(requestEvent);

    if (log.isDebugEnabled()) {
        log.debug("Hdiv test context initialized");
    }

    onSetUp();
}

From source file:org.impalaframework.web.spring.module.BaseWebModuleLoader.java

@Override
public void handleRefresh(String applicationId, ConfigurableApplicationContext context,
        ModuleDefinition moduleDefinition) {

    Assert.notNull(webAttributeQualifier, "webAttributeQualifier cannot be null");
    String applicationContextAttributeName = webAttributeQualifier.getQualifiedAttributeName(
            WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationId,
            moduleDefinition.getName());
    String servletContextAttributeName = webAttributeQualifier.getQualifiedAttributeName(
            SERVLET_CONTEXT_ATTRIBUTE_NAME, applicationId, moduleDefinition.getName());

    try {/*from  w  w  w  .  j av a  2s.com*/
        servletContext.setAttribute(applicationContextAttributeName, context);
        doHandleRefresh(applicationId, context, moduleDefinition);
    } catch (RuntimeException e) {
        logger.error(e.getMessage(), e);
        servletContext.removeAttribute(applicationContextAttributeName);
        servletContext.removeAttribute(servletContextAttributeName);
        throw e;
    } catch (Throwable e) {
        servletContext.removeAttribute(applicationContextAttributeName);
        servletContext.removeAttribute(servletContextAttributeName);
        throw new ExecutionException(e.getMessage(), e);
    }
}

From source file:org.impalaframework.web.spring.module.BaseWebModuleLoader.java

@Override
public void beforeClose(String applicationId, ApplicationContext applicationContext,
        ModuleDefinition moduleDefinition) {
    String servletContextAttributeName = getQualifiedAttributeName(SERVLET_CONTEXT_ATTRIBUTE_NAME,
            applicationId, moduleDefinition.getName());
    servletContext.removeAttribute(servletContextAttributeName);

    String applicationContextAttributeName = getQualifiedAttributeName(
            WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationId,
            moduleDefinition.getName());
    servletContext.removeAttribute(applicationContextAttributeName);
}

From source file:org.mule.config.builders.DeployableMuleXmlContextListener.java

public void initialize(ServletContext context) {
    String config = context.getInitParameter(MuleXmlBuilderContextListener.INIT_PARAMETER_MULE_CONFIG);
    if (config == null) {
        config = MuleServer.DEFAULT_CONFIGURATION;
        if (logger.isDebugEnabled()) {
            logger.debug("No Mule config file(s) specified, using default: " + config);
        }// ww  w. j  av  a2 s  .co  m
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Mule config file(s): " + config);
        }
    }

    if (muleContext == null) {
        throw new RuntimeException("MuleContext is not available");
    }

    try {
        configurationBuilder = new WebappMuleXmlConfigurationBuilder(context, config);
        configurationBuilder.setUseDefaultConfigResource(false);

        // Support Spring-first configuration in webapps
        final ApplicationContext parentContext = (ApplicationContext) context
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        if (parentContext != null) {
            configurationBuilder.setParentContext(parentContext);
        }
        configurationBuilder.configure(muleContext);
    } catch (MuleException ex) {
        context.log(ex.getMessage(), ex);
        // Logging is not configured OOTB for Tomcat, so we'd better make a
        // start-up failure plain to see.
        ex.printStackTrace();
    } catch (Error error) {
        // WSAD doesn't always report the java.lang.Error, log it
        context.log(error.getMessage(), error);
        // Logging is not configured OOTB for Tomcat, so we'd better make a
        // start-up failure plain to see.
        error.printStackTrace();
        throw error;
    }
}

From source file:org.mule.config.builders.MuleXmlBuilderContextListener.java

/**
 * Creates the MuleContext based on the configuration resource(s) and possibly 
 * init parameters for the Servlet./* w ww  . j a va2s . c  o m*/
 */
protected MuleContext createMuleContext(String configResource, ServletContext servletContext)
        throws ConfigurationException, InitialisationException {
    String serverId = StringUtils.defaultIfEmpty(servletContext.getInitParameter("mule.serverId"), null);

    // serverId will be used as a sub-folder in Mule working directory (.mule)

    if (serverId == null) {
        // guess this app's context name from the temp/work dir the container created us
        // Servlet 2.5 has servletContext.getContextPath(), but we can't force users to upgrade yet
        final File tempDir = (File) servletContext.getAttribute(ATTR_JAVAX_SERVLET_CONTEXT_TEMPDIR);
        final String contextName = FilenameUtils.getBaseName(tempDir.toString());
        serverId = contextName;
    }

    WebappMuleXmlConfigurationBuilder builder = new WebappMuleXmlConfigurationBuilder(servletContext,
            configResource);
    MuleContextFactory muleContextFactory = new DefaultMuleContextFactory();

    String muleAppConfig = servletContext.getInitParameter(INIT_PARAMETER_MULE_APP_CONFIG) != null
            ? servletContext.getInitParameter(INIT_PARAMETER_MULE_APP_CONFIG)
            : PropertiesMuleConfigurationFactory.getMuleAppConfiguration(configResource);

    DefaultMuleConfiguration muleConfiguration = new PropertiesMuleConfigurationFactory(muleAppConfig)
            .createConfiguration();

    /*
    We deliberately enable container mode here to allow for multi-tenant environment (multiple WARs
    embedding Mule instance each). See property javadocs for more info.
     */
    muleConfiguration.setContainerMode(true);

    if (serverId != null) {
        muleConfiguration.setId(serverId);
    }
    MuleContextBuilder muleContextBuilder = new DefaultMuleContextBuilder();
    muleContextBuilder.setMuleConfiguration(muleConfiguration);

    // Support Spring-first configuration in webapps
    final ApplicationContext parentContext = (ApplicationContext) servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (parentContext != null) {
        builder.setParentContext(parentContext);
    }
    return muleContextFactory.createMuleContext(builder, muleContextBuilder);
}

From source file:org.openmrs.web.Listener.java

/**
 * This method is called when the servlet context is initialized(when the Web Application is
 * deployed). You can initialize servlet context related data here.
 *
 * @param event/*from w  ww .ja v a  2 s .c o  m*/
 */
@Override
public void contextInitialized(ServletContextEvent event) {
    Log log = LogFactory.getLog(Listener.class);

    log.debug("Starting the OpenMRS webapp");

    try {
        // validate the current JVM version
        OpenmrsUtil.validateJavaVersion();

        ServletContext servletContext = event.getServletContext();

        // pulled from web.xml.
        loadConstants(servletContext);

        // erase things in the dwr file
        clearDWRFile(servletContext);

        // Try to get the runtime properties
        Properties props = getRuntimeProperties();
        if (props != null) {
            // the user has defined a runtime properties file
            setRuntimePropertiesFound(true);
            // set props to the context so that they can be
            // used during sessionFactory creation
            Context.setRuntimeProperties(props);
        }

        Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());

        if (!setupNeeded()) {
            // must be done after the runtime properties are
            // found but before the database update is done
            copyCustomizationIntoWebapp(servletContext, props);

            //super.contextInitialized(event);
            // also see commented out line in contextDestroyed

            /** This logic is from ContextLoader.initWebApplicationContext.
             * Copied here instead of calling that so that the context is not cached
             * and hence not garbage collected
             */
            XmlWebApplicationContext context = (XmlWebApplicationContext) createWebApplicationContext(
                    servletContext);
            configureAndRefreshWebApplicationContext(context, servletContext);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);

            WebDaemon.startOpenmrs(event.getServletContext());
        } else {
            setupNeeded = true;
        }

    } catch (Exception e) {
        setErrorAtStartup(e);
        log.fatal("Got exception while starting up: ", e);
    }

}

From source file:org.red5.server.net.rtmpt.RTMPTServlet.java

/**
 * Main entry point for the servlet./*from  ww w  . j  a v  a 2  s. c  om*/
 * 
 * @param req
 *            Request object
 * @param resp
 *            Response object
 * @throws IOException
 *             I/O exception
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    if (applicationContext == null) {
        ServletContext ctx = getServletContext();
        applicationContext = WebApplicationContextUtils.getWebApplicationContext(ctx);
        if (applicationContext == null) {
            applicationContext = (WebApplicationContext) ctx
                    .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        }
        log.debug("Application context: {}", applicationContext);
        // ensure we have a connection manager
        if (manager == null) {
            log.warn("Class instance connection manager was null, looking up in application context");
            manager = (RTMPConnManager) applicationContext.getBean("rtmpConnManager");
            if (manager == null) {
                log.warn("Connection manager was null in context, getting class instance");
                manager = RTMPConnManager.getInstance();
                if (manager == null) {
                    log.error("Connection manager is still null, this is bad");
                }
            }
        }
    }
    log.debug("Request - method: {} content type: {} path: {}",
            new Object[] { req.getMethod(), req.getContentType(), req.getServletPath() });
    // allow only POST requests with valid content length
    if (!REQUEST_METHOD.equals(req.getMethod()) || req.getContentLength() == 0) {
        // Bad request - return simple error page
        handleBadRequest("Bad request, only RTMPT supported.", resp);
        return;
    }
    // decide whether or not to enforce request content checks
    if (enforceContentTypeCheck && !CONTENT_TYPE.equals(req.getContentType())) {
        handleBadRequest(String.format("Bad request, unsupported content type: %s.", req.getContentType()),
                resp);
        return;
    }
    // get the uri
    String uri = req.getRequestURI().trim();
    log.debug("URI: {}", uri);
    // get the path
    String path = req.getServletPath();
    // since the only current difference in the type of request that we are interested in is the 'second' character, we can double
    // the speed of this entry point by using a switch on the second character.
    char p = path.charAt(1);
    switch (p) {
    case 'o': // OPEN_REQUEST
        handleOpen(req, resp);
        break;
    case 'c': // CLOSE_REQUEST
        setRequestInfo(req);
        handleClose(req, resp);
        requestInfo.remove();
        break;
    case 's': // SEND_REQUEST
        setRequestInfo(req);
        handleSend(req, resp);
        requestInfo.remove();
        break;
    case 'i': // IDLE_REQUEST
        setRequestInfo(req);
        handleIdle(req, resp);
        requestInfo.remove();
        break;
    case 'f': // HTTPIdent request (ident and ident2)
        //if HTTPIdent is requested send back some Red5 info
        //http://livedocs.adobe.com/flashmediaserver/3.0/docs/help.html?content=08_xmlref_011.html         
        String ident = "<fcs><Company>Red5</Company><Team>Red5 Server</Team></fcs>";
        // handle ident2 slightly different to appease osx clients
        if (uri.charAt(uri.length() - 1) == '2') {
            // check for pre-configured ident2 value
            if (ident2 != null) {
                ident = ident2;
            } else {
                // just send 404 back if no ident2 value is set
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                resp.setHeader("Connection", "Keep-Alive");
                resp.setHeader("Cache-Control", "no-cache");
                resp.flushBuffer();
                break;
            }
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setHeader("Connection", "Keep-Alive");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setContentType(CONTENT_TYPE);
        resp.setContentLength(ident.length());
        resp.getWriter().write(ident);
        resp.flushBuffer();
        break;
    default:
        handleBadRequest(String.format("RTMPT command %s is not supported.", path), resp);
    }
    // clear thread local reference
    Red5.setConnectionLocal(null);
}