Java Code Examples for org.springframework.cache.Cache

The following examples show how to use org.springframework.cache.Cache. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: entando-core   Author: entando   File: AbstractGenericCacheWrapper.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
protected <O> void manage(String key, O object, Action operation) {
    if (null == object) {
        return;
    }
    Cache cache = this.getCache();
    List<String> codes = (List<String>) this.get(cache, this.getCodesCacheKey(), List.class);
    if (Action.ADD.equals(operation)) {
        if (!codes.contains(key)) {
            codes.add(key);
            cache.put(this.getCodesCacheKey(), codes);
        }
        cache.put(this.getCacheKeyPrefix() + key, object);
    } else if (Action.UPDATE.equals(operation)) {
        if (!codes.contains(key)) {
            throw new CacheItemNotFoundException(key, cache.getName());
        }
        cache.put(this.getCacheKeyPrefix() + key, object);
    } else if (Action.DELETE.equals(operation)) {
        codes.remove(key);
        cache.evict(this.getCacheKeyPrefix() + key);
        cache.put(this.getCodesCacheKey(), codes);
    }
}
 
Example #2
Source Project: spring-analysis-note   Author: Vip-Augus   File: CacheAspectSupport.java    License: MIT License 6 votes vote down vote up
private void performCacheEvict(
		CacheOperationContext context, CacheEvictOperation operation, @Nullable Object result) {

	Object key = null;
	for (Cache cache : context.getCaches()) {
		if (operation.isCacheWide()) {
			logInvalidating(context, operation, null);
			doClear(cache);
		}
		else {
			if (key == null) {
				key = generateKey(context, result);
			}
			logInvalidating(context, operation, key);
			doEvict(cache, key);
		}
	}
}
 
Example #3
Source Project: spring-cloud-aws   Author: spring-cloud   File: ElastiCacheCachingConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void enableElasticache_configuredWithExplicitCluster_configuresExplicitlyConfiguredCaches()
		throws Exception {
	// Arrange

	// Act
	this.context = new AnnotationConfigApplicationContext(
			ApplicationConfigurationWithExplicitStackConfiguration.class);

	// Assert
	CacheManager cacheManager = this.context.getBean(CachingConfigurer.class)
			.cacheManager();
	assertThat(cacheManager.getCacheNames().size()).isEqualTo(2);
	Cache firstCache = cacheManager.getCache("firstCache");
	assertThat(firstCache.getName()).isNotNull();
	assertThat(getExpirationFromCache(firstCache)).isEqualTo(0);

	Cache secondCache = cacheManager.getCache("secondCache");
	assertThat(secondCache.getName()).isNotNull();
	assertThat(getExpirationFromCache(secondCache)).isEqualTo(0);
}
 
Example #4
Source Project: icure-backend   Author: taktik   File: SafeCache.java    License: GNU General Public License v2.0 6 votes vote down vote up
public V get(K key, ValueProvider<K, V> valueProvider) {
	V value;

	Cache.ValueWrapper valueWrapper = cache.get(key);
	if (valueWrapper == null) {
		synchronized (this) {
			valueWrapper = cache.get(key);
			if (valueWrapper == null) {
				value = valueProvider.getValue(key);
				cache.put(key, value);
			} else {
				value = (V) valueWrapper.get();
			}
		}
	} else {
		value = (V) valueWrapper.get();
	}

	return value;
}
 
Example #5
Source Project: cola-cloud   Author: leecho   File: SecurityAccessMetadataSource.java    License: MIT License 6 votes vote down vote up
public void loadUrlRoleMapping() {
    if(metadata != null){
        metadata.clear();
    }else{
        this.metadata = new HashMap<>();
    }
    //从缓存中获取数据
    Cache cache = cacheManager.getCache(ResourceCacheConstant.URL_ROLE_MAPPING_CACHE);
    Cache.ValueWrapper valueWrapper = cache.get(serviceId);
    Map<String, Set<String>> urlRoleMapping = null;
    if (valueWrapper != null) {
        urlRoleMapping = (Map<String, Set<String>>) valueWrapper.get();
    }
    //组装SpringSecurrty的数据
    if (urlRoleMapping != null) {
        for (Map.Entry<String, Set<String>> entry : urlRoleMapping.entrySet()) {
            Set<String> roleCodes = entry.getValue();
            Collection<ConfigAttribute> configs = CollectionUtils.collect(roleCodes.iterator(), input -> new SecurityConfig(input));
            this.metadata.put(entry.getKey(), configs);
        }
    }
}
 
