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:com.envision.envservice.filter.RedmineFilter.java

public String getRedmineUrl(String str) {
    String RedmineUrl = str.substring(str.indexOf("/Challenger/redmine/") + 20);
    WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext();
    CacheService cacheService = (CacheService) webAppContext.getBean("cacheService");
    Map map = cacheService.queryMap("redmine_url");
    String redmine_url = map.get("redmine_url").toString();
    String newUrl = RedmineUrl.replace(RedmineUrl, redmine_url + RedmineUrl);
    return newUrl;
}

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

@Test
public void checkUserEagerSynchAndLoginMMustermannDefaultTenant() {
    final WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    final PersonService personService = context.getBean("PersonService", PersonService.class);

    AuthenticationUtil.setFullyAuthenticatedUser("admin");
    Assert.assertTrue("User mmustermann should have been eagerly synchronized",
            personService.personExists("mmustermann"));

    final NodeRef personNodeRef = personService.getPerson("mmustermann");
    final PersonInfo personInfo = personService.getPerson(personNodeRef);

    Assert.assertEquals("First name of mustermann should have been synchronized", "Max",
            personInfo.getFirstName());/*  w w  w.  j a v a  2 s  .co m*/
    Assert.assertEquals("Last name of mmustermann should have been synchronized", "Mustermann",
            personInfo.getLastName());

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

    authenticationService.authenticate("mmustermann", "mmustermann".toCharArray());
}

From source file:architecture.ee.component.core.lifecycle.BootstrapImpl.java

@SuppressWarnings("unchecked")
public <T> T getBootstrapComponent(Class<T> requiredType) throws ComponentNotFoundException {
    if (requiredType == null) {
        throw new ComponentNotFoundException();
    }//from w ww  .ja v  a  2 s .co  m

    if (requiredType == Repository.class) {
        lock.lock();
        try {
            if (repository.getState() != State.INITIALIZED) {
                repository.initialize();
            }
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
        return (T) repository;
    }
    if (references.get(requiredType) == null) {
        try {
            if (getBootstrapApplicationContext() == null) {
                throw new IllegalStateException(L10NUtils.getMessage("003051"));
            }
            if (ContextLoader.getCurrentWebApplicationContext() != null) {
                log.debug("searching in current web application context");
                references.put(requiredType, new WeakReference<T>(
                        ContextLoader.getCurrentWebApplicationContext().getBean(requiredType)));
            } else {
                log.debug("searching in bootstrap application context");
                references.put(requiredType,
                        new WeakReference<T>(getBootstrapApplicationContext().getBean(requiredType)));
            }
        } catch (BeansException e) {
            throw new ComponentNotFoundException(L10NUtils.format("003052", requiredType.getName()), e);
        }
    }
    return (T) references.get(requiredType).get();
}

From source file:org.orderofthebee.addons.support.tools.repo.caches.CacheLookupUtils.java

/**
 * Resolves the {@link CacheStatistics cache statistics} of the {@link TransactionalCache transactional cache} instance that facades a
 * specific {@link SimpleCache shared/*  ww  w  . ja v  a  2  s  . co m*/
 * cache} and provides it in a more script-friendly representation.
 *
 * @param sharedCacheName
 *            the name of the shared cache
 * @return a facade to a snapshot of the cache statistics
 */
public static AlfrescoCacheStatsFacade resolveStatisticsViaTransactional(final String sharedCacheName) {
    ParameterCheck.mandatoryString("sharedCacheName", sharedCacheName);

    LOGGER.debug("Trying to resolve transactional cache for shared cache {}", sharedCacheName);

    String txnCacheName = null;

    final WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();

    if (applicationContext instanceof ConfigurableApplicationContext) {
        final ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext)
                .getBeanFactory();
        final String[] txnCacheBeanNames = applicationContext.getBeanNamesForType(TransactionalCache.class,
                false, false);

        // this is a rather ugly reference lookup, but so far I see no other way
        for (final String txnCacheBeanName : txnCacheBeanNames) {
            final BeanDefinition txnCacheDefinition = beanFactory.getBeanDefinition(txnCacheBeanName);

            final PropertyValue sharedCacheValue = txnCacheDefinition.getPropertyValues()
                    .getPropertyValue("sharedCache");
            final PropertyValue nameValue = txnCacheDefinition.getPropertyValues().getPropertyValue("name");
            if (nameValue != null && sharedCacheValue != null) {
                final Object sharedCacheRef = sharedCacheValue.getValue();
                if (sharedCacheRef instanceof RuntimeBeanReference) {
                    final String sharedCacheBeanName = ((RuntimeBeanReference) sharedCacheRef).getBeanName();

                    Object nameValueObj = nameValue.getValue();
                    if (nameValueObj instanceof TypedStringValue) {
                        nameValueObj = ((TypedStringValue) nameValueObj).getValue();
                    }

                    if (EqualsHelper.nullSafeEquals(sharedCacheBeanName, sharedCacheName)) {
                        if (txnCacheName != null) {
                            LOGGER.info("Shared cache {} is referenced by multiple transactional caches",
                                    sharedCacheName);
                            txnCacheName = null;
                            break;
                        }
                        txnCacheName = String.valueOf(nameValueObj);
                        LOGGER.debug("Resolved transactional cache {} for shared cache {}", txnCacheName,
                                sharedCacheName);
                    } else {
                        try {
                            final DefaultSimpleCache<?, ?> defaultSimpleCache = applicationContext
                                    .getBean(sharedCacheBeanName, DefaultSimpleCache.class);
                            if (EqualsHelper.nullSafeEquals(defaultSimpleCache.getCacheName(),
                                    sharedCacheName)) {
                                if (txnCacheName != null) {
                                    LOGGER.info(
                                            "Shared cache {} is referenced by multiple transactional caches",
                                            sharedCacheName);
                                    txnCacheName = null;
                                    break;
                                }
                                txnCacheName = String.valueOf(nameValueObj);
                                LOGGER.debug("Resolved transactional cache {} for shared cache {}",
                                        txnCacheName, sharedCacheName);
                            }
                            continue;
                        } catch (final BeansException be) {
                            // ignore - can be expected e.g. in EE or with alternative cache implementations
                        }
                    }
                }
            }
        }

        if (txnCacheName == null) {
            LOGGER.debug("Unable to resolve unique transactional cache for shared cache {}", sharedCacheName);
        }
    } else {
        LOGGER.debug(
                "Application context is not a configurable application context - unable to resolve transactional cache");
    }

    AlfrescoCacheStatsFacade facade = null;
    if (txnCacheName != null) {
        final CacheStatistics cacheStatistics = applicationContext.getBean("cacheStatistics",
                CacheStatistics.class);
        try {
            final Map<OpType, OperationStats> allStats = cacheStatistics.allStats(txnCacheName);
            facade = new AlfrescoCacheStatsFacade(allStats);
        } catch (final NoStatsForCache e) {
            facade = new AlfrescoCacheStatsFacade(Collections.emptyMap());
        }
    }

    return facade;
}

