Example usage for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext

List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext

Introduction

In this page you can find the example usage for org.springframework.web.context.support WebApplicationContextUtils getWebApplicationContext.

Prototype

@Nullable
public static WebApplicationContext getWebApplicationContext(ServletContext sc) 

Source Link

Document

Find the root WebApplicationContext for this web app, typically loaded via org.springframework.web.context.ContextLoaderListener .

Usage

From source file:com.github.peholmst.springsecuritydemo.servlet.SpringApplicationServlet.java

@SuppressWarnings("unchecked")
@Override/*  ww w. j av  a  2s. com*/
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    /*
     * Look up the name of the Vaadin application bean. The bean should be
     * either a prototype or have session scope.
     */
    applicationBean = servletConfig.getInitParameter("applicationBean");
    if (applicationBean == null) {
        if (logger.isErrorEnabled()) {
            logger.error("ApplicationBean not specified in servlet parameters");
        }
        throw new ServletException("ApplicationBean not specified in servlet parameters");
    }

    if (logger.isInfoEnabled()) {
        logger.info("Using applicationBean '" + applicationBean + "'");
    }

    /*
     * Fetch the Spring web application context
     */
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());

    if (applicationContext.isSingleton(applicationBean)) {
        if (logger.isErrorEnabled()) {
            logger.error("ApplicationBean must not be a singleton");
        }
        throw new ServletException("ApplicationBean must not be a singleton");
    }
    if (!applicationContext.isPrototype(applicationBean) && logger.isWarnEnabled()) {
        logger.warn("ApplicationBean is not a prototype");
    }

    /*
     * Get the application class from the application context
     */
    applicationClass = (Class<? extends Application>) applicationContext.getType(applicationBean);
    if (logger.isDebugEnabled()) {
        logger.debug("Vaadin application class is [" + applicationClass + "]");
    }
    /*
     * Initialize the locale resolver
     */
    initLocaleResolver(applicationContext);
}

From source file:nl.jeslee.jersey.server.spring.SpringComponentProvider.java

@Override
public void initialize(ServiceLocator locator) {
    this.locator = locator;

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(LocalizationMessages.CTX_LOOKUP_STARTED());
    }/*from   w  w w .j  a  va  2s .  com*/

    ServletContext sc = locator.getService(ServletContext.class);

    if (sc != null) {
        // servlet container
        ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
    } else {
        // non-servlet container
        ctx = createSpringContext();
    }
    if (ctx == null) {
        LOGGER.severe(LocalizationMessages.CTX_LOOKUP_FAILED());
        return;
    }
    LOGGER.config(LocalizationMessages.CTX_LOOKUP_SUCESSFUL());

    // initialize HK2 spring-bridge
    SpringBridge.getSpringBridge().initializeSpringBridge(locator);
    SpringIntoHK2Bridge springBridge = locator.getService(SpringIntoHK2Bridge.class);
    springBridge.bridgeSpringBeanFactory(ctx);

    // register Spring @Autowired annotation handler with HK2 ServiceLocator
    ServiceLocatorUtilities.addOneConstant(locator, new AutowiredInjectResolver(ctx));
    ServiceLocatorUtilities.addOneConstant(locator, ctx, "SpringContext", ApplicationContext.class);
    LOGGER.config(LocalizationMessages.SPRING_COMPONENT_PROVIDER_INITIALIZED());
}

From source file:org.openmeetings.servlet.outputhandler.Export.java

public UsersDaoImpl getUsersDao() {
    try {//  www . ja  va  2s.  c o  m
        if (ScopeApplicationAdapter.initComplete) {
            ApplicationContext context = WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext());
            return (UsersDaoImpl) context.getBean("usersDao");
        }
    } catch (Exception err) {
        log.error("[getUsersDao]", err);
    }
    return null;
}

From source file:org.openmeetings.servlet.outputhandler.CalendarServlet.java

public Usermanagement getUserManagement() {
    try {/*from   w ww.  j  ava2s .  co  m*/
        if (ScopeApplicationAdapter.initComplete) {
            ApplicationContext context = WebApplicationContextUtils
                    .getWebApplicationContext(getServletContext());
            return (Usermanagement) context.getBean("userManagement");
        }
    } catch (Exception err) {
        log.error("[getUserManagement]", err);
    }
    return null;
}

From source file:org.tonguetied.web.servlet.ServletContextInitializer.java