Example #6
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractJCacheAnnotationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void earlyRemoveAllWithException() {
	Cache cache = getCache(DEFAULT_CACHE);

	Object key = createKey(name.getMethodName());
	cache.put(key, new Object());

	try {
		service.earlyRemoveAllWithException(true);
		fail("Should have thrown an exception");
	}
	catch (UnsupportedOperationException e) {
		// This is what we expect
	}
	assertTrue(isEmpty(cache));
}
 
Example #7
Source Project: yes-cart   Author: inspire-software   File: ResilientCartRepositoryImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetShoppingCartNullOrEmptyToken() throws Exception {

    final ShoppingCartStateService shoppingCartStateService = context.mock(ShoppingCartStateService.class, "shoppingCartStateService");
    final ShopService shopService = context.mock(ShopService.class, "shopService");
    final CartUpdateProcessor cartUpdateProcessor = context.mock(CartUpdateProcessor.class, "cartUpdateProcessor");
    final TaskExecutor taskExecutor = context.mock(TaskExecutor.class, "taskExecutor");
    final CacheManager cacheManager = context.mock(CacheManager.class, "cacheManager");
    final Cache cartCache = context.mock(Cache.class, "cartCache");

    context.checking(new Expectations() {{
        oneOf(cacheManager).getCache("web.shoppingCart"); will(returnValue(cartCache));
    }});

    final ResilientCartRepositoryImpl repo = new ResilientCartRepositoryImpl(shoppingCartStateService, shopService, cartUpdateProcessor, mockCartSerDes, 60, cacheManager, taskExecutor);

    assertNull(repo.getShoppingCart(null));
    assertNull(repo.getShoppingCart("  "));

    context.assertIsSatisfied();

}
 
Example #8
Source Project: java-technology-stack   Author: codeEngraver   File: AspectJCacheAnnotationTests.java    License: MIT License 6 votes vote down vote up
@Override
public void testMultiEvict(CacheableService<?> service) {
	Object o1 = new Object();

	Object r1 = service.multiCache(o1);
	Object r2 = service.multiCache(o1);

	Cache primary = cm.getCache("primary");
	Cache secondary = cm.getCache("secondary");

	assertSame(r1, r2);
	assertSame(r1, primary.get(o1).get());
	assertSame(r1, secondary.get(o1).get());

	service.multiEvict(o1);
	assertNull(primary.get(o1));
	assertNull(secondary.get(o1));

	Object r3 = service.multiCache(o1);
	Object r4 = service.multiCache(o1);
	assertNotSame(r1, r3);
	assertSame(r3, r4);

	assertSame(r3, primary.get(o1).get());
	assertSame(r4, secondary.get(o1).get());
}
 
Example #9
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractJCacheAnnotationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void cacheCheckedException() {
	String keyItem = name.getMethodName();
	Cache cache = getCache(EXCEPTION_CACHE);

	Object key = createKey(keyItem);
	assertNull(cache.get(key));

	try {
		service.cacheWithCheckedException(keyItem, true);
		fail("Should have thrown an exception");
	}
	catch (IOException e) {
		// This is what we expect
	}

	Cache.ValueWrapper result = cache.get(key);
	assertNotNull(result);
	assertEquals(IOException.class, result.get().getClass());
}
 
