/[classpath]/classpath/java/beans/PropertyChangeSupport.java
ViewVC logotype

Diff of /classpath/java/beans/PropertyChangeSupport.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.7 by mark, Tue Jan 22 22:26:59 2002 UTC revision 1.8 by ericb, Mon Apr 1 03:00:07 2002 UTC
# Line 1  Line 1 
1  /* java.beans.PropertyChangeSupport  /* PropertyChangeSupport.java -- support to manage property change listeners
2     Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.     Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation, Inc.
3    
4  This file is part of GNU Classpath.  This file is part of GNU Classpath.
5    
# Line 7  GNU Classpath is free software; you can Line 7  GNU Classpath is free software; you can
7  it under the terms of the GNU General Public License as published by  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)  the Free Software Foundation; either version 2, or (at your option)
9  any later version.  any later version.
10    
11  GNU Classpath is distributed in the hope that it will be useful, but  GNU Classpath is distributed in the hope that it will be useful, but
12  WITHOUT ANY WARRANTY; without even the implied warranty of  WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Line 37  exception statement from your version. * Line 37  exception statement from your version. *
37    
38    
39  package java.beans;  package java.beans;
40  import java.util.Hashtable;  
41  import java.util.Vector;  import java.io.IOException;
 import java.util.Enumeration;  
42  import java.io.ObjectInputStream;  import java.io.ObjectInputStream;
43  import java.io.ObjectOutputStream;  import java.io.ObjectOutputStream;
 import java.io.IOException;  
44  import java.io.Serializable;  import java.io.Serializable;
45    import java.util.ArrayList;
46    import java.util.Arrays;
47    import java.util.Hashtable;
48    import java.util.Iterator;
49    import java.util.Map.Entry;
50    import java.util.Vector;
51    
52  /**  /**
53   ** PropertyChangeSupport makes it easy to fire property   * PropertyChangeSupport makes it easy to fire property change events and
54   ** change events and handle listeners.   * handle listeners. It allows chaining of listeners, as well as filtering
55   **   * by property name. In addition, it will serialize only those listeners
56   ** @author John Keiser   * which are serializable, ignoring the others without problem. This class
57   ** @since JDK1.1   * is thread-safe.
58   ** @version 1.2.0, 15 Mar 1999   *
59   **/   * @author John Keiser
60     * @author Eric Blake <ebb9@email.byu.edu>
61  public class PropertyChangeSupport implements java.io.Serializable {   * @since 1.1
62          transient Hashtable propertyListeners = new Hashtable();   * @status updated to 1.4
63          transient Vector listeners = new Vector();   */
64          Hashtable children;  public class PropertyChangeSupport implements Serializable
65          Object source;  {
66          int propertyChangeSupportSerializedDataVersion = 2;    /**
67          private static final long serialVersionUID = 6401253773779951803L;     * Compatible with JDK 1.1+.
68       */
69          /**    private static final long serialVersionUID = 6401253773779951803L;
70           * Saves the state of the object to the stream. */  
71          private void writeObject(ObjectOutputStream stream) throws IOException {    /**
72                  children = propertyListeners.isEmpty() ? null : propertyListeners;     * Maps property names (String) to named listeners (PropertyChangeSupport).
73                  stream.defaultWriteObject();     * If this is a child instance, this field will be null.
74                  for (Enumeration e = listeners.elements(); e.hasMoreElements(); ) {     *
75                          PropertyChangeListener l = (PropertyChangeListener)e.nextElement();     * @serial the map of property names to named listener managers
76                          if (l instanceof Serializable)     * @since 1.2
77                            stream.writeObject(l);     */
78                  }    private Hashtable children;
79                  stream.writeObject(null);  
80          }    /**
81       * The non-null source object for any generated events.
82          /**     *
83           * Reads the object back from stream (deserialization).     * @serial the event source
84           */     */
85          private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {    private final Object source;
86                  stream.defaultReadObject();  
87                  propertyListeners = (children == null) ? new Hashtable() : children;    /**
88                  PropertyChangeListener l;     * A field to compare serialization versions - this class uses version 2.
89                  while ((l = (PropertyChangeListener)stream.readObject()) != null) {     *
90                          addPropertyChangeListener(l);     * @serial the serialization format
91                  }     */
92                  // FIXME: XXX: There is no spec for JDK 1.1 serialization    private final int propertyChangeSupportSerializedDataVersion = 2;
93                  // so it is unclear what to do if the value of  
94                  // propertyChangeSupportSerializedDataVersion is 1.    /**
95          }     * The list of all registered property listeners. If this instance was
96       * created by user code, this only holds the global listeners (ie. not tied
97          /** Create PropertyChangeSupport to work with a specific     * to a name), and may be null. If it was created by this class, as a
98           ** source bean.     * helper for named properties, then this vector will be non-null, and this
99           ** @param source the source bean to use.     * instance appears as a value in the <code>children</code> hashtable of
100           **/     * another instance, so that the listeners are tied to the key of that
101          public PropertyChangeSupport(Object source) {     * hashtable entry.
102                  this.source = source;     */
103          }    private transient Vector listeners;
104    
105          /** Adds a PropertyChangeListener to the list of listeners.    /**
106           ** All property change events will be sent to this listener.     * Create a PropertyChangeSupport to work with a specific source bean.
107           ** <P>     *
108           **     * @param source the source bean to use
109           ** The listener add is not unique: that is, <em>n</em> adds with     * @throws NullPointerException if source is null
110           ** the same listener will result in <em>n</em> events being sent     */
111           ** to that listener for every property change.    public PropertyChangeSupport(Object source)
112           ** <P>    {
113           **      this.source = source;
114           ** Adding a null listener will cause undefined behavior.      if (source == null)
115           **        throw new NullPointerException();
116           ** @param l the listener to add.    }
117           **/  
118          public void addPropertyChangeListener(PropertyChangeListener l) {    /**
119                  listeners.addElement(l);     * Adds a PropertyChangeListener to the list of global listeners. All
120          }     * property change events will be sent to this listener. The listener add
121       * is not unique: that is, <em>n</em> adds with the same listener will
122          /** Adds a PropertyChangeListener listening on the specified property.     * result in <em>n</em> events being sent to that listener for every
123           ** Events will be sent to the listener for that particular property.     * property change. Adding a null listener may cause a NullPointerException
124           ** <P>     * down the road. This method will unwrap a PropertyChangeListenerProxy,
125           **     * registering the underlying delegate to the named property list.
126           ** The listener add is not unique; that is, <em>n</em> adds on a     *
127           ** particular property for a particular listener will result in     * @param l the listener to add
128           ** <em>n</em> events being sent to that listener when that     */
129           ** property is changed.    public synchronized void addPropertyChangeListener(PropertyChangeListener l)
130           ** <P>    {
131           **      if (l instanceof PropertyChangeListenerProxy)
132           ** The effect is cumulative, too; if you are registered to listen        {
133           ** to receive events on all property changes, and then you          PropertyChangeListenerProxy p = (PropertyChangeListenerProxy) l;
134           ** register on a particular property, you will receive change          addPropertyChangeListener(p.propertyName,
135           ** events for that property twice.                                    (PropertyChangeListener) p.getListener());
136           ** <P>        }
137           **      else
138           ** Adding a null listener will cause undefined behavior.        {
139           **          if (listeners == null)
140           ** @param propertyName the name of the property to listen on.            listeners = new Vector();
141           ** @param l the listener to add.          listeners.add(l);
142           **/        }
143          public void addPropertyChangeListener(String propertyName, PropertyChangeListener l) {    }
144                  synchronized(propertyListeners) {  
145                          Vector v = (Vector)propertyListeners.get(propertyName);    /**
146                          try {     * Removes a PropertyChangeListener from the list of global listeners. If
147                                  v.addElement(l);     * any specific properties are being listened on, they must be deregistered
148                          } catch(NullPointerException e) {     * by themselves; this will only remove the general listener to all
149                                  /* If v is not found, create a new vector. */     * properties. If <code>add()</code> has been called multiple times for a
150                                  v = new Vector();     * particular listener, <code>remove()</code> will have to be called the
151                                  v.addElement(l);     * same number of times to deregister it. This method will unwrap a
152                                  propertyListeners.put(propertyName, v);     * PropertyChangeListenerProxy, removing the underlying delegate from the
153                          }     * named property list.
154                  }     *
155          }     * @param l the listener to remove
156       */
157          /** Removes a PropertyChangeListener from the list of listeners.    public synchronized void
158           ** If any specific properties are being listened on, they must      removePropertyChangeListener(PropertyChangeListener l)
159           ** be deregistered by themselves; this will only remove the    {
160           ** general listener to all properties.      if (l instanceof PropertyChangeListenerProxy)
161           ** <P>        {
162           **          PropertyChangeListenerProxy p = (PropertyChangeListenerProxy) l;
163           ** If <code>add()</code> has been called multiple times for a          removePropertyChangeListener(p.propertyName,
164           ** particular listener, <code>remove()</code> will have to be                                       (PropertyChangeListener) p.getListener());
165           ** called the same number of times to deregister it.        }
166           **      else if (listeners != null)
167           ** @param l the listener to remove.        {
168           **/          listeners.remove(l);
169          public void removePropertyChangeListener(PropertyChangeListener l) {          if (listeners.isEmpty())
170                  listeners.removeElement(l);            listeners = null;
171          }        }
172      }
173          /** Removes a PropertyChangeListener from listening to a specific property.  
174           ** <P>    /**
175           **     * Returns an array of all registered property change listeners. Those that
176           ** If <code>add()</code> has been called multiple times for a     * were registered under a name will be wrapped in a
177           ** particular listener on a property, <code>remove()</code> will     * <code>PropertyChangeListenerProxy</code>, so you must check whether the
178           ** have to be called the same number of times to deregister it.     * listener is an instance of the proxy class in order to see what name the
179           **     * real listener is registered under. If there are no registered listeners,
180           ** @param propertyName the property to stop listening on.     * this returns an empty array.
181           ** @param l the listener to remove.     *
182           **/     * @return the array of registered listeners
183          public void removePropertyChangeListener(String propertyName, PropertyChangeListener l) {     * @see PropertyChangeListenerProxy
184                  synchronized(propertyListeners) {     * @since 1.4
185                          Vector v = (Vector)propertyListeners.get(propertyName);     */
186                          try {    public synchronized PropertyChangeListener[] getPropertyChangeListeners()
187                                  v.removeElement(l);    {
188                                  if(v.size() == 0) {      ArrayList list = new ArrayList();
189                                          propertyListeners.remove(propertyName);      if (listeners != null)
190                                  }        list.addAll(listeners);
191                          } catch(NullPointerException e) {      if (children != null)
192                                  /* if v is not found, do nothing. */        {
193                          }          int i = children.size();
194                  }          Iterator iter = children.entrySet().iterator();
195          }          while (--i >= 0)
196              {
197          /** Fire a PropertyChangeEvent to all the listeners.              Entry e = (Entry) iter.next();
198           **              String name = (String) e.getKey();
199           ** @param event the event to fire.              Vector v = ((PropertyChangeSupport) e.getValue()).listeners;
200           **/              int j = v.size();
201          public void firePropertyChange(PropertyChangeEvent event) {              while (--j >= 0)
202                  for(int i=0;i<listeners.size();i++) {                list.add(new PropertyChangeListenerProxy
203                          ((PropertyChangeListener)listeners.elementAt(i)).propertyChange(event);                  (name, (PropertyChangeListener) v.get(j)));
204                  }            }
205                  Vector moreListeners = (Vector)propertyListeners.get(event.getPropertyName());        }
206                  if(moreListeners != null) {      return (PropertyChangeListener[])
207                          for(int i=0;i<moreListeners.size();i++) {        list.toArray(new PropertyChangeListener[list.size()]);
208                                  ((PropertyChangeListener)moreListeners.elementAt(i)).propertyChange(event);    }
209                          }  
210                  }    /**
211          }     * Adds a PropertyChangeListener listening on the specified property. Events
212       * will be sent to the listener only if the property name matches. The
213          /** Fire a PropertyChangeEvent containing the old and new values of the property to all the listeners.     * listener add is not unique; that is, <em>n</em> adds on a particular
214           **     * property for a particular listener will result in <em>n</em> events
215           ** @param propertyName the name of the property that changed.     * being sent to that listener when that property is changed. The effect is
216           ** @param oldVal the old value.     * cumulative, too; if you are registered to listen to receive events on
217           ** @param newVal the new value.     * all property changes, and then you register on a particular property,
218           **/     * you will receive change events for that property twice. Adding a null
219          public void firePropertyChange(String propertyName, Object oldVal, Object newVal) {     * listener may cause a NullPointerException down the road. This method
220                  firePropertyChange(new PropertyChangeEvent(source,propertyName,oldVal,newVal));     * will unwrap a PropertyChangeListenerProxy, registering the underlying
221          }     * delegate to the named property list if the names match, and discarding
222       * it otherwise.
223          /** Fire a PropertyChangeEvent containing the old and new values of the property to all the listeners.     *
224           **     * @param propertyName the name of the property to listen on
225           ** @param propertyName the name of the property that changed.     * @param l the listener to add
226           ** @param oldVal the old value.     * @throws NullPointerException if propertyName is null
227           ** @param newVal the new value.     */
228           **/    public synchronized void addPropertyChangeListener(String propertyName,
229          public void firePropertyChange(String propertyName, boolean oldVal, boolean newVal) {                                                       PropertyChangeListener l)
230                  firePropertyChange(new PropertyChangeEvent(source, propertyName, new Boolean(oldVal), new Boolean(newVal)));    {
231          }      while (l instanceof PropertyChangeListenerProxy)
232          {
233          /** Fire a PropertyChangeEvent containing the old and new values of the property to all the listeners.          PropertyChangeListenerProxy p = (PropertyChangeListenerProxy) l;
234           **          if (propertyName == null ? p.propertyName != null
235           ** @param propertyName the name of the property that changed.              : ! propertyName.equals(p.propertyName))
236           ** @param oldVal the old value.            return;
237           ** @param newVal the new value.          l = (PropertyChangeListener) p.getListener();
238           **/        }
239          public void firePropertyChange(String propertyName, int oldVal, int newVal) {      PropertyChangeSupport s = null;
240                  firePropertyChange(new PropertyChangeEvent(source, propertyName, new Integer(oldVal), new Integer(newVal)));      if (children == null)
241          }        children = new Hashtable();
242        else
243          /** Tell whether the specified property is being listened on or not.        s = (PropertyChangeSupport) children.get(propertyName);
244           ** This will only return <code>true</code> if there are listeners      if (s == null)
245           ** on all properties or if there is a listener specifically on this        {
246           ** property.          s = new PropertyChangeSupport(source);
247           **          s.listeners = new Vector();
248           ** @param propertyName the property that may be listened on          children.put(propertyName, s);
249           ** @return whether the property is being listened on        }
250           **/      s.listeners.add(l);
251           public boolean hasListeners(String propertyName) {    }
252                  return listeners.size() > 0  || propertyListeners.get(propertyName) != null;  
253           }    /**
254  }     * Removes a PropertyChangeListener from listening to a specific property.
255       * If <code>add()</code> has been called multiple times for a particular
256       * listener on a property, <code>remove()</code> will have to be called the
257       * same number of times to deregister it. This method will unwrap a
258       * PropertyChangeListenerProxy, removing the underlying delegate from the
259       * named property list if the names match.
260       *
261       * @param propertyName the property to stop listening on
262       * @param l the listener to remove
263       * @throws NullPointerException if propertyName is null
264       */
265      public synchronized void
266        removePropertyChangeListener(String propertyName, PropertyChangeListener l)
267      {
268        if (children == null)
269          return;
270        PropertyChangeSupport s
271          = (PropertyChangeSupport) children.get(propertyName);
272        if (s == null)
273          return;
274        while (l instanceof PropertyChangeListenerProxy)
275          {
276            PropertyChangeListenerProxy p = (PropertyChangeListenerProxy) l;
277            if (propertyName == null ? p.propertyName != null
278                : ! propertyName.equals(p.propertyName))
279              return;
280            l = (PropertyChangeListener) p.getListener();
281          }
282        s.listeners.remove(l);
283        if (s.listeners.isEmpty())
284          {
285            children.remove(propertyName);
286            if (children.isEmpty())
287              children = null;
288          }
289      }
290    
291      /**
292       * Returns an array of all property change listeners registered under the
293       * given property name. If there are no registered listeners, this returns
294       * an empty array.
295       *
296       * @return the array of registered listeners
297       * @throws NullPointerException if propertyName is null
298       * @since 1.4
299       */
300      public synchronized PropertyChangeListener[]
301        getPropertyChangeListeners(String propertyName)
302      {
303        if (children == null)
304          return new PropertyChangeListener[0];
305        PropertyChangeSupport s
306          = (PropertyChangeSupport) children.get(propertyName);
307        if (s == null)
308          return new PropertyChangeListener[0];
309        return (PropertyChangeListener[])
310          s.listeners.toArray(new PropertyChangeListener[s.listeners.size()]);
311      }
312    
313      /**
314       * Fire a PropertyChangeEvent containing the old and new values of the
315       * property to all the global listeners, and to all the listeners for the
316       * specified property name. This does nothing if old and new are non-null
317       * and equal.
318       *
319       * @param propertyName the name of the property that changed
320       * @param oldVal the old value
321       * @param newVal the new value
322       */
323      public void firePropertyChange(String propertyName,
324                                     Object oldVal, Object newVal)
325      {
326        firePropertyChange(new PropertyChangeEvent(source, propertyName,
327                                                   oldVal, newVal));
328      }
329    
330      /**
331       * Fire a PropertyChangeEvent containing the old and new values of the
332       * property to all the global listeners, and to all the listeners for the
333       * specified property name. This does nothing if old and new are equal.
334       *
335       * @param propertyName the name of the property that changed
336       * @param oldVal the old value
337       * @param newVal the new value
338       */
339      public void firePropertyChange(String propertyName, int oldVal, int newVal)
340      {
341        if (oldVal != newVal)
342          firePropertyChange(new PropertyChangeEvent(source, propertyName,
343                                                     new Integer(oldVal),
344                                                     new Integer(newVal)));
345      }
346    
347      /**
348       * Fire a PropertyChangeEvent containing the old and new values of the
349       * property to all the global listeners, and to all the listeners for the
350       * specified property name. This does nothing if old and new are equal.
351       *
352       * @param propertyName the name of the property that changed
353       * @param oldVal the old value
354       * @param newVal the new value
355       */
356      public void firePropertyChange(String propertyName,
357                                     boolean oldVal, boolean newVal)
358      {
359        if (oldVal != newVal)
360          firePropertyChange(new PropertyChangeEvent(source, propertyName,
361                                                     Boolean.valueOf(oldVal),
362                                                     Boolean.valueOf(newVal)));
363      }
364    
365      /**
366       * Fire a PropertyChangeEvent to all the global listeners, and to all the
367       * listeners for the specified property name. This does nothing if old and
368       * new values of the event are equal.
369       *
370       * @param event the event to fire
371       * @throws NullPointerException if event is null
372       */
373      public void firePropertyChange(PropertyChangeEvent event)
374      {
375        if (event.oldValue != null && event.oldValue.equals(event.newValue))
376          return;
377        Vector v = listeners; // Be thread-safe.
378        if (v != null)
379          {
380            int i = v.size();
381            while (--i >= 0)
382              ((PropertyChangeListener) v.get(i)).propertyChange(event);
383          }
384        Hashtable h = children; // Be thread-safe.
385        if (h != null && event.propertyName != null)
386          {
387            PropertyChangeSupport s
388              = (PropertyChangeSupport) h.get(event.propertyName);
389            if (s != null)
390              {
391                v = s.listeners; // Be thread-safe.
392                int i = v == null ? 0 : v.size();
393                while (--i >= 0)
394                  ((PropertyChangeListener) v.get(i)).propertyChange(event);
395              }
396          }
397      }
398    
399      /**
400       * Tell whether the specified property is being listened on or not. This
401       * will only return <code>true</code> if there are listeners on all
402       * properties or if there is a listener specifically on this property.
403       *
404       * @param propertyName the property that may be listened on
405       * @return whether the property is being listened on
406       * @throws NullPointerException if propertyName is null
407       */
408      public synchronized boolean hasListeners(String propertyName)
409      {
410        return listeners != null || (children != null
411                                     && children.get(propertyName) != null);
412      }
413    
414      /**
415       * Saves the state of the object to the stream.
416       *
417       * @param s the stream to write to
418       * @throws IOException if anything goes wrong
419       * @serialData this writes out a null-terminated list of serializable
420       *             global property change listeners (the listeners for a named
421       *             property are written out as the global listeners of the
422       *             children, when the children hashtable is saved)
423       */
424      private synchronized void writeObject(ObjectOutputStream s)
425        throws IOException
426      {
427        s.defaultWriteObject();
428        if (listeners != null)
429          {
430            int i = listeners.size();
431            while (--i >= 0)
432              if (listeners.get(i) instanceof Serializable)
433                s.writeObject(listeners.get(i));
434          }
435        s.writeObject(null);
436      }
437    
438      /**
439       * Reads the object back from stream (deserialization).
440       *
441       * XXX Since serialization for 1.1 streams was not documented, this may
442       * not work if propertyChangeSupportSerializedDataVersion is 1.
443       *
444       * @param s the stream to read from
445       * @throws IOException if reading the stream fails
446       * @throws ClassNotFoundException if deserialization fails
447       * @serialData this reads in a null-terminated list of serializable
448       *             global property change listeners (the listeners for a named
449       *             property are written out as the global listeners of the
450       *             children, when the children hashtable is saved)
451       */
452      private void readObject(ObjectInputStream s)
453        throws IOException, ClassNotFoundException
454      {
455        s.defaultReadObject();
456        PropertyChangeListener l = (PropertyChangeListener) s.readObject();
457        while (l != null)
458          {
459            addPropertyChangeListener(l);
460            l = (PropertyChangeListener) s.readObject();
461          }
462        // Sun is not as careful with children as we are, and lets some proxys
463        // in that can never receive events. So, we clean up anything that got
464        // serialized, to make sure our invariants hold.
465        if (children != null)
466          {
467            int i = children.size();
468            Iterator iter = children.entrySet().iterator();
469            while (--i >= 0)
470              {
471                Entry e = (Entry) iter.next();
472                String name = (String) e.getKey();
473                PropertyChangeSupport pcs = (PropertyChangeSupport) e.getValue();
474                if (pcs.listeners == null)
475                  pcs.listeners = new Vector();
476                if (pcs.children != null)
477                  pcs.listeners.addAll
478                    (Arrays.asList(pcs.getPropertyChangeListeners(name)));
479                if (pcs.listeners.size() == 0)
480                  iter.remove();
481                else
482                  pcs.children = null;
483              }
484            if (children.size() == 0)
485              children = null;
486          }
487      }
488    } // class PropertyChangeSupport

Legend:
Removed from v.1.7  
changed lines
  Added in v.1.8

savannah-hackers-public@gnu.org
ViewVC Help
Powered by ViewVC 1.1.26