001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.apache.commons.lang3.event; 019 020import java.io.ByteArrayOutputStream; 021import java.io.IOException; 022import java.io.ObjectInputStream; 023import java.io.ObjectOutputStream; 024import java.io.Serializable; 025import java.lang.reflect.InvocationHandler; 026import java.lang.reflect.InvocationTargetException; 027import java.lang.reflect.Method; 028import java.lang.reflect.Proxy; 029import java.util.ArrayList; 030import java.util.List; 031import java.util.Objects; 032import java.util.concurrent.CopyOnWriteArrayList; 033 034import org.apache.commons.lang3.ArrayUtils; 035import org.apache.commons.lang3.Validate; 036 037/** 038 * An EventListenerSupport object can be used to manage a list of event 039 * listeners of a particular type. The class provides 040 * {@link #addListener(Object)} and {@link #removeListener(Object)} methods 041 * for registering listeners, as well as a {@link #fire()} method for firing 042 * events to the listeners. 043 * 044 * <p> 045 * To use this class, suppose you want to support ActionEvents. You would do: 046 * </p> 047 * <pre><code> 048 * public class MyActionEventSource 049 * { 050 * private EventListenerSupport<ActionListener> actionListeners = 051 * EventListenerSupport.create(ActionListener.class); 052 * 053 * public void someMethodThatFiresAction() 054 * { 055 * ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "somethingCool"); 056 * actionListeners.fire().actionPerformed(e); 057 * } 058 * } 059 * </code></pre> 060 * 061 * <p> 062 * Serializing an {@link EventListenerSupport} instance will result in any 063 * non-{@link Serializable} listeners being silently dropped. 064 * </p> 065 * 066 * @param <L> the type of event listener that is supported by this proxy. 067 * 068 * @since 3.0 069 */ 070public class EventListenerSupport<L> implements Serializable { 071 072 /** Serialization version */ 073 private static final long serialVersionUID = 3593265990380473632L; 074 075 /** 076 * The list used to hold the registered listeners. This list is 077 * intentionally a thread-safe copy-on-write-array so that traversals over 078 * the list of listeners will be atomic. 079 */ 080 private List<L> listeners = new CopyOnWriteArrayList<>(); 081 082 /** 083 * The proxy representing the collection of listeners. Calls to this proxy 084 * object will be sent to all registered listeners. 085 */ 086 private transient L proxy; 087 088 /** 089 * Empty typed array for #getListeners(). 090 */ 091 private transient L[] prototypeArray; 092 093 /** 094 * Creates an EventListenerSupport object which supports the specified 095 * listener type. 096 * 097 * @param <T> the type of the listener interface 098 * @param listenerInterface the type of listener interface that will receive 099 * events posted using this class. 100 * 101 * @return an EventListenerSupport object which supports the specified 102 * listener type. 103 * 104 * @throws NullPointerException if {@code listenerInterface} is 105 * {@code null}. 106 * @throws IllegalArgumentException if {@code listenerInterface} is 107 * not an interface. 108 */ 109 public static <T> EventListenerSupport<T> create(final Class<T> listenerInterface) { 110 return new EventListenerSupport<>(listenerInterface); 111 } 112 113 /** 114 * Creates an EventListenerSupport object which supports the provided 115 * listener interface. 116 * 117 * @param listenerInterface the type of listener interface that will receive 118 * events posted using this class. 119 * 120 * @throws NullPointerException if {@code listenerInterface} is 121 * {@code null}. 122 * @throws IllegalArgumentException if {@code listenerInterface} is 123 * not an interface. 124 */ 125 public EventListenerSupport(final Class<L> listenerInterface) { 126 this(listenerInterface, Thread.currentThread().getContextClassLoader()); 127 } 128 129 /** 130 * Creates an EventListenerSupport object which supports the provided 131 * listener interface using the specified class loader to create the JDK 132 * dynamic proxy. 133 * 134 * @param listenerInterface the listener interface. 135 * @param classLoader the class loader. 136 * 137 * @throws NullPointerException if {@code listenerInterface} or 138 * {@code classLoader} is {@code null}. 139 * @throws IllegalArgumentException if {@code listenerInterface} is 140 * not an interface. 141 */ 142 public EventListenerSupport(final Class<L> listenerInterface, final ClassLoader classLoader) { 143 this(); 144 Objects.requireNonNull(listenerInterface, "listenerInterface"); 145 Objects.requireNonNull(classLoader, "classLoader"); 146 Validate.isTrue(listenerInterface.isInterface(), "Class %s is not an interface", 147 listenerInterface.getName()); 148 initializeTransientFields(listenerInterface, classLoader); 149 } 150 151 /** 152 * Create a new EventListenerSupport instance. 153 * Serialization-friendly constructor. 154 */ 155 private EventListenerSupport() { 156 } 157 158 /** 159 * Returns a proxy object which can be used to call listener methods on all 160 * of the registered event listeners. All calls made to this proxy will be 161 * forwarded to all registered listeners. 162 * 163 * @return a proxy object which can be used to call listener methods on all 164 * of the registered event listeners 165 */ 166 public L fire() { 167 return proxy; 168 } 169 170//********************************************************************************************************************** 171// Other Methods 172//********************************************************************************************************************** 173 174 /** 175 * Registers an event listener. 176 * 177 * @param listener the event listener (may not be {@code null}). 178 * 179 * @throws NullPointerException if {@code listener} is 180 * {@code null}. 181 */ 182 public void addListener(final L listener) { 183 addListener(listener, true); 184 } 185 186 /** 187 * Registers an event listener. Will not add a pre-existing listener 188 * object to the list if {@code allowDuplicate} is false. 189 * 190 * @param listener the event listener (may not be {@code null}). 191 * @param allowDuplicate the flag for determining if duplicate listener 192 * objects are allowed to be registered. 193 * 194 * @throws NullPointerException if {@code listener} is {@code null}. 195 * @since 3.5 196 */ 197 public void addListener(final L listener, final boolean allowDuplicate) { 198 Objects.requireNonNull(listener, "listener"); 199 if (allowDuplicate || !listeners.contains(listener)) { 200 listeners.add(listener); 201 } 202 } 203 204 /** 205 * Returns the number of registered listeners. 206 * 207 * @return the number of registered listeners. 208 */ 209 int getListenerCount() { 210 return listeners.size(); 211 } 212 213 /** 214 * Unregisters an event listener. 215 * 216 * @param listener the event listener (may not be {@code null}). 217 * 218 * @throws NullPointerException if {@code listener} is 219 * {@code null}. 220 */ 221 public void removeListener(final L listener) { 222 Objects.requireNonNull(listener, "listener"); 223 listeners.remove(listener); 224 } 225 226 /** 227 * Gets an array containing the currently registered listeners. 228 * Modification to this array's elements will have no effect on the 229 * {@link EventListenerSupport} instance. 230 * @return L[] 231 */ 232 public L[] getListeners() { 233 return listeners.toArray(prototypeArray); 234 } 235 236 /** 237 * Serialize. 238 * @param objectOutputStream the output stream 239 * @throws IOException if an IO error occurs 240 */ 241 private void writeObject(final ObjectOutputStream objectOutputStream) throws IOException { 242 final ArrayList<L> serializableListeners = new ArrayList<>(); 243 244 // don't just rely on instanceof Serializable: 245 ObjectOutputStream testObjectOutputStream = new ObjectOutputStream(new ByteArrayOutputStream()); 246 for (final L listener : listeners) { 247 try { 248 testObjectOutputStream.writeObject(listener); 249 serializableListeners.add(listener); 250 } catch (final IOException exception) { 251 //recreate test stream in case of indeterminate state 252 testObjectOutputStream = new ObjectOutputStream(new ByteArrayOutputStream()); 253 } 254 } 255 /* 256 * we can reconstitute everything we need from an array of our listeners, 257 * which has the additional advantage of typically requiring less storage than a list: 258 */ 259 objectOutputStream.writeObject(serializableListeners.toArray(prototypeArray)); 260 } 261 262 /** 263 * Deserialize. 264 * @param objectInputStream the input stream 265 * @throws IOException if an IO error occurs 266 * @throws ClassNotFoundException if the class cannot be resolved 267 */ 268 private void readObject(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException { 269 @SuppressWarnings("unchecked") // Will throw CCE here if not correct 270 final L[] srcListeners = (L[]) objectInputStream.readObject(); 271 272 this.listeners = new CopyOnWriteArrayList<>(srcListeners); 273 274 final Class<L> listenerInterface = ArrayUtils.getComponentType(srcListeners); 275 276 initializeTransientFields(listenerInterface, Thread.currentThread().getContextClassLoader()); 277 } 278 279 /** 280 * Initialize transient fields. 281 * @param listenerInterface the class of the listener interface 282 * @param classLoader the class loader to be used 283 */ 284 private void initializeTransientFields(final Class<L> listenerInterface, final ClassLoader classLoader) { 285 // Will throw CCE here if not correct 286 this.prototypeArray = ArrayUtils.newInstance(listenerInterface, 0); 287 createProxy(listenerInterface, classLoader); 288 } 289 290 /** 291 * Create the proxy object. 292 * @param listenerInterface the class of the listener interface 293 * @param classLoader the class loader to be used 294 */ 295 private void createProxy(final Class<L> listenerInterface, final ClassLoader classLoader) { 296 proxy = listenerInterface.cast(Proxy.newProxyInstance(classLoader, 297 new Class[] { listenerInterface }, createInvocationHandler())); 298 } 299 300 /** 301 * Create the {@link InvocationHandler} responsible for broadcasting calls 302 * to the managed listeners. Subclasses can override to provide custom behavior. 303 * @return ProxyInvocationHandler 304 */ 305 protected InvocationHandler createInvocationHandler() { 306 return new ProxyInvocationHandler(); 307 } 308 309 /** 310 * An invocation handler used to dispatch the event(s) to all the listeners. 311 */ 312 protected class ProxyInvocationHandler implements InvocationHandler { 313 314 /** 315 * Propagates the method call to all registered listeners in place of the proxy listener object. 316 * 317 * @param unusedProxy the proxy object representing a listener on which the invocation was called; not used 318 * @param method the listener method that will be called on all of the listeners. 319 * @param args event arguments to propagate to the listeners. 320 * @return the result of the method call 321 * @throws InvocationTargetException if an error occurs 322 * @throws IllegalArgumentException if an error occurs 323 * @throws IllegalAccessException if an error occurs 324 */ 325 @Override 326 public Object invoke(final Object unusedProxy, final Method method, final Object[] args) 327 throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { 328 for (final L listener : listeners) { 329 method.invoke(listener, args); 330 } 331 return null; 332 } 333 } 334}