Example #10
Source Project: spring4-understanding   Author: langtianya   File: AbstractCacheManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Cache getCache(String name) {
	Cache cache = this.cacheMap.get(name);
	if (cache != null) {
		return cache;
	}
	else {
		// Fully synchronize now for missing cache creation...
		synchronized (this.cacheMap) {
			cache = this.cacheMap.get(name);
			if (cache == null) {
				cache = getMissingCache(name);
				if (cache != null) {
					cache = decorateCache(cache);
					this.cacheMap.put(name, cache);
					updateCacheNames(name);
				}
			}
			return cache;
		}
	}
}
 
Example #11
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractJCacheAnnotationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void putWithExceptionVetoPut() {
	String keyItem = name.getMethodName();
	Cache cache = getCache(DEFAULT_CACHE);

	Object key = createKey(keyItem);
	Object value = new Object();
	assertNull(cache.get(key));

	try {
		service.putWithException(keyItem, value, false);
		fail("Should have thrown an exception");
	}
	catch (NullPointerException e) {
		// This is what we expect
	}
	assertNull(cache.get(key));
}
 
Example #12
Source Project: arcus-spring   Author: naver   File: ArcusCacheManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Collection<? extends Cache> loadCaches() {
  List<Cache> caches = new ArrayList<Cache>(initialCacheConfigs.size());
  for (Map.Entry<String, ArcusCacheConfiguration> entry : initialCacheConfigs.entrySet()) {
    caches.add(
      createCache(entry.getKey(), entry.getValue()));
  }

  return caches;
}
 
Example #13
Source Project: we-cmdb   Author: WeBankPartners   File: RequestScopedCacheManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Cache getCache(String name) {
    final Map<String, Cache> cacheMap = threadLocalCache.get();
    Cache cache = cacheMap.get(name);
    if (cache == null) {
        cache = createCache(name);
        cacheMap.put(name, cache);
    }
    return cache;
}
 
Example #14
Source Project: entando-core   Author: entando   File: AbstractGenericCacheWrapper.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void insertObjectsOnCache(Cache cache, Map<String, O> objects) {
    List<String> codes = new ArrayList<>();
    Iterator<String> iter = objects.keySet().iterator();
    while (iter.hasNext()) {
        String key = iter.next();
        cache.put(this.getCacheKeyPrefix() + key, objects.get(key));
        codes.add(key);
    }
    cache.put(this.getCodesCacheKey(), codes);
}
 
Example #15
Source Project: yes-cart   Author: inspire-software   File: ResilientCartRepositoryImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetShoppingCartFromCacheLoggedOutInactiveNoSetting() throws Exception {

    final ShoppingCartStateService shoppingCartStateService = context.mock(ShoppingCartStateService.class, "shoppingCartStateService");
    final ShopService shopService = context.mock(ShopService.class, "shopService");
    final CartUpdateProcessor cartUpdateProcessor = context.mock(CartUpdateProcessor.class, "cartUpdateProcessor");
    final TaskExecutor taskExecutor = context.mock(TaskExecutor.class, "taskExecutor");
    final CacheManager cacheManager = context.mock(CacheManager.class, "cacheManager");
    final Cache cartCache = context.mock(Cache.class, "cartCache");
    final Cache.ValueWrapper wrapper = context.mock(Cache.ValueWrapper.class, "wrapper");
    final ShoppingCart cachedCart = context.mock(ShoppingCart.class, "cachedCart");

    final byte[] cached = new byte[0];

    context.checking(new Expectations() {{
        oneOf(cacheManager).getCache("web.shoppingCart"); will(returnValue(cartCache));
        oneOf(cartCache).get("IN-CACHE"); will(returnValue(wrapper));
        oneOf(wrapper).get(); will(returnValue(cached));
        oneOf(mockCartSerDes).restoreState(cached); will(returnValue(cachedCart));
        allowing(cachedCart).getLogonState(); will(returnValue(ShoppingCart.SESSION_EXPIRED));
    }});

    final ResilientCartRepositoryImpl repo = new ResilientCartRepositoryImpl(shoppingCartStateService, shopService, cartUpdateProcessor, mockCartSerDes, 60, cacheManager, taskExecutor);

    assertEquals(cachedCart, repo.getShoppingCart("IN-CACHE"));

    context.assertIsSatisfied();

}
 
