01: package org.shiftone.cache.util;
02:
03: import org.shiftone.cache.Cache;
04:
05: import java.lang.reflect.InvocationHandler;
06: import java.lang.reflect.Method;
07: import java.lang.reflect.UndeclaredThrowableException;
08: import java.util.Arrays;
09:
10: /**
11: * Class CacheInvocationHandler is used to create cached proxies
12: *
13: * @see org.shiftone.cache.CacheProxy
14: *
15: * @author <a href="mailto:jeff@shiftone.org">Jeff Drost</a>
16: * @version $Revision: 1.7 $
17: */
18: public class CacheInvocationHandler implements InvocationHandler {
19:
20: private Cache cache = null;
21: private Object target = null;
22:
23: public CacheInvocationHandler(Object target, Cache cache) {
24: this .cache = cache;
25: this .target = target;
26: }
27:
28: public Object invoke(Object proxy, Method method, Object[] args)
29: throws Throwable {
30:
31: Object result = null;
32: Throwable throwable = null;
33: CallKey callKey = null;
34:
35: callKey = new CallKey(method.getName(), args);
36:
37: try {
38: result = cache.getObject(callKey);
39:
40: if (result == null) {
41: result = method.invoke(target, args);
42:
43: cache.addObject(callKey, result);
44: }
45: } catch (UndeclaredThrowableException e) {
46: throw e.getUndeclaredThrowable();
47: }
48:
49: return result;
50: }
51: }
52:
53: class CallKey {
54:
55: private final String methodName;
56: private final Object[] args;
57:
58: public CallKey(String methodName, Object[] args) {
59: this .methodName = methodName;
60: this .args = args;
61: }
62:
63: public int hashCode() {
64:
65: int code = methodName.hashCode();
66:
67: if (args != null) {
68: for (int i = 0; i < args.length; i++) {
69: code = (31 * code) + args[i].hashCode();
70: }
71: }
72:
73: return code;
74: }
75:
76: public boolean equals(Object o) {
77:
78: if (this == o) {
79: return true;
80: }
81:
82: if (!(o instanceof CallKey)) {
83: return false;
84: }
85:
86: final CallKey callKey = (CallKey) o;
87:
88: if (!methodName.equals(callKey.methodName)) {
89: return false;
90: }
91:
92: if (!Arrays.equals(args, callKey.args)) {
93: return false;
94: }
95:
96: return true;
97: }
98: }
|