1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.jcs3.jcache.cdi;
20
21 import javax.cache.Cache;
22 import javax.cache.CacheManager;
23 import javax.cache.Caching;
24 import javax.cache.annotation.CacheMethodDetails;
25 import javax.cache.annotation.CacheResolver;
26 import javax.cache.annotation.CacheResolverFactory;
27 import javax.cache.annotation.CacheResult;
28 import javax.cache.configuration.MutableConfiguration;
29 import javax.cache.spi.CachingProvider;
30 import java.lang.annotation.Annotation;
31
32 public class CacheResolverFactoryImpl implements CacheResolverFactory
33 {
34 private final CacheManager cacheManager;
35 private final CachingProvider provider;
36
37 public CacheResolverFactoryImpl()
38 {
39 provider = Caching.getCachingProvider();
40 cacheManager = provider.getCacheManager(provider.getDefaultURI(), provider.getDefaultClassLoader());
41 }
42
43 @Override
44 public CacheResolver getCacheResolver(final CacheMethodDetails<? extends Annotation> cacheMethodDetails)
45 {
46 return findCacheResolver(cacheMethodDetails.getCacheName());
47 }
48
49 @Override
50 public CacheResolver getExceptionCacheResolver(final CacheMethodDetails<CacheResult> cacheMethodDetails)
51 {
52 final String exceptionCacheName = cacheMethodDetails.getCacheAnnotation().exceptionCacheName();
53 if (exceptionCacheName == null || exceptionCacheName.isEmpty())
54 {
55 throw new IllegalArgumentException("CacheResult.exceptionCacheName() not specified");
56 }
57 return findCacheResolver(exceptionCacheName);
58 }
59
60 private CacheResolver findCacheResolver(final String exceptionCacheName)
61 {
62 Cache<?, ?> cache = cacheManager.getCache(exceptionCacheName);
63 if (cache == null)
64 {
65 cache = createCache(exceptionCacheName);
66 }
67 return new CacheResolverImpl(cache);
68 }
69
70 private Cache<?, ?> createCache(final String exceptionCacheName)
71 {
72 cacheManager.createCache(exceptionCacheName, new MutableConfiguration<>().setStoreByValue(false));
73 return cacheManager.getCache(exceptionCacheName);
74 }
75
76 public void release()
77 {
78 cacheManager.close();
79 provider.close();
80 }
81 }