KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > soto > aop > AdviceInterceptor


1 package org.sapia.soto.aop;
2
3 import net.sf.cglib.proxy.MethodInterceptor;
4 import net.sf.cglib.proxy.MethodProxy;
5
6 import gnu.trove.THashMap;
7
8 import java.lang.reflect.Method JavaDoc;
9
10 import java.util.ArrayList JavaDoc;
11 import java.util.Iterator JavaDoc;
12 import java.util.List JavaDoc;
13 import java.util.Map JavaDoc;
14
15
16 /**
17  * Intercepts methods and dispatches their call to the appropriate
18  * <code>Adviser</code>.
19  *
20  * @author Yanick Duchesne
21  * <dl>
22  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2003 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
23  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
24  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
25  * </dl>
26  */

27 public class AdviceInterceptor implements MethodInterceptor {
28   private Map _invokers = new THashMap();
29   private Class JavaDoc _advised;
30
31   /**
32    * Constructor for AopInterceptor.
33    */

34   public AdviceInterceptor(Class JavaDoc advised) {
35     _advised = advised;
36   }
37
38   /**
39    * Adds an <code>AopDelegate</code> to this instance, for the
40    * given method.
41    *
42    * @param method <code>Method</code> object to which the given
43    * delegate should be associated.
44    *
45    * @param deleg an <code>Invoker</code>.
46    */

47   public void addInvoker(Method JavaDoc method, Invoker inv) {
48     List JavaDoc invokers = (List JavaDoc) _invokers.get(method);
49
50     if (invokers == null) {
51       invokers = new ArrayList JavaDoc(1);
52     }
53
54     invokers.add(inv);
55     _invokers.put(method, invokers);
56   }
57
58   /**
59    * Initializes this instance.
60    */

61   public void init() {
62     ((THashMap) _invokers).compact();
63   }
64
65   public Class JavaDoc getAdvisedClass() {
66     return _advised;
67   }
68
69   /**
70    * @see net.sf.cglib.MethodInterceptor#intercept(Object, Method, Object[], MethodProxy)
71    */

72   public Object JavaDoc intercept(Object JavaDoc instance, Method JavaDoc toCall, Object JavaDoc[] args,
73     MethodProxy proxy) throws Throwable JavaDoc {
74     Object JavaDoc toReturn;
75
76     if (_invokers.size() > 0) {
77       List JavaDoc invokers = (List JavaDoc) _invokers.get(toCall);
78
79       if ((invokers == null) || (invokers.size() == 0)) {
80         toReturn = proxy.invokeSuper(instance, args);
81       } else {
82         Iterator JavaDoc itr = invokers.iterator();
83         Invocation invocation = new Invocation(instance, toCall, proxy, args);
84         toReturn = ((Invoker) itr.next()).invoke(invocation, itr);
85       }
86     } else {
87       toReturn = proxy.invokeSuper(instance, args);
88     }
89
90     return toReturn;
91   }
92 }
93
Popular Tags