Example #16
Source Project: rice   Author: kuali   File: RoleServiceImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
protected Role getRoleFromCache(String id) {
    Cache cache = cacheManager.getCache(Role.Cache.NAME);
    Cache.ValueWrapper cachedValue = cache.get("id=" + id);
    if (cachedValue != null) {
        return (Role) cachedValue.get();
    }
    return null;
}
 
Example #17
Source Project: spring-analysis-note   Author: Vip-Augus   File: JCacheCacheManager.java    License: MIT License 5 votes vote down vote up
@Override
protected Collection<Cache> loadCaches() {
	CacheManager cacheManager = getCacheManager();
	Assert.state(cacheManager != null, "No CacheManager set");

	Collection<Cache> caches = new LinkedHashSet<>();
	for (String cacheName : cacheManager.getCacheNames()) {
		javax.cache.Cache<Object, Object> jcache = cacheManager.getCache(cacheName);
		caches.add(new JCacheCache(jcache, isAllowNullValues()));
	}
	return caches;
}
 
Example #18
Source Project: n2o-framework   Author: i-novus-llc   File: SyncCacheTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected E handleCache(String key, CacheCallback<E> callback, Cache cache) {
    synchronized (key.intern()) {
        //еще раз читаем, т.к. в кэш могли положить пока ждали
        Cache.ValueWrapper valueWrapper = cache.get(key);
        if (valueWrapper != null) {
            E value = (E)valueWrapper.get();
            callback.doInCacheHit(value);
            return value;
        }
        return super.handleCache(key, callback, cache);
    }
}
 
Example #19
Source Project: spring4-understanding   Author: langtianya   File: CacheAspectSupport.java    License: Apache License 2.0 5 votes vote down vote up
private Cache.ValueWrapper findInCaches(CacheOperationContext context, Object key) {
	for (Cache cache : context.getCaches()) {
		Cache.ValueWrapper wrapper = doGet(cache, key);
		if (wrapper != null) {
			if (logger.isTraceEnabled()) {
				logger.trace("Cache entry for key '" + key + "' found in cache '" + cache.getName() + "'");
			}
			return wrapper;
		}
	}
	return null;
}
 
Example #20
Source Project: java-technology-stack   Author: codeEngraver   File: TransactionAwareCacheDecoratorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void putTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);

	TransactionStatus status = this.txManager.getTransaction(
			new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));

	Object key = new Object();
	cache.put(key, "123");
	assertNull(target.get(key));
	this.txManager.commit(status);

	assertEquals("123", target.get(key, String.class));
}
 
Example #21
Source Project: spring4-understanding   Author: langtianya   File: CacheResolverCustomizationTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void noCustomization() {
	Cache cache = cacheManager.getCache("default");

	Object key = new Object();
	assertCacheMiss(key, cache);

	Object value = simpleService.getSimple(key);
	assertCacheHit(key, value, cache);
}
 
