1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.student.common.util.spring;
17
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.List;
21
22 import net.sf.ehcache.CacheManager;
23 import net.sf.ehcache.Element;
24 import net.sf.ehcache.ObjectExistsException;
25
26 import org.aopalliance.aop.Advice;
27 import org.apache.commons.collections.keyvalue.MultiKey;
28 import org.apache.log4j.Logger;
29 import org.aspectj.lang.ProceedingJoinPoint;
30
31 public class MethodArgsToObjectEhcacheAdvice implements Advice {
32 final Logger LOG = Logger.getLogger(getClass());
33
34 private CacheManager cacheManager;
35 private String cacheName;
36 private boolean enabled;
37
38
39
40
41 public MethodArgsToObjectEhcacheAdvice() {
42 super();
43 }
44
45
46
47
48 public MethodArgsToObjectEhcacheAdvice(String cacheName) {
49 super();
50 this.cacheName = cacheName;
51 }
52
53 public Object invalidateCache(ProceedingJoinPoint pjp) throws Throwable {
54 Object result = pjp.proceed();
55 if(enabled){
56 if (cacheManager == null) {
57 cacheManager = CacheManager.getInstance();
58 try {
59 cacheManager.addCache(cacheName);
60 } catch (ObjectExistsException e) {
61
62 }
63 }
64 LOG.info("Invalidating Cache: " + cacheName);
65 cacheManager.getCache(cacheName).removeAll();
66 }
67 return result;
68 }
69
70 public Object getFromCache(ProceedingJoinPoint pjp) throws Throwable {
71 if(!enabled){
72 return pjp.proceed();
73 }
74
75 if (cacheManager == null) {
76 cacheManager = CacheManager.getInstance();
77 try {
78 cacheManager.addCache(cacheName);
79 } catch (ObjectExistsException e) {
80
81 }
82 }
83 MultiKey cacheKey = getCacheKey(pjp);
84
85 Element cachedResult = cacheManager.getCache(cacheName).get(cacheKey);
86 Object result = null;
87 if (cachedResult == null) {
88 result = pjp.proceed();
89 LOG.info("Storing to Cache: " + cacheName);
90 cacheManager.getCache(cacheName).put(new Element(cacheKey, result));
91 } else {
92 LOG.info("Found in Cache: " + cacheName);
93 result = cachedResult.getValue();
94 }
95
96 return result;
97 }
98
99 private MultiKey getCacheKey(ProceedingJoinPoint pjp) {
100 List<Object> keyList = new ArrayList<Object>();
101 keyList.add(pjp.getSignature().getName());
102 for(Object arg : pjp.getArgs()){
103 keyList.add(arg.toString());
104 }
105 return new MultiKey(keyList.toArray());
106 }
107
108
109
110
111 public String getCacheName() {
112 return cacheName;
113 }
114
115
116
117
118
119 public void setCacheName(String cacheName) {
120 this.cacheName = cacheName;
121 }
122
123 public void setCacheManager(CacheManager cacheManager) {
124 this.cacheManager = cacheManager;
125 }
126
127 public boolean isEnabled() {
128 return enabled;
129 }
130
131 public void setEnabled(boolean enabled) {
132 this.enabled = enabled;
133 }
134
135 }