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 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
41
42
43 private static final long serialVersionUID = -7441959527908682219L;
44 @Inject
45 private CDIJCacheHelper helper;
46
47 @AroundInvoke
48 public Object cache(final InvocationContext ic) throws Throwable
49 {
50 final CDIJCacheHelper.MethodMeta methodMeta = helper.findMeta(ic);
51
52 final String cacheName = methodMeta.getCacheRemoveCacheName();
53
54 final CacheResolverFactory cacheResolverFactory = methodMeta.getCacheRemoveResolverFactory();
55 final CacheKeyInvocationContext<CacheRemove> context = new CacheKeyInvocationContextImpl<>(
56 ic, methodMeta.getCacheRemove(), cacheName, methodMeta);
57 final CacheResolver cacheResolver = cacheResolverFactory.getCacheResolver(context);
58 final Cache<Object, Object> cache = cacheResolver.resolveCache(context);
59
60 final GeneratedCacheKey cacheKey = methodMeta.getCacheRemoveKeyGenerator().generateCacheKey(context);
61 final CacheRemove cacheRemove = methodMeta.getCacheRemove();
62 final boolean afterInvocation = methodMeta.isCacheRemoveAfter();
63
64 if (!afterInvocation)
65 {
66 cache.remove(cacheKey);
67 }
68
69 final Object result;
70 try
71 {
72 result = ic.proceed();
73 }
74 catch (final Throwable t)
75 {
76 if (afterInvocation && helper.isIncluded(t.getClass(), cacheRemove.evictFor(), cacheRemove.noEvictFor()))
77 {
78 cache.remove(cacheKey);
79 }
80
81 throw t;
82 }
83
84 if (afterInvocation)
85 {
86 cache.remove(cacheKey);
87 }
88
89 return result;
90 }
91 }