KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > shiftone > cache > util > CacheInvocationHandler


1 package org.shiftone.cache.util;
2
3
4
5 import org.shiftone.cache.Cache;
6
7 import java.lang.reflect.InvocationHandler JavaDoc;
8 import java.lang.reflect.Method JavaDoc;
9 import java.lang.reflect.UndeclaredThrowableException JavaDoc;
10 import java.util.Arrays JavaDoc;
11
12
13 /**
14  * Class CacheInvocationHandler is used to create cached proxies
15  *
16  * @see org.shiftone.cache.CacheProxy
17  *
18  * @author <a HREF="mailto:jeff@shiftone.org">Jeff Drost</a>
19  * @version $Revision: 1.7 $
20  */

21 public class CacheInvocationHandler implements InvocationHandler JavaDoc
22 {
23
24     private Cache cache = null;
25     private Object JavaDoc target = null;
26
27     public CacheInvocationHandler(Object JavaDoc target, Cache cache)
28     {
29         this.cache = cache;
30         this.target = target;
31     }
32
33
34     public Object JavaDoc invoke(Object JavaDoc proxy, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc
35     {
36
37         Object JavaDoc result = null;
38         Throwable JavaDoc throwable = null;
39         CallKey callKey = null;
40
41         callKey = new CallKey(method.getName(), args);
42
43         try
44         {
45             result = cache.getObject(callKey);
46
47             if (result == null)
48             {
49                 result = method.invoke(target, args);
50
51                 cache.addObject(callKey, result);
52             }
53         }
54         catch (UndeclaredThrowableException JavaDoc e)
55         {
56             throw e.getUndeclaredThrowable();
57         }
58
59         return result;
60     }
61 }
62
63 class CallKey
64 {
65
66     private final String JavaDoc methodName;
67     private final Object JavaDoc[] args;
68
69     public CallKey(String JavaDoc methodName, Object JavaDoc[] args)
70     {
71         this.methodName = methodName;
72         this.args = args;
73     }
74
75
76     public int hashCode()
77     {
78
79         int code = methodName.hashCode();
80
81         if (args != null)
82         {
83             for (int i = 0; i < args.length; i++)
84             {
85                 code = (31 * code) + args[i].hashCode();
86             }
87         }
88
89         return code;
90     }
91
92
93     public boolean equals(Object JavaDoc o)
94     {
95
96         if (this == o)
97         {
98             return true;
99         }
100
101         if (!(o instanceof CallKey))
102         {
103             return false;
104         }
105
106         final CallKey callKey = (CallKey) o;
107
108         if (!methodName.equals(callKey.methodName))
109         {
110             return false;
111         }
112
113         if (!Arrays.equals(args, callKey.args))
114         {
115             return false;
116         }
117
118         return true;
119     }
120 }
121
Popular Tags