1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.jcs.jcache.cdi;
20
21 import java.io.Serializable;
22
23 import javax.annotation.Priority;
24 import javax.cache.Cache;
25 import javax.cache.annotation.CacheKeyInvocationContext;
26 import javax.cache.annotation.CacheRemove;
27 import javax.cache.annotation.CacheResolver;
28 import javax.cache.annotation.CacheResolverFactory;
29 import javax.cache.annotation.GeneratedCacheKey;
30 import javax.inject.Inject;
31 import javax.interceptor.AroundInvoke;
32 import javax.interceptor.Interceptor;
33 import javax.interceptor.InvocationContext;
34
35 @CacheRemove
36 @Interceptor
37 @Priority(1000)
38 public class CacheRemoveInterceptor implements Serializable
39 {
40 @Inject
41 private CDIJCacheHelper helper;
42
43 @AroundInvoke
44 public Object cache(final InvocationContext ic) throws Throwable
45 {
46 final CDIJCacheHelper.MethodMeta methodMeta = helper.findMeta(ic);
47
48 final String cacheName = methodMeta.getCacheRemoveCacheName();
49
50 final CacheResolverFactory cacheResolverFactory = methodMeta.getCacheRemoveResolverFactory();
51 final CacheKeyInvocationContext<CacheRemove> context = new CacheKeyInvocationContextImpl<CacheRemove>(
52 ic, methodMeta.getCacheRemove(), cacheName, methodMeta);
53 final CacheResolver cacheResolver = cacheResolverFactory.getCacheResolver(context);
54 final Cache<Object, Object> cache = cacheResolver.resolveCache(context);
55
56 final GeneratedCacheKey cacheKey = methodMeta.getCacheRemoveKeyGenerator().generateCacheKey(context);
57 final CacheRemove cacheRemove = methodMeta.getCacheRemove();
58 final boolean afterInvocation = methodMeta.isCacheRemoveAfter();
59
60 if (!afterInvocation)
61 {
62 cache.remove(cacheKey);
63 }
64
65 final Object result;
66 try
67 {
68 result = ic.proceed();
69 }
70 catch (final Throwable t)
71 {
72 if (afterInvocation)
73 {
74 if (helper.isIncluded(t.getClass(), cacheRemove.evictFor(), cacheRemove.noEvictFor()))
75 {
76 cache.remove(cacheKey);
77 }
78 }
79
80 throw t;
81 }
82
83 if (afterInvocation)
84 {
85 cache.remove(cacheKey);
86 }
87
88 return result;
89 }
90 }