Example usage for org.springframework.web.context ContextLoader getCurrentWebApplicationContext

List of usage examples for org.springframework.web.context ContextLoader getCurrentWebApplicationContext

Introduction

In this page you can find the example usage for org.springframework.web.context ContextLoader getCurrentWebApplicationContext.

Prototype

@Nullable
public static WebApplicationContext getCurrentWebApplicationContext() 

Source Link

Document

Obtain the Spring root web application context for the current thread (i.e.

Usage

From source file:de.acosix.alfresco.mtsupport.repo.integration.AuthenticationTest.java

@Test
public void loginExistingUserAFaustTenantBetaAndNoSynch() {
    final WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    final TenantAdminService tenantAdminService = context.getBean("TenantAdminService",
            TenantAdminService.class);

    AuthenticationUtil.setFullyAuthenticatedUser("admin");
    if (!tenantAdminService.existsTenant("tenantbeta")) {
        tenantAdminService.createTenant("tenantbeta", "admin".toCharArray());
    }//from  www. j  a v a  2  s  .co m
    AuthenticationUtil.clearCurrentSecurityContext();

    final AuthenticationService authenticationService = context.getBean("AuthenticationService",
            AuthenticationService.class);

    authenticationService.authenticate("afaust@tenantbeta", "afaust".toCharArray());

    final PersonService personService = context.getBean("PersonService", PersonService.class);
    Assert.assertTrue("User afaust should have been lazily created",
            personService.personExists("afaust@tenantbeta"));

    final NodeRef personNodeRef = personService.getPerson("afaust@tenantbeta");
    final PersonInfo personInfo = personService.getPerson(personNodeRef);

    Assert.assertEquals("First name of afaust@tenantbeta should not have been synchronized", "afaust",
            personInfo.getFirstName());
    Assert.assertEquals("Last name of afaust@tenantbeta should not have been synchronized", "",
            personInfo.getLastName());

    Assert.assertFalse("User mmustermann@tenantbeta should not have been eagerly synchronized",
            personService.personExists("mmustermann@tenantbeta"));
}

From source file:com.byd.test.actions.OrderAction.java

License:asdf

@RequestMapping("stopSchedual")
public void stopSchedual() {
    try {//from ww w .ja  v  a  2s. co  m
        Scheduler scheduler = (Scheduler) ContextLoader.getCurrentWebApplicationContext()
                .getBean("schedulerFactory");
        if (scheduler.isShutdown()) {
            System.out.println("?");
            throw new Exception("?");
        }
        scheduler.standby();
    } catch (SchedulerException ex) {
        Logger.getLogger(OrderAction.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(OrderAction.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.usergrid.rest.AbstractRestTest.java

/**
 * Hook to get the token for our base user
 *///from ww w .  j  ava2 s  . c  om
@Before
public void acquireToken() throws Exception {

    WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();

    properties = (Properties) context.getBean("properties");

    managementService = (ManagementService) context.getBean("managementService");

    ApplicationInfo appInfo = managementService.getApplicationInfo("test-organization/test-app");

    User user = managementService.getAppUserByIdentifier(appInfo.getId(), Identifier.from("ed@anuff.com"));

    access_token = managementService.getAccessTokenForAppUser(appInfo.getId(), user.getUuid());

    loginClient();

}

From source file:org.frat.common.security.BaseSecurityContext.java

/**
 * .//  w w w.  j  a  va  2  s .  com
 * 
 * @param username
 */
public static void kickOutUnLogin() {
    try {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();

        // applicationHashSet?session
        @SuppressWarnings("unchecked")
        HashSet<HttpSession> sessions = (HashSet<HttpSession>) servletContext.getAttribute("loginSessions");
        List<HttpSession> sessionList = new ArrayList<HttpSession>();
        if (StringUtil.isObjNotNull(sessions)) {
            for (HttpSession session : sessions) {
                SysUserDto user = (SysUserDto) session.getAttribute("shiro.user");
                if (null != session && StringUtil.isObjNull(user)) {
                    // LOGGER.debug("getLastAccessedTime="+ new
                    // Date(session.getLastAccessedTime()));
                    // LOGGER.debug("now="+ new Date());
                    int diffTime = DateUtil.diffTime(new Date(), new Date(session.getLastAccessedTime()));
                    // LOGGER.debug("diffTime="+diffTime);
                    if (diffTime > 300) {
                        sessionList.add(session);
                    }
                }
            }
            for (HttpSession session : sessionList) {
                session.invalidate();
                LOGGER.debug("success kick out UnLogin session [" + session.getId() + "]");
            }
        }
    } catch (Exception e) {
        LOGGER.error("");
        LOGGER.error(StackTraceUtil.getStackTrace(e));
    }

}

From source file:org.jahia.bin.listeners.JahiaContextLoaderListener.java

@SuppressWarnings("unchecked")
public static void endContextInitialized() {
    try {/*w ww .ja v  a2  s  . co m*/
        logger.info("Finishing context initialization phase");

        // do initialization of all services, implementing JahiaAfterInitializationService
        initJahiaAfterInitializationServices();

        // register listeners after the portal is started
        ApplicationsManagerServiceImpl.getInstance().registerListeners();

        // set fallback locale
        Config.set(servletContext, Config.FMT_FALLBACK_LOCALE,
                (SettingsBean.getInstance().getDefaultLanguageCode() != null)
                        ? SettingsBean.getInstance().getDefaultLanguageCode()
                        : Locale.ENGLISH.getLanguage());

        jahiaContextListenersConfiguration = (Map<String, Object>) ContextLoader
                .getCurrentWebApplicationContext().getBean("jahiaContextListenersConfiguration");
        if (isEventInterceptorActivated("interceptServletContextListenerEvents")) {
            SpringContextSingleton.getInstance()
                    .publishEvent(new ServletContextInitializedEvent(getServletContext()));
        }
        contextInitialized = true;

        // execute patches after the complete initialization
        if (SettingsBean.getInstance().isProcessingServer()) {
            GroovyPatcher.executeScripts(servletContext, "contextInitialized");
        } else {
            // we leave the possibility to provide Groovy scripts for non-processing servers
            GroovyPatcher.executeScripts(servletContext, "nonProcessingServer");
        }
        logger.info("Context initialization phase finished");
    } catch (JahiaException e) {
        running = false;
        logger.error(e.getMessage(), e);
        throw new JahiaRuntimeException(e);
    } catch (RuntimeException e) {
        running = false;
        throw e;
    } finally {
        JCRSessionFactory.getInstance().closeAllSessions();
    }
}

From source file:org.jahia.bin.listeners.JahiaContextLoaderListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    startupTime = System.currentTimeMillis();
    startupWithTrust(Jahia.isEnterpriseEdition() ? (Jahia.getBuildNumber() + "." + Jahia.getEEBuildNumber())
            : String.valueOf(Jahia.getBuildNumber()));

    logger.info("Starting up Digital Experience Manager, please wait...");

    servletContext = event.getServletContext();

    Jahia.setContextPath(servletContext.getContextPath());

    initWebAppRoot();//from   ww  w .j av a  2 s . c o m

    if (System.getProperty("jahia.config") == null) {
        setSystemProperty("jahia.config", "");
    }
    if (System.getProperty("jahia.license") == null) {
        setSystemProperty("jahia.license", "");
    }

    try {
        // verify supported Java version
        Jahia.verifyJavaVersion(servletContext.getInitParameter("supported_jdk_versions"));
    } catch (JahiaInitializationException e) {
        throw new JahiaRuntimeException(e);
    }

    detectPID(servletContext);

    GroovyPatcher.executeScripts(servletContext, "beforeContextInitializing");

    // initialize VFS file system (solves classloader issue: https://issues.apache.org/jira/browse/VFS-228 )
    try {
        VFS.getManager();
    } catch (FileSystemException e) {
        throw new JahiaRuntimeException(e);
    }

    try {
        long timer = System.currentTimeMillis();
        logger.info("Start initializing Spring root application context");

        running = true;

        super.contextInitialized(event);

        logger.info("Spring Root application context initialized in {} ms",
                (System.currentTimeMillis() - timer));

        // initialize services registry
        ServicesRegistry.getInstance().init();

        // fire Spring event that the root context is initialized
        WebApplicationContext rootCtx = ContextLoader.getCurrentWebApplicationContext();
        rootCtx.publishEvent(new RootContextInitializedEvent(rootCtx));

        if (Jahia.isEnterpriseEdition()) {
            requireLicense();
        }

        boolean isProcessingServer = SettingsBean.getInstance().isProcessingServer();

        // execute patches after root context initialization
        if (isProcessingServer) {
            GroovyPatcher.executeScripts(servletContext, "rootContextInitialized");
        }

        // start OSGi container
        FrameworkService.getInstance().start();

    } catch (JahiaException e) {
        running = false;
        logger.error(e.getMessage(), e);
        throw new JahiaRuntimeException(e);
    } catch (RuntimeException e) {
        running = false;
        throw e;
    } finally {
        JCRSessionFactory.getInstance().closeAllSessions();
    }
}

From source file:org.jahia.bin.listeners.JahiaContextLoaderListener.java

private static void requireLicense() {
    try {/* w  ww.  j  a  v  a  2s  .c  o m*/
        AbstractFilter editModeFilter = (AbstractFilter) ContextLoader.getCurrentWebApplicationContext()
                .getBean("editModeFilter");
        if (!ContextLoader.getCurrentWebApplicationContext().getBean("licenseChecker").getClass().getName()
                .equals("org.jahia.security.license.LicenseChecker")
                || !editModeFilter.getClass().getName()
                        .equals("org.jahia.services.render.filter.SecureEditModeFilter")
                || editModeFilter.isDisabled()) {
            throw new FatalBeanException("Required classes for license manager were not found");
        }
    } catch (NoSuchBeanDefinitionException e) {
        throw new FatalBeanException("Required classes for license manager were not found", e);
    }
}

From source file:org.springframework.web.context.support.SpringBeanAutowiringSupport.java

/**
 * Process {@code @Autowired} injection for the given target object,
 * based on the current web application context.
 * <p>Intended for use as a delegate.
 * @param target the target object to process
 * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext()
 *///from  w ww . j a va2  s .  c  o m
public static void processInjectionBasedOnCurrentContext(Object target) {
    Assert.notNull(target, "Target object must not be null");
    WebApplicationContext cc = ContextLoader.getCurrentWebApplicationContext();
    if (cc != null) {
        AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
        bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
        bpp.processInjection(target);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Current WebApplicationContext is not available for processing of "
                    + ClassUtils.getShortName(target.getClass()) + ": "
                    + "Make sure this class gets constructed in a Spring web application. Proceeding without injection.");
        }
    }
}

From source file:org.springframework.web.socket.server.endpoint.SpringConfigurator.java

@Override
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {

    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
    if (wac == null) {
        String message = "Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?";
        logger.error(message);// www . j  a va 2  s.c o m
        throw new IllegalStateException(message);
    }

    Map<String, T> beans = wac.getBeansOfType(endpointClass);
    if (beans.isEmpty()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Creating new @ServerEndpoint instance of type " + endpointClass);
        }
        return wac.getAutowireCapableBeanFactory().createBean(endpointClass);
    } else if (beans.size() == 1) {
        if (logger.isTraceEnabled()) {
            logger.trace("Using @ServerEndpoint singleton " + beans.keySet().iterator().next());
        }
        return beans.values().iterator().next();
    } else {
        // Should not happen ..
        String message = "Found more than one matching @ServerEndpoint beans of type " + endpointClass;
        logger.error(message);
        throw new IllegalStateException(message);
    }
}

From source file:org.springframework.web.socket.server.standard.SpringConfigurator.java

@SuppressWarnings("unchecked")
@Override/*from   ww w  .  j av  a  2s.  c  om*/
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
    if (wac == null) {
        String message = "Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?";
        logger.error(message);
        throw new IllegalStateException(message);
    }

    String beanName = ClassUtils.getShortNameAsProperty(endpointClass);
    if (wac.containsBean(beanName)) {
        T endpoint = wac.getBean(beanName, endpointClass);
        if (logger.isTraceEnabled()) {
            logger.trace("Using @ServerEndpoint singleton " + endpoint);
        }
        return endpoint;
    }

    Component ann = AnnotationUtils.findAnnotation(endpointClass, Component.class);
    if (ann != null && wac.containsBean(ann.value())) {
        T endpoint = wac.getBean(ann.value(), endpointClass);
        if (logger.isTraceEnabled()) {
            logger.trace("Using @ServerEndpoint singleton " + endpoint);
        }
        return endpoint;
    }

    beanName = getBeanNameByType(wac, endpointClass);
    if (beanName != null) {
        return (T) wac.getBean(beanName);
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Creating new @ServerEndpoint instance of type " + endpointClass);
    }
    return wac.getAutowireCapableBeanFactory().createBean(endpointClass);
}