/**
 * Perform server servlet initialization. When the servlet is first 
 * initialized, the server system properties are set. These server 
 * properties are used in the domain layer, but are not known until the web
 * application is deployed and started. Also loads application wide 
 * variables including://from w  ww .ja va2  s . c  om
 * <ul>
 *   <li>the list of supported languages</li>
 * </ul>
 * 
 * This method also performs database management. It determines if this 
 * server should run an embedded database, ie it is in demo mode, and 
 * starts the database. It also creates the database, the first time it 
 * connects to the server.
 *   
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
public void contextInitialized(ServletContextEvent event) {
    loadSupportedLanguages(event.getServletContext());

    WebApplicationContext applicationContext = WebApplicationContextUtils
            .getWebApplicationContext(event.getServletContext());
    AdministrationService administrationService = (AdministrationService) applicationContext
            .getBean("administrationService");
    Properties props = loadProperties(event.getServletContext(), DIR_WEB_INF + "/jdbc.properties");
    final String dialect = props.getProperty(KEY_HIBERNATE_DIALECT);
    if (EmbeddedDatabaseServer.isEmbeddable(dialect))
        EmbeddedDatabaseServer.startDatabase(props);
    ServerData serverData = administrationService.getLatestData();
    // If server data does not exist then assume the database has not been
    // created
    if (serverData == null) {
        if (logger.isDebugEnabled())
            logger.debug("attempting to create database");

        final String[] schemas = loadSchemas(event.getServletContext(), dialect, administrationService);
        administrationService.createDatabase(schemas);
        serverData = createServerData(event.getServletContext());
        if (serverData != null)
            administrationService.saveOrUpdate(serverData);
    }
    // check if we need to update
    else {
        if (logger.isDebugEnabled())
            logger.debug("attempting to update database");

        ServerData curServerData = createServerData(event.getServletContext());
        if (curServerData.compareTo(serverData) > 0) {
            //                final String[] schemas = loadSchemas(event.getServletContext(), dialect, curServerData.getVersion());
            //                administrationService.createDatabase(schemas);
            administrationService.saveOrUpdate(curServerData);
        }
    }
    if (logger.isInfoEnabled()) {
        logger.info("Charset for this JVM: " + Charset.defaultCharset());
    }
}

From source file:com.ewcms.component.counter.web.CounterServlet.java

private CounterServiceable getCountSerivce() {
    ServletContext application = getServletContext();
    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);

    return (CounterServiceable) wac.getBean("counterService");
}

From source file:org.exoplatform.mongo.service.MongoRestServiceTest.java

@Before
public void setUp() throws Exception {
    WebAppContext context = new WebAppContext();
    context.setContextPath("/");
    context.setWar(getWebappDirectory().getAbsolutePath());

    server = new Server(9002);
    server.setHandler(context);/*  www . j a v  a  2  s.  c  o  m*/
    server.setStopAtShutdown(true);
    server.start();

    WebApplicationContextUtils.getWebApplicationContext(context.getServletContext());

    String testUsername = "junit";
    String testPassword = EncodingUtils.encodeBase64("r3$tfuLM0ng0");
    Mongo mongo = (Mongo) AppContext.getApplicationContext().getBean("mongo");
    DB db = mongo.getDB("credentials");
    DBCollection collection = db.getCollection("data_service");
    DBObject credentials = new BasicDBObject();
    credentials.put("user", testUsername);
    credentials.put("password", testPassword);
    collection.insert(credentials);

    clientHandle = ResourceClientFactory.getClientHandle(testUsername, testPassword, 0, 0);
}

From source file:org.apache.tapestry5.internal.spring.SpringModuleDef.java

/**
 * Invoked to obtain the Spring ApplicationContext, presumably stored in the ServletContext.
 * This method is only used in Tapestry 5.0 compatibility mode (in Tapestry 5.1 and above,
 * the default is for Tapestry to <em>create</em> the ApplicationContext).
 *
 * @param servletContext used to locate the ApplicationContext
 * @return the ApplicationContext itself
 * @throws RuntimeException if the ApplicationContext could not be located or is otherwise invalid
 * @since 5.2.0//  w w w  . j  a  va  2  s . c  o m
 */
protected ApplicationContext locateApplicationContext(ServletContext servletContext) {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);

    if (context == null) {
        throw new NullPointerException(String.format(
                "No Spring ApplicationContext stored in the ServletContext as attribute '%s'. "
                        + "You should either re-enable Tapestry as the creator of the ApplicationContext, or "
                        + "add a Spring ContextLoaderListener to web.xml.",
                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
    }

    return context;
}

From source file:org.sarons.spring4me.web.filter.PageFilter.java

protected ConfigurableWebApplicationContext initPageApplicationContext() {
    WebApplicationContext root = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    ////  www  .  j a  v  a  2s . com
    ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils
            .instantiateClass(contextClass);
    wac.setParent(root);
    wac.setServletContext(getServletContext());
    wac.setServletConfig(new DelegatingServletConfig(getServletContext()));
    wac.setNamespace(getNamespace());
    wac.setConfigLocation(getWidgetConfigLocation());
    wac.refresh();
    //
    return wac;
}

From source file:org.spring4gwt.server.SpringGwtRemoteServiceServlet.java

/**
 * Look up a spring bean with the specified name in the current web
 * application context.//from  ww w.ja  va  2s.c  o  m
 * 
 * @param name
 *            bean name
 * @return the bean
 */
protected Object getBean(String name) {
    WebApplicationContext applicationContext = WebApplicationContextUtils
            .getWebApplicationContext(getServletContext());
    if (applicationContext == null) {
        throw new IllegalStateException("No Spring web application context found");
    }
    if (!applicationContext.containsBean(name)) {
        {
            throw new IllegalArgumentException("Spring bean not found: " + name);
        }
    }
    return applicationContext.getBean(name);
}