01: package com.technoetic.xplanner.db;
02:
03: import java.util.Arrays;
04: import java.util.HashMap;
05: import java.util.List;
06: import java.util.Map;
07:
08: import org.aopalliance.intercept.MethodInterceptor;
09: import org.aopalliance.intercept.MethodInvocation;
10: import org.apache.commons.lang.StringUtils;
11: import org.apache.log4j.Logger;
12:
13: /**
14: * User: Mateusz Prokopowicz
15: * Date: Sep 6, 2005
16: * Time: 6:40:13 AM
17: */
18: public class MethodCacheInterceptor implements MethodInterceptor {
19: private Map resultByArgsByMethodName;
20: Logger LOG = Logger.getLogger(MethodCacheInterceptor.class);
21:
22: public MethodCacheInterceptor(Map cacheMap) {
23: this .resultByArgsByMethodName = cacheMap;
24: }
25:
26: public Object invoke(MethodInvocation invocation) throws Throwable {
27: String methodName = invocation.getMethod().getName();
28: List argumentList = Arrays.asList(invocation.getArguments());
29: return cache(methodName, argumentList, invocation);
30: }
31:
32: Object cache(String methodName, List argumentList,
33: MethodInvocation invocation) throws Throwable {
34: Object retVal;
35: LOG
36: .debug("Processing caching for method "
37: + methodName
38: + "("
39: + StringUtils.join(argumentList.iterator(),
40: ", ") + ")");
41: Map resultByArgs = (Map) resultByArgsByMethodName
42: .get(methodName);
43: if (resultByArgs == null) {
44: LOG.debug("No method cache");
45: resultByArgs = new HashMap();
46: resultByArgsByMethodName.put(methodName, resultByArgs);
47: }
48: if (!resultByArgs.containsKey(argumentList)) {
49: LOG
50: .debug("No arguments cache. Calling the orginal method and cache the result");
51: retVal = invocation.proceed();
52: resultByArgs.put(argumentList, retVal);
53: } else {
54: LOG.debug("The cache found. Returning the cached result");
55: retVal = resultByArgs.get(argumentList);
56: }
57: return retVal;
58: }
59: }
|