Example #22
Source Project: spring4-understanding   Author: langtianya   File: AbstractCacheInvoker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute {@link Cache#evict(Object)} on the specified {@link Cache} and
 * invoke the error handler if an exception occurs.
 */
protected void doEvict(Cache cache, Object key) {
	try {
		cache.evict(key);
	}
	catch (RuntimeException e) {
		getErrorHandler().handleCacheEvictError(e, cache, key);
	}
}
 
Example #23
Source Project: java-technology-stack   Author: codeEngraver   File: CacheResolverAdapterTests.java    License: MIT License 5 votes vote down vote up
protected CacheResolver getCacheResolver(CacheInvocationContext<? extends Annotation> context, String cacheName) {
	CacheResolver cacheResolver = mock(CacheResolver.class);
	javax.cache.Cache cache;
	if (cacheName == null) {
		cache = null;
	}
	else {
		cache = mock(javax.cache.Cache.class);
		given(cache.getName()).willReturn(cacheName);
	}
	given(cacheResolver.resolveCache(context)).willReturn(cache);
	return cacheResolver;
}
 
Example #24
Source Project: spring4-understanding   Author: langtianya   File: AbstractCacheInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the collection of caches in a single expected element.
 * <p>Throw an {@link IllegalStateException} if the collection holds more than one element
 * @return the singe element or {@code null} if the collection is empty
 */
static Cache extractFrom(Collection<? extends Cache> caches) {
	if (CollectionUtils.isEmpty(caches)) {
		return null;
	}
	else if (caches.size() == 1) {
		return caches.iterator().next();
	}
	else {
		throw new IllegalStateException("Unsupported cache resolution result " + caches +
				": JSR-107 only supports a single cache.");
	}
}
 
Example #25
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractCacheInterceptor.java    License: MIT License 5 votes vote down vote up
/**
 * Convert the collection of caches in a single expected element.
 * <p>Throw an {@link IllegalStateException} if the collection holds more than one element
 * @return the single element or {@code null} if the collection is empty
 */
@Nullable
static Cache extractFrom(Collection<? extends Cache> caches) {
	if (CollectionUtils.isEmpty(caches)) {
		return null;
	}
	else if (caches.size() == 1) {
		return caches.iterator().next();
	}
	else {
		throw new IllegalStateException("Unsupported cache resolution result " + caches +
				": JSR-107 only supports a single cache.");
	}
}
 
Example #26
Source Project: rice   Author: kuali   File: RoleServiceImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
protected Role getRoleFromCache(String namespaceCode, String name) {
    Cache cache = cacheManager.getCache(Role.Cache.NAME);
    Cache.ValueWrapper cachedValue = cache.get("namespaceCode=" + namespaceCode + "|name=" + name);
    if (cachedValue != null) {
        return (Role) cachedValue.get();
    }
    return null;
}
 
Example #27
Source Project: lams   Author: lamsfoundation   File: JCacheCacheManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Collection<Cache> loadCaches() {
	Collection<Cache> caches = new LinkedHashSet<Cache>();
	for (String cacheName : getCacheManager().getCacheNames()) {
		javax.cache.Cache<Object, Object> jcache = getCacheManager().getCache(cacheName);
		caches.add(new JCacheCache(jcache, isAllowNullValues()));
	}
	return caches;
}
 
Example #28
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractCacheInvoker.java    License: MIT License 5 votes vote down vote up
/**
 * Execute {@link Cache#put(Object, Object)} on the specified {@link Cache}
 * and invoke the error handler if an exception occurs.
 */
protected void doPut(Cache cache, Object key, @Nullable Object result) {
	try {
		cache.put(key, result);
	}
	catch (RuntimeException ex) {
		getErrorHandler().handleCachePutError(ex, cache, key, result);
	}
}
 
Example #29
Source Project: n2o-framework   Author: i-novus-llc   File: SyncTwoLevelCacheTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected S handleSecondCache(String key, TwoLevelCacheCallback<F, S> callback, Cache secondLevelCache) {
    synchronized (key.intern()) {
        //еще раз читаем, т.к. в кэш могли положить пока ждали
        Cache.ValueWrapper valueWrapper = secondLevelCache.get(key);
        if (valueWrapper != null) {
            S value = (S) valueWrapper.get();
            callback.doInSecondLevelCacheHit(value);
            return value;
        }
        return super.handleSecondCache(key, callback, secondLevelCache);
    }
}
 
Example #30
Source Project: entando-core   Author: entando   File: ApiResourceCacheWrapper.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void initCache(Map<String, ApiResource> resources, IApiCatalogDAO apiCatalogDAO) throws ApsSystemException {
	try {
		Cache cache = this.getCache();
		this.releaseCachedObjects(cache);
		apiCatalogDAO.loadApiStatus(resources);
		this.insertObjectsOnCache(cache, resources);
	} catch (Throwable t) {
		logger.error("Error bootstrapping ApiCatalog cache", t);
		throw new ApsSystemException("Error bootstrapping ApiCatalog cache", t);
	}
}