From source file:jp.terasoluna.fw.web.struts.util.SpringMessageResources.java

/**
 * wp??[^SpringMessageResources???B//  ww  w.  ja  v  a2  s  .  com
 *
 * @param factory ?bZ?[W\?[Xt@Ng
 * @param config ReiMessageSourceBean
 *               ?i?ftHg"messageSource"?j
 */
public SpringMessageResources(MessageResourcesFactory factory, String config) {
    super(factory, config);
    replaceMessageFormatCache();
    this.context = ContextLoader.getCurrentWebApplicationContext();

    initMessageSource();
}

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

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

    AuthenticationUtil.setFullyAuthenticatedUser("admin");
    if (!tenantAdminService.existsTenant("tenantalpha")) {
        tenantAdminService.createTenant("tenantalpha", "admin".toCharArray());
    }/*from  w w  w .j a  va  2  s. com*/
    AuthenticationUtil.clearCurrentSecurityContext();

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

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

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

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

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

    Assert.assertTrue("User mmustermann@tenantalpha should not have been eagerly synchronized",
            personService.personExists("mmustermann@tenantalpha"));

    personNodeRef = personService.getPerson("mmustermann@tenantalpha");
    personInfo = personService.getPerson(personNodeRef);

    Assert.assertEquals("First name of mustermann should have been synchronized", "Max",
            personInfo.getFirstName());
    Assert.assertEquals("Last name of mmustermann should have been synchronized", "Mustermann",
            personInfo.getLastName());
}

From source file:jp.terasoluna.fw.web.struts.util.SpringMessageResources.java

/**
 * wp??[^SpringMessageResources???B//from w  ww.  j  a  v  a2  s . c om
 *
 * @param factory ?bZ?[W\?[Xt@Ng
 * @param config ReiMessageSourceBean
 *               ?i?ftHg"messageSource"?j
 * @param returnNull <code>org.apache.struts.util.MessageResources</code>
 *                   NX <code>returnNull</code>?B
 *                   <code>false</code> w?AL?[Y?bZ?[W
 *                   ??????Locale.key???`?bZ?[W
 *                   p?B
 */
public SpringMessageResources(MessageResourcesFactory factory, String config, boolean returnNull) {
    super(factory, config, returnNull);
    replaceMessageFormatCache();
    this.context = ContextLoader.getCurrentWebApplicationContext();

    initMessageSource();
}

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

License:asdf

@RequestMapping("setJobTime")
public void setJobTime() {
    try {/*from w w  w  .  j ava 2  s.  com*/
        Scheduler scheduler = (Scheduler) ContextLoader.getCurrentWebApplicationContext()
                .getBean("schedulerFactory");
        CronTriggerBean trigger = (CronTriggerBean) scheduler.getTrigger("dispatchingBillCreatorTrigger",
                Scheduler.DEFAULT_GROUP);
        if (scheduler.isShutdown()) {
            System.out.println("?");
            throw new Exception("?");
        }
        String cronExpression = trigger.getCronExpression();
        System.out.println(" ----------------   " + cronExpression);
        trigger.setCronExpression("0/8 * * * * ?");
        scheduler.rescheduleJob("schedulerFactory", Scheduler.DEFAULT_GROUP, trigger);
    } catch (SchedulerException | ParseException 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:architecture.ee.component.core.lifecycle.BootstrapImpl.java

public AdminService getAdminService() throws ComponentNotFoundException {

    if (bootstrapAdminServiceEnabled.get()) {
        return getBootstrapComponent(AdminService.class);
    } else {/* w  w w  .ja v  a 2s .c o  m*/
        if (initialized.get()) {
            try {
                return ContextLoader.getCurrentWebApplicationContext().getBean(AdminService.class);
            } catch (BeansException e1) {
                throw new ComponentNotFoundException(e1);
            }
        } else {
            throw new ComponentNotFoundException();
        }
    }
}

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

License:asdf

@RequestMapping("runSchedual")
public void runSchedual() {
    try {/*from ww  w .jav a 2 s. c om*/
        Scheduler scheduler = (Scheduler) ContextLoader.getCurrentWebApplicationContext()
                .getBean("schedulerFactory");
        if (!scheduler.isInStandbyMode()) {
            System.out.println("?");
            throw new Exception("?");
        }
        scheduler.start();
    } 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);
    }
}