1 package org.sapia.ubik.rmi.interceptor; 2 3 import org.sapia.ubik.rmi.server.Log; 4 5 import java.lang.reflect.InvocationTargetException ; 6 import java.lang.reflect.Method ; 7 8 import java.util.*; 9 10 11 22 public class MultiDispatcher { 23 Map _interceptors = new HashMap(); 24 25 33 public void addInterceptor(Class event, Interceptor it) 34 throws InvalidInterceptorException { 35 Class itClass = it.getClass(); 36 int idx = event.getName().lastIndexOf('.'); 37 String shortName; 38 39 if (idx < 0) { 40 shortName = event.getName(); 41 } else { 42 shortName = event.getName().substring(idx + 1); 43 } 44 45 char[] content = shortName.toCharArray(); 46 content[0] = Character.toUpperCase(content[0]); 47 shortName = "on" + new String (content); 48 49 Method m; 50 51 try { 52 m = itClass.getMethod(shortName, new Class [] { event }); 53 } catch (Exception e) { 54 throw new InvalidInterceptorException(e); 55 } 56 57 List interceptors = (List) _interceptors.get(event); 58 59 if (interceptors == null) { 60 interceptors = new ArrayList(); 61 _interceptors.put(event, interceptors); 62 } 63 64 interceptors.add(new InterceptorInfo(it, m)); 65 } 66 67 71 public void dispatch(Event event) { 72 List interceptors = (List) _interceptors.get(event.getClass()); 73 74 if (interceptors == null) { 75 return; 76 } 77 78 InterceptorInfo info; 79 80 for (int i = 0; i < interceptors.size(); i++) { 81 info = (InterceptorInfo) interceptors.get(i); 82 83 try { 84 info.method.invoke(info.interceptor, new Object [] { event }); 85 } catch (Throwable t) { 86 if (t instanceof RuntimeException ) { 87 throw (RuntimeException ) t; 88 } else if (t instanceof InvocationTargetException ) { 89 Throwable t2 = ((InvocationTargetException ) t).getTargetException(); 90 91 if (t2 instanceof RuntimeException ) { 92 throw (RuntimeException ) t2; 93 } 94 } 95 96 handleError(t); 97 } 98 } 99 } 100 101 106 protected void handleError(Throwable t) { 107 Log.error(getClass(), t); 108 } 109 } 110 | Popular Tags |