rt/emul/compact/src/main/java/java/beans/VetoableChangeSupport.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 26 Feb 2013 16:54:16 +0100
changeset 772 d382dacfd73f
parent 604 emul/compact/src/main/java/java/beans/VetoableChangeSupport.java@3fcc279c921b
permissions -rw-r--r--
Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
     1 /*
     2  * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 package java.beans;
    26 
    27 import java.io.Serializable;
    28 import java.io.ObjectStreamField;
    29 import java.io.ObjectOutputStream;
    30 import java.io.ObjectInputStream;
    31 import java.io.IOException;
    32 import java.util.Hashtable;
    33 import java.util.Map.Entry;
    34 import org.apidesign.bck2brwsr.emul.lang.System;
    35 
    36 /**
    37  * This is a utility class that can be used by beans that support constrained
    38  * properties.  It manages a list of listeners and dispatches
    39  * {@link PropertyChangeEvent}s to them.  You can use an instance of this class
    40  * as a member field of your bean and delegate these types of work to it.
    41  * The {@link VetoableChangeListener} can be registered for all properties
    42  * or for a property specified by name.
    43  * <p>
    44  * Here is an example of {@code VetoableChangeSupport} usage that follows
    45  * the rules and recommendations laid out in the JavaBeans&trade; specification:
    46  * <pre>
    47  * public class MyBean {
    48  *     private final VetoableChangeSupport vcs = new VetoableChangeSupport(this);
    49  *
    50  *     public void addVetoableChangeListener(VetoableChangeListener listener) {
    51  *         this.vcs.addVetoableChangeListener(listener);
    52  *     }
    53  *
    54  *     public void removeVetoableChangeListener(VetoableChangeListener listener) {
    55  *         this.vcs.removeVetoableChangeListener(listener);
    56  *     }
    57  *
    58  *     private String value;
    59  *
    60  *     public String getValue() {
    61  *         return this.value;
    62  *     }
    63  *
    64  *     public void setValue(String newValue) throws PropertyVetoException {
    65  *         String oldValue = this.value;
    66  *         this.vcs.fireVetoableChange("value", oldValue, newValue);
    67  *         this.value = newValue;
    68  *     }
    69  *
    70  *     [...]
    71  * }
    72  * </pre>
    73  * <p>
    74  * A {@code VetoableChangeSupport} instance is thread-safe.
    75  * <p>
    76  * This class is serializable.  When it is serialized it will save
    77  * (and restore) any listeners that are themselves serializable.  Any
    78  * non-serializable listeners will be skipped during serialization.
    79  *
    80  * @see PropertyChangeSupport
    81  */
    82 public class VetoableChangeSupport implements Serializable {
    83     private VetoableChangeListenerMap map = new VetoableChangeListenerMap();
    84 
    85     /**
    86      * Constructs a <code>VetoableChangeSupport</code> object.
    87      *
    88      * @param sourceBean  The bean to be given as the source for any events.
    89      */
    90     public VetoableChangeSupport(Object sourceBean) {
    91         if (sourceBean == null) {
    92             throw new NullPointerException();
    93         }
    94         source = sourceBean;
    95     }
    96 
    97     /**
    98      * Add a VetoableChangeListener to the listener list.
    99      * The listener is registered for all properties.
   100      * The same listener object may be added more than once, and will be called
   101      * as many times as it is added.
   102      * If <code>listener</code> is null, no exception is thrown and no action
   103      * is taken.
   104      *
   105      * @param listener  The VetoableChangeListener to be added
   106      */
   107     public void addVetoableChangeListener(VetoableChangeListener listener) {
   108         if (listener == null) {
   109             return;
   110         }
   111         if (listener instanceof VetoableChangeListenerProxy) {
   112             VetoableChangeListenerProxy proxy =
   113                     (VetoableChangeListenerProxy)listener;
   114             // Call two argument add method.
   115             addVetoableChangeListener(proxy.getPropertyName(),
   116                                       proxy.getListener());
   117         } else {
   118             this.map.add(null, listener);
   119         }
   120     }
   121 
   122     /**
   123      * Remove a VetoableChangeListener from the listener list.
   124      * This removes a VetoableChangeListener that was registered
   125      * for all properties.
   126      * If <code>listener</code> was added more than once to the same event
   127      * source, it will be notified one less time after being removed.
   128      * If <code>listener</code> is null, or was never added, no exception is
   129      * thrown and no action is taken.
   130      *
   131      * @param listener  The VetoableChangeListener to be removed
   132      */
   133     public void removeVetoableChangeListener(VetoableChangeListener listener) {
   134         if (listener == null) {
   135             return;
   136         }
   137         if (listener instanceof VetoableChangeListenerProxy) {
   138             VetoableChangeListenerProxy proxy =
   139                     (VetoableChangeListenerProxy)listener;
   140             // Call two argument remove method.
   141             removeVetoableChangeListener(proxy.getPropertyName(),
   142                                          proxy.getListener());
   143         } else {
   144             this.map.remove(null, listener);
   145         }
   146     }
   147 
   148     /**
   149      * Returns an array of all the listeners that were added to the
   150      * VetoableChangeSupport object with addVetoableChangeListener().
   151      * <p>
   152      * If some listeners have been added with a named property, then
   153      * the returned array will be a mixture of VetoableChangeListeners
   154      * and <code>VetoableChangeListenerProxy</code>s. If the calling
   155      * method is interested in distinguishing the listeners then it must
   156      * test each element to see if it's a
   157      * <code>VetoableChangeListenerProxy</code>, perform the cast, and examine
   158      * the parameter.
   159      *
   160      * <pre>
   161      * VetoableChangeListener[] listeners = bean.getVetoableChangeListeners();
   162      * for (int i = 0; i < listeners.length; i++) {
   163      *        if (listeners[i] instanceof VetoableChangeListenerProxy) {
   164      *     VetoableChangeListenerProxy proxy =
   165      *                    (VetoableChangeListenerProxy)listeners[i];
   166      *     if (proxy.getPropertyName().equals("foo")) {
   167      *       // proxy is a VetoableChangeListener which was associated
   168      *       // with the property named "foo"
   169      *     }
   170      *   }
   171      * }
   172      *</pre>
   173      *
   174      * @see VetoableChangeListenerProxy
   175      * @return all of the <code>VetoableChangeListeners</code> added or an
   176      *         empty array if no listeners have been added
   177      * @since 1.4
   178      */
   179     public VetoableChangeListener[] getVetoableChangeListeners(){
   180         return this.map.getListeners();
   181     }
   182 
   183     /**
   184      * Add a VetoableChangeListener for a specific property.  The listener
   185      * will be invoked only when a call on fireVetoableChange names that
   186      * specific property.
   187      * The same listener object may be added more than once.  For each
   188      * property,  the listener will be invoked the number of times it was added
   189      * for that property.
   190      * If <code>propertyName</code> or <code>listener</code> is null, no
   191      * exception is thrown and no action is taken.
   192      *
   193      * @param propertyName  The name of the property to listen on.
   194      * @param listener  The VetoableChangeListener to be added
   195      */
   196     public void addVetoableChangeListener(
   197                                 String propertyName,
   198                 VetoableChangeListener listener) {
   199         if (listener == null || propertyName == null) {
   200             return;
   201         }
   202         listener = this.map.extract(listener);
   203         if (listener != null) {
   204             this.map.add(propertyName, listener);
   205         }
   206     }
   207 
   208     /**
   209      * Remove a VetoableChangeListener for a specific property.
   210      * If <code>listener</code> was added more than once to the same event
   211      * source for the specified property, it will be notified one less time
   212      * after being removed.
   213      * If <code>propertyName</code> is null, no exception is thrown and no
   214      * action is taken.
   215      * If <code>listener</code> is null, or was never added for the specified
   216      * property, no exception is thrown and no action is taken.
   217      *
   218      * @param propertyName  The name of the property that was listened on.
   219      * @param listener  The VetoableChangeListener to be removed
   220      */
   221     public void removeVetoableChangeListener(
   222                                 String propertyName,
   223                 VetoableChangeListener listener) {
   224         if (listener == null || propertyName == null) {
   225             return;
   226         }
   227         listener = this.map.extract(listener);
   228         if (listener != null) {
   229             this.map.remove(propertyName, listener);
   230         }
   231     }
   232 
   233     /**
   234      * Returns an array of all the listeners which have been associated
   235      * with the named property.
   236      *
   237      * @param propertyName  The name of the property being listened to
   238      * @return all the <code>VetoableChangeListeners</code> associated with
   239      *         the named property.  If no such listeners have been added,
   240      *         or if <code>propertyName</code> is null, an empty array is
   241      *         returned.
   242      * @since 1.4
   243      */
   244     public VetoableChangeListener[] getVetoableChangeListeners(String propertyName) {
   245         return this.map.getListeners(propertyName);
   246     }
   247 
   248     /**
   249      * Reports a constrained property update to listeners
   250      * that have been registered to track updates of
   251      * all properties or a property with the specified name.
   252      * <p>
   253      * Any listener can throw a {@code PropertyVetoException} to veto the update.
   254      * If one of the listeners vetoes the update, this method passes
   255      * a new "undo" {@code PropertyChangeEvent} that reverts to the old value
   256      * to all listeners that already confirmed this update
   257      * and throws the {@code PropertyVetoException} again.
   258      * <p>
   259      * No event is fired if old and new values are equal and non-null.
   260      * <p>
   261      * This is merely a convenience wrapper around the more general
   262      * {@link #fireVetoableChange(PropertyChangeEvent)} method.
   263      *
   264      * @param propertyName  the programmatic name of the property that is about to change
   265      * @param oldValue      the old value of the property
   266      * @param newValue      the new value of the property
   267      * @throws PropertyVetoException if one of listeners vetoes the property update
   268      */
   269     public void fireVetoableChange(String propertyName, Object oldValue, Object newValue)
   270             throws PropertyVetoException {
   271         if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
   272             fireVetoableChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue));
   273         }
   274     }
   275 
   276     /**
   277      * Reports an integer constrained property update to listeners
   278      * that have been registered to track updates of
   279      * all properties or a property with the specified name.
   280      * <p>
   281      * Any listener can throw a {@code PropertyVetoException} to veto the update.
   282      * If one of the listeners vetoes the update, this method passes
   283      * a new "undo" {@code PropertyChangeEvent} that reverts to the old value
   284      * to all listeners that already confirmed this update
   285      * and throws the {@code PropertyVetoException} again.
   286      * <p>
   287      * No event is fired if old and new values are equal.
   288      * <p>
   289      * This is merely a convenience wrapper around the more general
   290      * {@link #fireVetoableChange(String, Object, Object)} method.
   291      *
   292      * @param propertyName  the programmatic name of the property that is about to change
   293      * @param oldValue      the old value of the property
   294      * @param newValue      the new value of the property
   295      * @throws PropertyVetoException if one of listeners vetoes the property update
   296      */
   297     public void fireVetoableChange(String propertyName, int oldValue, int newValue)
   298             throws PropertyVetoException {
   299         if (oldValue != newValue) {
   300             fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue));
   301         }
   302     }
   303 
   304     /**
   305      * Reports a boolean constrained property update to listeners
   306      * that have been registered to track updates of
   307      * all properties or a property with the specified name.
   308      * <p>
   309      * Any listener can throw a {@code PropertyVetoException} to veto the update.
   310      * If one of the listeners vetoes the update, this method passes
   311      * a new "undo" {@code PropertyChangeEvent} that reverts to the old value
   312      * to all listeners that already confirmed this update
   313      * and throws the {@code PropertyVetoException} again.
   314      * <p>
   315      * No event is fired if old and new values are equal.
   316      * <p>
   317      * This is merely a convenience wrapper around the more general
   318      * {@link #fireVetoableChange(String, Object, Object)} method.
   319      *
   320      * @param propertyName  the programmatic name of the property that is about to change
   321      * @param oldValue      the old value of the property
   322      * @param newValue      the new value of the property
   323      * @throws PropertyVetoException if one of listeners vetoes the property update
   324      */
   325     public void fireVetoableChange(String propertyName, boolean oldValue, boolean newValue)
   326             throws PropertyVetoException {
   327         if (oldValue != newValue) {
   328             fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
   329         }
   330     }
   331 
   332     /**
   333      * Fires a property change event to listeners
   334      * that have been registered to track updates of
   335      * all properties or a property with the specified name.
   336      * <p>
   337      * Any listener can throw a {@code PropertyVetoException} to veto the update.
   338      * If one of the listeners vetoes the update, this method passes
   339      * a new "undo" {@code PropertyChangeEvent} that reverts to the old value
   340      * to all listeners that already confirmed this update
   341      * and throws the {@code PropertyVetoException} again.
   342      * <p>
   343      * No event is fired if the given event's old and new values are equal and non-null.
   344      *
   345      * @param event  the {@code PropertyChangeEvent} to be fired
   346      * @throws PropertyVetoException if one of listeners vetoes the property update
   347      */
   348     public void fireVetoableChange(PropertyChangeEvent event)
   349             throws PropertyVetoException {
   350         Object oldValue = event.getOldValue();
   351         Object newValue = event.getNewValue();
   352         if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
   353             String name = event.getPropertyName();
   354 
   355             VetoableChangeListener[] common = this.map.get(null);
   356             VetoableChangeListener[] named = (name != null)
   357                         ? this.map.get(name)
   358                         : null;
   359 
   360             VetoableChangeListener[] listeners;
   361             if (common == null) {
   362                 listeners = named;
   363             }
   364             else if (named == null) {
   365                 listeners = common;
   366             }
   367             else {
   368                 listeners = new VetoableChangeListener[common.length + named.length];
   369                 System.arraycopy(common, 0, listeners, 0, common.length);
   370                 System.arraycopy(named, 0, listeners, common.length, named.length);
   371             }
   372             if (listeners != null) {
   373                 int current = 0;
   374                 try {
   375                     while (current < listeners.length) {
   376                         listeners[current].vetoableChange(event);
   377                         current++;
   378                     }
   379                 }
   380                 catch (PropertyVetoException veto) {
   381                     event = new PropertyChangeEvent(this.source, name, newValue, oldValue);
   382                     for (int i = 0; i < current; i++) {
   383                         try {
   384                             listeners[i].vetoableChange(event);
   385                         }
   386                         catch (PropertyVetoException exception) {
   387                             // ignore exceptions that occur during rolling back
   388                         }
   389                     }
   390                     throw veto; // rethrow the veto exception
   391                 }
   392             }
   393         }
   394     }
   395 
   396     /**
   397      * Check if there are any listeners for a specific property, including
   398      * those registered on all properties.  If <code>propertyName</code>
   399      * is null, only check for listeners registered on all properties.
   400      *
   401      * @param propertyName  the property name.
   402      * @return true if there are one or more listeners for the given property
   403      */
   404     public boolean hasListeners(String propertyName) {
   405         return this.map.hasListeners(propertyName);
   406     }
   407 
   408     /**
   409      * @serialData Null terminated list of <code>VetoableChangeListeners</code>.
   410      * <p>
   411      * At serialization time we skip non-serializable listeners and
   412      * only serialize the serializable listeners.
   413      */
   414     private void writeObject(ObjectOutputStream s) throws IOException {
   415         Hashtable<String, VetoableChangeSupport> children = null;
   416         VetoableChangeListener[] listeners = null;
   417         synchronized (this.map) {
   418             for (Entry<String, VetoableChangeListener[]> entry : this.map.getEntries()) {
   419                 String property = entry.getKey();
   420                 if (property == null) {
   421                     listeners = entry.getValue();
   422                 } else {
   423                     if (children == null) {
   424                         children = new Hashtable<String, VetoableChangeSupport>();
   425                     }
   426                     VetoableChangeSupport vcs = new VetoableChangeSupport(this.source);
   427                     vcs.map.set(null, entry.getValue());
   428                     children.put(property, vcs);
   429                 }
   430             }
   431         }
   432         ObjectOutputStream.PutField fields = s.putFields();
   433         fields.put("children", children);
   434         fields.put("source", this.source);
   435         fields.put("vetoableChangeSupportSerializedDataVersion", 2);
   436         s.writeFields();
   437 
   438         if (listeners != null) {
   439             for (VetoableChangeListener l : listeners) {
   440                 if (l instanceof Serializable) {
   441                     s.writeObject(l);
   442                 }
   443             }
   444         }
   445         s.writeObject(null);
   446     }
   447 
   448     private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
   449         this.map = new VetoableChangeListenerMap();
   450 
   451         ObjectInputStream.GetField fields = s.readFields();
   452 
   453         Hashtable<String, VetoableChangeSupport> children = (Hashtable<String, VetoableChangeSupport>) fields.get("children", null);
   454         this.source = fields.get("source", null);
   455         fields.get("vetoableChangeSupportSerializedDataVersion", 2);
   456 
   457         Object listenerOrNull;
   458         while (null != (listenerOrNull = s.readObject())) {
   459             this.map.add(null, (VetoableChangeListener)listenerOrNull);
   460         }
   461         if (children != null) {
   462             for (Entry<String, VetoableChangeSupport> entry : children.entrySet()) {
   463                 for (VetoableChangeListener listener : entry.getValue().getVetoableChangeListeners()) {
   464                     this.map.add(entry.getKey(), listener);
   465                 }
   466             }
   467         }
   468     }
   469 
   470     /**
   471      * The object to be provided as the "source" for any generated events.
   472      */
   473     private Object source;
   474 
   475     /**
   476      * @serialField children                                   Hashtable
   477      * @serialField source                                     Object
   478      * @serialField vetoableChangeSupportSerializedDataVersion int
   479      */
   480     private static final ObjectStreamField[] serialPersistentFields = {
   481             new ObjectStreamField("children", Hashtable.class),
   482             new ObjectStreamField("source", Object.class),
   483             new ObjectStreamField("vetoableChangeSupportSerializedDataVersion", Integer.TYPE)
   484     };
   485 
   486     /**
   487      * Serialization version ID, so we're compatible with JDK 1.1
   488      */
   489     static final long serialVersionUID = -5090210921595982017L;
   490 
   491     /**
   492      * This is a {@link ChangeListenerMap ChangeListenerMap} implementation
   493      * that works with {@link VetoableChangeListener VetoableChangeListener} objects.
   494      */
   495     private static final class VetoableChangeListenerMap extends ChangeListenerMap<VetoableChangeListener> {
   496         private static final VetoableChangeListener[] EMPTY = {};
   497 
   498         /**
   499          * Creates an array of {@link VetoableChangeListener VetoableChangeListener} objects.
   500          * This method uses the same instance of the empty array
   501          * when {@code length} equals {@code 0}.
   502          *
   503          * @param length  the array length
   504          * @return        an array with specified length
   505          */
   506         @Override
   507         protected VetoableChangeListener[] newArray(int length) {
   508             return (0 < length)
   509                     ? new VetoableChangeListener[length]
   510                     : EMPTY;
   511         }
   512 
   513         /**
   514          * Creates a {@link VetoableChangeListenerProxy VetoableChangeListenerProxy}
   515          * object for the specified property.
   516          *
   517          * @param name      the name of the property to listen on
   518          * @param listener  the listener to process events
   519          * @return          a {@code VetoableChangeListenerProxy} object
   520          */
   521         @Override
   522         protected VetoableChangeListener newProxy(String name, VetoableChangeListener listener) {
   523             return new VetoableChangeListenerProxy(name, listener);
   524         }
   525     }
   526 }