OSDN Git Service

2004-07-14 Jerry Quinn <jlquinn@optonline.net>
[pf3gnuchains/gcc-fork.git] / libjava / java / beans / EventHandler.java
1 /* java.beans.EventHandler
2    Copyright (C) 2004 Free Software Foundation, Inc.
3
4 This file is part of GNU Classpath.
5
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10  
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING.  If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
20
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library.  Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
25
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module.  An independent module is a module which is not derived from
33 or based on this library.  If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so.  If you do not wish to do so, delete this
36 exception statement from your version. */
37
38
39 package java.beans;
40
41 import java.lang.reflect.Constructor;
42 import java.lang.reflect.InvocationHandler;
43 import java.lang.reflect.InvocationTargetException;
44 import java.lang.reflect.Method;
45 import java.lang.reflect.Proxy;
46
47 /**
48  * class EventHandler
49  *
50  * EventHandler forms a bridge between dynamically created listeners and
51  * arbitrary properties and methods.  The idea is that a Proxy that implements
52  * a listener class calls the EventHandler when a listener method is called.
53  * The Proxy calls invoke(), which dispatches the event to a method, called
54  * the action, in another object, called the target.
55  *
56  * The event passed to the listener method is used to access a prespecified
57  * property, which in turn is passed to the action method.
58  * 
59  * Normally, call EventHandler.create(), which constructs an EventHandler and
60  * a Proxy for the listener interface.  When the listenerMethod gets called on
61  * the proxy, it in turn calls invoke on the attached EventHandler.  The
62  * invoke call extracts the bean property from the event object and passes it
63  * to the action method of target object.
64  *
65  * TODO: Add examples of using this thing.
66  * 
67  * @author Jerry Quinn (jlquinn@optonline.net)
68  * @since 1.4
69  */
70 public class EventHandler implements InvocationHandler
71 {
72   // The name of the method that will be implemented.  If null, any method.
73   private String listenerMethod;
74
75   // The object to call action on.
76   private Object target;
77
78   // The name of the method or property setter in target.
79   private String action;
80
81   // The property to extract from an event passed to listenerMethod.
82   private String property;
83
84   // String class doesn't already have a capitalize routine.
85   final private String capitalize(String s)
86   {
87     return s.substring(0, 1).toUpperCase() + s.substring(1);
88   }
89
90   /**
91    * Creates a new <code>EventHandler</code> instance.
92    *
93    * Typical creation is done with the create method, not by newing an
94    * EventHandler.
95    *
96    * This constructs an EventHandler that will connect the method
97    * listenerMethodName to target.action, extracting eventPropertyName from
98    * the first argument of listenerMethodName. and sending it to action.
99    *
100    *
101    *
102    * @param target Object that will perform the action.
103    * @param action A property or method of the target.
104    * @param eventPropertyName A readable property of the inbound event.
105    * @param listenerMethodName The listener method name triggering the action.
106    */
107   public EventHandler(Object target, String action, String eventPropertyName,
108                       String listenerMethodName)
109   {
110     this.target = target;
111     this.action = action;       // Turn this into a method or do we wait till
112                                 // runtime
113     property = eventPropertyName;
114     listenerMethod = listenerMethodName;
115   }
116
117   /**
118    * Return the event property name.
119    */
120   public String getEventPropertyName()
121   {
122     return property;
123   }
124
125   /**
126    * Return the listener's method name.
127    */
128   public String getListenerMethodName()
129   {
130     return listenerMethod;
131   }
132
133   /**
134    * Return the target object.
135    */
136   public Object getTarget()
137   {
138     return target;
139   }
140
141   /**
142    * Return the action method name.
143    */
144   public String getAction()
145   {
146     return action;
147   }
148
149   // Fetch a qualified property like a.b.c from object o.  The properties can
150   // be boolean isProp or object getProp properties.
151   //
152   // Returns a length 2 array with the first entry containing the value
153   // extracted from the property, and the second entry contains the class of
154   // the method return type.
155   //
156   // We play this game because if the method returns a native type, the return
157   // value will be a wrapper.  If we then take the type of the wrapper and use
158   // it to locate the action method that takes the native type, it won't match.
159   private Object[] getProperty(Object o, String prop)
160     throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
161   {
162     // Use the event object when the property name to extract is null.
163     if (prop == null)
164       return new Object[] {o, o.getClass()};
165
166     // Isolate the first property name from a.b.c.
167     int pos;
168     String rest = null;
169     if ((pos = prop.indexOf('.')) != -1)
170       {
171         rest = prop.substring(pos + 1);
172         prop = prop.substring(0, pos);
173       }
174
175     // Find a method named getProp.  It could be isProp instead.
176     Method getter;
177     try
178       {
179         // Look for boolean property getter isProperty
180         getter = o.getClass().getMethod("is" + capitalize(prop),
181                                                  null);
182       }
183     catch (NoSuchMethodException e)
184       {
185         // Look for regular property getter getProperty
186         getter = o.getClass().getMethod("get" + capitalize(prop),
187                                                  null);
188       }
189     Object val = getter.invoke(o, null);
190
191     if (rest != null)
192       return getProperty(val, rest);
193
194     return new Object[] {val, getter.getReturnType()};
195   }
196
197
198   /**
199    * Invoke the event handler.
200    *
201    * Proxy is the object that was used, method is the method that was invoked
202    * on object, and arguments is the set of arguments passed to this method.
203    * We assume that the first argument is the event to extract a property
204    * from.
205    *
206    * Assuming that method matches the listener method specified when creating
207    * this EventHandler, the desired property is extracted from this argument.
208    * The property is passed to target.setAction(), if possible.  Otherwise
209    * target.action() is called, where action is the string fed to the
210    * constructor.
211    *
212    * For now we punt on indexed properties.  Sun docs are not clear to me
213    * about this.
214    *
215    * @param proxy The proxy object that had method invoked on it.
216    * @param method The method that was invoked.
217    * @param arguments Arguments to method.
218    * @return Result of invoking target.action on the event property
219    */
220   public Object invoke(Object proxy, Method method, Object[] arguments)
221     throws Exception
222   {
223     // Do we actually need the proxy?
224     if (method == null)
225       throw new RuntimeException("Invoking null method");
226
227     // Listener methods that weren't specified are ignored.  If listenerMethod
228     // is null, then all listener methods are processed.
229     if (listenerMethod != null && !method.getName().equals(listenerMethod))
230       return null;
231
232     // Extract the first arg from arguments and do getProperty on arg
233     if (arguments == null || arguments.length == 0)
234       return null;
235     Object event = arguments[0]; // We hope :-)
236
237     // Obtain the property XXX propertyType keeps showing up null - why?
238     // because the object inside getProperty changes, but the ref variable
239     // can't change this way, dolt!  need a better way to get both values out
240     // - need method and object to do the invoke and get return type
241     Object v[] = getProperty(event, property);
242     Object val = v[0];
243     Class propertyType = (Class) v[1];
244
245     // Find the actual method of target to invoke.  We can't do this in the
246     // constructor since we don't know the type of the property we extracted
247     // from the event then.
248     //
249     // action can be either a property or a method.  Sun's docs seem to imply
250     // that action should be treated as a property first, and then a method,
251     // but don't specifically say it.
252     //
253     // XXX check what happens with native type wrappers.  The better thing to
254     // do is look at the return type of the method
255     Method actionMethod;
256     try
257       {
258         // Look for a property setter for action.
259         actionMethod = 
260           target.getClass().getMethod("set" + capitalize(action),
261                                       new Class[] {propertyType});
262       }
263     catch (NoSuchMethodException e)
264       {
265         // If action as property didn't work, try as method.
266         try
267           {
268             actionMethod = 
269               target.getClass().getMethod(action, new Class[] {propertyType});
270           }
271         catch (NoSuchMethodException e1)
272           {
273             // When event property is null, we may call action with no args
274             if (property == null)
275               {
276                 actionMethod =
277                   target.getClass().getMethod(action, null);
278                 return actionMethod.invoke(target, null);
279               }
280             else
281               throw e1;
282           }
283       }
284
285     // Invoke target.action(property)
286     return actionMethod.invoke(target, new Object[] {val});
287   }
288
289   /**
290    * Construct a new object to dispatch events.
291    *
292    * Equivalent to:
293    * create(listenerInterface, target, action, null, null)
294    *
295    * I.e. all listenerInterface methods are mapped to
296    * target.action(EventObject) or target.action(), if the first doesn't
297    * exist.
298    *
299    * @param listenerInterface Listener interface to implement.
300    * @param target Object to invoke action on.
301    * @param action Target property or method to invoke.
302    * @return A constructed proxy object.
303    */
304   public static Object create(Class listenerInterface, Object target, String action)
305   {
306     return create(listenerInterface, target, action, null, null);
307   }
308
309   /**
310    * Construct a new object to dispatch events.
311    *
312    * Equivalent to:
313    * create(listenerInterface, target, action, eventPropertyName, null)
314    *
315    * I.e. all listenerInterface methods are mapped to
316    * target.action(event.getEventPropertyName)
317    * 
318    *
319    * @param listenerInterface Listener interface to implement.
320    * @param target Object to invoke action on.
321    * @param action Target property or method to invoke.
322    * @param eventPropertyName Name of property to extract from event.
323    * @return A constructed proxy object.
324    */
325   public static Object create(Class listenerInterface, Object target,
326                               String action, String eventPropertyName)
327   {
328     return create(listenerInterface, target, action, eventPropertyName, null);
329   }
330
331
332   /**
333    * Construct a new object to dispatch events.
334    *
335    * This creates an object that acts as a proxy for the method
336    * listenerMethodName in listenerInterface.  When the listener method is
337    * activated, the object extracts eventPropertyName from the event.  Then it
338    * passes the property to the method target.setAction, or target.action if
339    * action is not a property with a setter.
340    *
341    * For example, EventHandler.create(MouseListener.class, test, "pushed",
342    * "button", "mouseClicked") generates a proxy object that implements
343    * MouseListener, at least for the method mouseClicked().  The other methods
344    * of MouseListener are null operations.  When mouseClicked is invoked, the
345    * generated object extracts the button property from the MouseEvent,
346    * i.e. event.getButton(), and calls test.setPushed() with the result.  So under
347    * the covers the following happens:
348    *
349    * <CODE>
350    * object.mouseClicked(MouseEvent e) { test.setPushed(e.getButton()); }
351    * </CODE>
352    *
353    * The Sun spec specifies a hierarchical property naming scheme.  Generally
354    * if the property is a.b.c, this corresponds to event.getA().getB().getC()
355    * or event.getA().getB().isC().  I don't see how you specify an indexed
356    * property, though.  This may be a limitation of the Sun implementation as
357    * well.  The spec doesn't seem to address it.
358    * 
359    * If eventPropertyName is null, EventHandler instead uses the event object
360    * in place of a property, i.e. it calls target.action(EventObject).  If
361    * there is no method named action taking an EventObject argument,
362    * EventHandler looks for a method target.action() taking no arguments.
363    *
364    * If listenerMethodName is null, every method in listenerInterface gets
365    * mapped to target.action, rather than the specified listener method.
366    * 
367    * @param listenerInterface Listener interface to implement.
368    * @param target Object to invoke action on.
369    * @param action Target method name to invoke.
370    * @param eventPropertyName Name of property to extract from event.
371    * @param listenerMethodName Listener method to implement.
372    * @return A constructed proxy object.
373    */
374   public static Object create(Class listenerInterface, Object target,
375                               String action, String eventPropertyName,
376                               String listenerMethodName)
377   {
378     // Create EventHandler instance
379     EventHandler eh = new EventHandler(target, action, eventPropertyName,
380                                        listenerMethodName);
381
382     // Create proxy object passing in the event handler
383     Object proxy = Proxy.newProxyInstance(listenerInterface.getClassLoader(),
384                                           new Class[] {listenerInterface},
385                                           eh);
386
387     return proxy;
388   }
389
390 }