KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > ubik > rmi > interceptor > SingleDispatcher


1 package org.sapia.ubik.rmi.interceptor;
2
3 import java.lang.reflect.Method JavaDoc;
4
5 import java.util.*;
6
7
8 /**
9  * This dispatcher allows to register only one interceptor
10  * per event type.
11  *
12  * @author Yanick Duchesne
13  * <dl>
14  * <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>
15  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
16  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
17  * </dl>
18  */

19 public class SingleDispatcher {
20   Map _interceptors = new HashMap();
21
22   /**
23    * Registers an interceptor with the given event type.
24    *
25    * @param event an event class.
26    * @param it an <code>Interceptor</code> instance.
27    *
28    * @throws InvalidInterceptorException if the interceptor could not be registered.
29    */

30   public void registerInterceptor(Class JavaDoc event, Interceptor it)
31     throws InvalidInterceptorException {
32     Class JavaDoc itClass = it.getClass();
33     int idx = event.getName().lastIndexOf('.');
34     String JavaDoc shortName;
35
36     if (idx < 0) {
37       shortName = event.getName();
38     } else {
39       shortName = event.getName().substring(idx + 1);
40     }
41
42     char[] content = shortName.toCharArray();
43     content[0] = Character.toUpperCase(content[0]);
44     shortName = "on" + new String JavaDoc(content);
45
46     Method JavaDoc m;
47
48     try {
49       m = itClass.getMethod(shortName, new Class JavaDoc[] { event });
50     } catch (Exception JavaDoc e) {
51       throw new InvalidInterceptorException(e);
52     }
53
54     if (_interceptors.get(event) != null) {
55       throw new InvalidInterceptorException(
56         "interceptor already registered for " + event.getName());
57     }
58
59     _interceptors.put(event, new InterceptorInfo(it, m));
60   }
61
62   /**
63    * Dispatches the given event to the interceptor that has
64    * registered for the event's class.
65    */

66   public void dispatch(Event event) {
67     InterceptorInfo info = (InterceptorInfo) _interceptors.get(event.getClass());
68
69     if (info == null) {
70       return;
71     }
72
73     try {
74       info.method.invoke(info.interceptor, new Object JavaDoc[] { event });
75     } catch (Throwable JavaDoc t) {
76       handleError(t);
77     }
78   }
79
80   /**
81    * Template method that is called internally when an error is
82    * trapped when invoking the call-back method on a given
83    * interceptor instance.
84    */

85   protected void handleError(Throwable JavaDoc t) {
86     t.printStackTrace();
87   }
88 }
89
Popular Tags