001/* 002 Licensed to the Apache Software Foundation (ASF) under one 003 or more contributor license agreements. See the NOTICE file 004 distributed with this work for additional information 005 regarding copyright ownership. The ASF licenses this file 006 to you under the Apache License, Version 2.0 (the 007 "License"); you may not use this file except in compliance 008 with the License. You may obtain a copy of the License at 009 010 http://www.apache.org/licenses/LICENSE-2.0 011 012 Unless required by applicable law or agreed to in writing, 013 software distributed under the License is distributed on an 014 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 KIND, either express or implied. See the License for the 016 specific language governing permissions and limitations 017 under the License. 018 */ 019 020package org.apache.wiki.event; 021 022import org.apache.logging.log4j.LogManager; 023import org.apache.logging.log4j.Logger; 024import org.apache.wiki.util.Synchronizer; 025 026import java.lang.ref.WeakReference; 027import java.util.Collections; 028import java.util.Comparator; 029import java.util.ArrayList; 030import java.util.Map; 031import java.util.List; 032import java.util.Set; 033import java.util.TreeSet; 034import java.util.concurrent.ConcurrentHashMap; 035import java.util.concurrent.CopyOnWriteArrayList; 036import java.util.concurrent.atomic.AtomicBoolean; 037import java.util.concurrent.locks.ReentrantLock; 038 039/** 040 * A singleton class that manages the addition and removal of WikiEvent listeners to a event source, as well as the firing of events 041 * to those listeners. An "event source" is the object delegating its event handling to an inner delegating class supplied by this 042 * manager. The class being serviced is considered a "client" of the delegate. The WikiEventManager operates across any number of 043 * simultaneously-existing Engines since it manages all delegation on a per-object basis. Anything that might fire a WikiEvent 044 * (or any of its subclasses) can be a client. 045 * </p> 046 * 047 * <h3>Using a Delegate for Event Listener Management</h3> 048 * <p> 049 * Basically, rather than have all manner of client classes maintain their own listener lists, add and remove listener methods, any 050 * class wanting to attach listeners can simply request a delegate object to provide that service. The delegate handles the listener 051 * list, the add and remove listener methods. Firing events is then a matter of calling the WikiEventManager's 052 * {@link #fireEvent(Object,WikiEvent)} method, where the Object is the client. Prior to instantiating the event object, the 053 * client can call {@link #isListening(Object)} to see there are any listeners attached to its delegate. 054 * </p> 055 * 056 * <h3>Adding Listeners</h3> 057 * <p> 058 * Adding a WikiEventListener to an object is very simple: 059 * </p> 060 * <pre> 061 * WikiEventManager.addWikiEventListener( object, listener ); 062 * </pre> 063 * 064 * <h3>Removing Listeners</h3> 065 * <p> 066 * Removing a WikiEventListener from an object is very simple: 067 * </p> 068 * <pre> 069 * WikiEventManager.removeWikiEventListener( object, listener ); 070 * </pre> 071 * If you only have a reference to the listener, the following method will remove it from any clients managed by the WikiEventManager: 072 * <pre> 073 * WikiEventManager.removeWikiEventListener( listener ); 074 * </pre> 075 * 076 * <h3>Backward Compatibility: Replacing Existing <tt>fireEvent()</tt> Methods</h3> 077 * <p> 078 * Using one manager for all events processing permits consolidation of all event listeners and their associated methods in one place 079 * rather than having them attached to specific subcomponents of an application, and avoids a great deal of event-related cut-and-paste 080 * code. Convenience methods that call the WikiEventManager for event delegation can be written to maintain existing APIs. 081 * </p> 082 * <p> 083 * For example, an existing <tt>fireEvent()</tt> method might look something like this: 084 * </p> 085 * <pre> 086 * protected final void fireEvent( WikiEvent event ) { 087 * for( WikiEventListener listener : m_listeners ) { 088 * listener.actionPerformed( event ); 089 * } 090 * } 091 * </pre> 092 * <p> 093 * One disadvantage is that the above method is supplied with event objects, which are created even when no listener exists for them. 094 * In a busy wiki with many users unused/unnecessary event creation could be considerable. Another advantage is that in addition to 095 * the iterator, there must be code to support the addition and remove of listeners. The above could be replaced with the below code 096 * (and with no necessary local support for adding and removing listeners): 097 * </p> 098 * <pre> 099 * protected final void fireEvent( int type ) { 100 * if( WikiEventManager.isListening( this ) ) { 101 * WikiEventManager.fireEvent( this, new WikiEngineEvent( this, type ) ); 102 * } 103 * } 104 * </pre> 105 * <p> 106 * This only needs to be customized to supply the specific parameters for whatever WikiEvent you want to create. 107 * </p> 108 * 109 * <h3 id="preloading">Preloading Listeners</h3> 110 * <p> 111 * This may be used to create listeners for objects that don't yet exist, particularly designed for embedded applications that need 112 * to be able to listen for the instantiation of an Object, by maintaining a cache of client-less WikiEvent sources that set their 113 * client upon being popped from the cache. Each time any of the methods expecting a client parameter is called with a null parameter 114 * it will preload an internal cache with a client-less delegate object that will be popped and returned in preference to creating a 115 * new object. This can have unwanted side effects if there are multiple clients populating the cache with listeners. The only check 116 * is for a Class match, so be aware if others might be populating the client-less cache with listeners. 117 * </p> 118 * <h3>Listener lifecycle</h3> 119 * <p> 120 * Note that in most cases it is not necessary to remove a listener. As of 2.4.97, the listeners are stored as WeakReferences, and 121 * will be automatically cleaned at the next garbage collection, if you no longer hold a reference to them. Of course, until the 122 * garbage is collected, your object might still be getting events, so if you wish to avoid that, please remove it explicitly as 123 * described above. 124 * </p> 125 * @since 2.4.20 126 */ 127public final class WikiEventManager { 128 129 private static final Logger LOG = LogManager.getLogger(WikiEventManager.class); 130 131 /* If true, permits a WikiEventMonitor to be set. */ 132 private static final boolean c_permitMonitor = true; 133 134 /* Optional listener to be used as all-event monitor. */ 135 private static WikiEventListener c_monitor; 136 137 /* The Map of client object to WikiEventDelegate. */ 138 private final Map< Object, WikiEventDelegate > m_delegates = new ConcurrentHashMap<>(); 139 140 /* The List containing any preloaded WikiEventDelegates, guarded by m_delegates. */ 141 private final List< WikiEventDelegate > m_preloadCache = new ArrayList<>(); 142 143 /* Singleton instance of the WikiEventManager. */ 144 private static WikiEventManager c_instance; 145 146 /* 147 * Locks used to ensure thread safety when accessing shared resources. 148 * This locks provide more flexibility and capabilities than the intrinsic locking mechanism, 149 * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread 150 * waiting to acquire a lock. 151 * 152 * @see java.util.concurrent.locks.ReentrantLock 153 */ 154 private static final ReentrantLock instanceLock = new ReentrantLock(); 155 /* Guards m_delegates and m_preloadCache when they are changed together. */ 156 private final ReentrantLock delegatesLock = new ReentrantLock(); 157 private static final ReentrantLock removeWikiEventListenerLock = new ReentrantLock(); 158 159 /** Constructor for a WikiEventManager. */ 160 private WikiEventManager() { 161 c_instance = this; 162 LOG.debug( "instantiated WikiEventManager" ); 163 } 164 165 /** 166 * As this is a singleton class, this returns the single instance of this class provided with the property file 167 * filename and bit-wise application settings. 168 * 169 * @return A shared instance of the WikiEventManager 170 */ 171 public static WikiEventManager getInstance() { 172 if (c_instance == null) { 173 Synchronizer.synchronize(instanceLock, () -> { 174 if (c_instance == null) { 175 c_instance = new WikiEventManager(); 176 // start up any post-instantiation services here 177 } 178 }); 179 } 180 return c_instance; 181 } 182 183 // public/API methods ...................................................... 184 185 /** 186 * Registers a WikiEventListener with a WikiEventDelegate for the provided client object. 187 * 188 * <h3>Monitor Listener</h3> 189 * 190 * If <tt>client</tt> is a reference to the WikiEventManager class itself and the compile-time flag {@link #c_permitMonitor} is true, 191 * this attaches the listener as an all-event monitor, overwriting any previous listener (hence returning true). 192 * <p> 193 * You can remove any existing monitor by either calling this method with <tt>client</tt> as a reference to this class and the 194 * <tt>listener</tt> parameter as null, or {@link #removeWikiEventListener(Object,WikiEventListener)} with a <tt>client</tt> 195 * as a reference to this class. The <tt>listener</tt> parameter in this case is ignored. 196 * 197 * @param client the client of the event source 198 * @param listener the event listener 199 * @return true if the listener was added (i.e., it was not already in the list and was added) 200 */ 201 public static boolean addWikiEventListener( final Object client, final WikiEventListener listener ) { 202 if( client == WikiEventManager.class ) { 203 if ( c_permitMonitor ) { 204 c_monitor = listener; 205 } 206 return c_permitMonitor; 207 } 208 final WikiEventDelegate delegate = getInstance().getDelegateFor(client); 209 return delegate.addWikiEventListener(listener); 210 } 211 212 /** 213 * Un-registers a WikiEventListener with the WikiEventDelegate for the provided client object. 214 * 215 * @param client the client of the event source 216 * @param listener the event listener 217 * @return true if the listener was found and removed. 218 */ 219 public static boolean removeWikiEventListener( final Object client, final WikiEventListener listener ) { 220 if ( client == WikiEventManager.class ) { 221 c_monitor = null; 222 return true; 223 } 224 final WikiEventDelegate delegate = getInstance().getDelegateFor(client); 225 return delegate.removeWikiEventListener(listener); 226 } 227 228 /** 229 * Return the Set containing the WikiEventListeners attached to the delegate for the supplied client. If there are no 230 * attached listeners, returns an empty Iterator rather than null. Note that this will create a delegate for the client 231 * if it did not exist prior to the call. 232 * 233 * <h3>NOTE</h3> 234 * <p> 235 * This method returns a Set rather than an Iterator because of the high likelihood of the Set being modified while an 236 * Iterator might be active. This returns an unmodifiable reference to the actual Set containing the delegate's listeners. 237 * Any attempt to modify the Set will throw an {@link java.lang.UnsupportedOperationException}. This method is not 238 * synchronized and it should be understood that the composition of the backing Set may change at any time. 239 * </p> 240 * 241 * @param client the client of the event source 242 * @return an unmodifiable Set containing the WikiEventListeners attached to the client 243 * @throws java.lang.UnsupportedOperationException if any attempt is made to modify the Set 244 */ 245 public static Set<WikiEventListener> getWikiEventListeners( final Object client ) throws UnsupportedOperationException { 246 final WikiEventDelegate delegate = getInstance().getDelegateFor(client); 247 return delegate.getWikiEventListeners(); 248 } 249 250 /** 251 * Un-registers a WikiEventListener from any WikiEventDelegate client managed by this WikiEventManager. A true return value indicates 252 * the WikiEventListener was found and removed. 253 * 254 * @param listener the event listener 255 * @return true if the listener was found and removed. 256 */ 257 public static boolean removeWikiEventListener( final WikiEventListener listener ) { 258 final AtomicBoolean removed = new AtomicBoolean(false); 259 // get the Map.entry object for the entire Map, then check match on entry (listener) 260 final WikiEventManager mgr = getInstance(); 261 final Map< Object, WikiEventDelegate > sources = Collections.synchronizedMap( mgr.getDelegates() ); 262 Synchronizer.synchronize(removeWikiEventListenerLock, () -> { 263 // get an iterator over the Map.Enty objects in the map 264 for( final Map.Entry< Object, WikiEventDelegate > entry : sources.entrySet() ) { 265 // the entry value is the delegate 266 final WikiEventDelegate delegate = entry.getValue(); 267 268 // now see if we can remove the listener from the delegate (delegate may be null because this is a weak reference) 269 if( delegate != null && delegate.removeWikiEventListener( listener ) ) { 270 removed.set(true); // was removed 271 } 272 } 273 }); 274 return removed.get(); 275 } 276 277 private void removeDelegates() { 278 Synchronizer.synchronize( delegatesLock, () -> { 279 m_delegates.clear(); 280 m_preloadCache.clear(); 281 } ); 282 } 283 284 public static void shutdown() { 285 getInstance().removeDelegates(); 286 } 287 288 /** 289 * Returns true if there are one or more listeners registered with the provided client Object (undelegated event source). This locates 290 * any delegate and checks to see if it has any listeners attached. 291 * 292 * @param client the client Object 293 * @return True, if there is a listener for this client object. 294 */ 295 public static boolean isListening( final Object client ) { 296 return getInstance().getDelegateFor( client ).isListening(); 297 } 298 299 /** 300 * Notify all listeners of the WikiEventDelegate having a registered interest in change events of the supplied WikiEvent. 301 * 302 * @param client the client initiating the event. 303 * @param event the WikiEvent to fire. 304 */ 305 public static void fireEvent( final Object client, final WikiEvent event ) { 306 final WikiEventDelegate source = getInstance().getDelegateFor( client ); 307 source.fireEvent( event ); 308 if( c_monitor != null ) { 309 c_monitor.actionPerformed( event ); 310 } 311 } 312 313 // private and utility methods ............................................. 314 315 /** 316 * Return the client-to-delegate Map. 317 */ 318 private Map< Object, WikiEventDelegate > getDelegates() { 319 return m_delegates; 320 } 321 322 /** 323 * Returns a WikiEventDelegate for the provided client Object. If the parameter is a class reference, will generate and return a 324 * client-less WikiEventDelegate. If the parameter is not a Class and the delegate cache contains any objects matching the Class 325 * of any delegates in the cache, the first Class-matching delegate will be used in preference to creating a new delegate. 326 * If a null parameter is supplied, this will create a client-less delegate that will attach to the first incoming client (i.e., 327 * there will be no Class-matching requirement). 328 * 329 * @param client the client Object, or alternately a Class reference 330 * @return the WikiEventDelegate. 331 */ 332 private WikiEventDelegate getDelegateFor( final Object client ) { 333 return Synchronizer.synchronize( delegatesLock, () -> { 334 if( client == null || client instanceof Class ) { // then preload the cache 335 final WikiEventDelegate delegate = new WikiEventDelegate( client ); 336 m_preloadCache.add( delegate ); 337 m_delegates.put( client, delegate ); 338 return delegate; 339 } else if( !m_preloadCache.isEmpty() ) { 340 // then see if any of the cached delegates match the class of the incoming client 341 for( int i = m_preloadCache.size()-1 ; i >= 0 ; i-- ) { // start with most-recently added 342 final WikiEventDelegate delegate = m_preloadCache.get( i ); 343 if( delegate.getClientClass() == null || delegate.getClientClass().equals( client.getClass() ) ) { 344 // we have a hit, so use it, but only on a client we haven't seen before 345 if( !m_delegates.containsKey( client ) ) { 346 m_preloadCache.remove( delegate ); 347 m_delegates.put( client, delegate ); 348 return delegate; 349 } 350 } 351 } 352 } 353 // otherwise treat normally... 354 WikiEventDelegate delegate = m_delegates.get( client ); 355 if( delegate == null ) { 356 delegate = new WikiEventDelegate( client ); 357 m_delegates.put( client, delegate ); 358 } 359 return delegate; 360 } ); 361 } 362 363 364 // ......................................................................... 365 366 /** 367 * Inner delegating class that manages event listener addition and removal. Classes that generate events can obtain an instance of 368 * this class from the WikiEventManager and delegate responsibility to it. Interaction with this delegating class is done via the 369 * methods of the {@link WikiEventDelegate} API. 370 * 371 * @since 2.4.20 372 */ 373 private static final class WikiEventDelegate { 374 375 /* A list of event listeners for this instance. */ 376 private final CopyOnWriteArrayList< WeakReference< WikiEventListener > > m_listenerList = new CopyOnWriteArrayList<>(); 377 private Class< ? > m_class; 378 379 /** 380 * Constructor for an WikiEventDelegateImpl, provided with the client Object it will service, or the Class 381 * of client, the latter when used to preload a future incoming delegate. 382 */ 383 WikiEventDelegate( final Object client ) { 384 if( client instanceof Class ) { 385 m_class = ( Class< ? > )client; 386 } 387 } 388 389 /** 390 * Returns the class of the client-less delegate, null if this delegate is attached to a client Object. 391 */ 392 Class< ? > getClientClass() { 393 return m_class; 394 } 395 396 /** 397 * Return an unmodifiable Set containing the WikiEventListeners of this WikiEventDelegateImpl. If there are no attached listeners, 398 * returns an empty Set rather than null. 399 * 400 * @return an unmodifiable Set containing this delegate's WikiEventListeners 401 * @throws java.lang.UnsupportedOperationException if any attempt is made to modify the Set 402 */ 403 public Set< WikiEventListener > getWikiEventListeners() { 404 final TreeSet< WikiEventListener > set = new TreeSet<>( new WikiEventListenerComparator() ); 405 for( final WeakReference< WikiEventListener > wikiEventListenerWeakReference : m_listenerList ) { 406 final WikiEventListener l = wikiEventListenerWeakReference.get(); 407 if( l != null ) { 408 set.add( l ); 409 } 410 } 411 412 return Collections.unmodifiableSet( set ); 413 } 414 415 /** 416 * Adds <tt>listener</tt> as a listener for events fired by the WikiEventDelegate. 417 * 418 * @param listener the WikiEventListener to be added 419 * @return true if the listener was added (i.e., it was not already in the list and was added) 420 */ 421 public boolean addWikiEventListener( final WikiEventListener listener ) { 422 final boolean listenerAlreadyContained = m_listenerList.stream() 423 .map( WeakReference::get ) 424 .anyMatch( ref -> ref == listener ); 425 if( !listenerAlreadyContained ) { 426 return m_listenerList.add( new WeakReference<>( listener ) ); 427 } 428 return false; 429 } 430 431 /** 432 * Removes <tt>listener</tt> from the WikiEventDelegate. 433 * 434 * @param listener the WikiEventListener to be removed 435 * @return true if the listener was removed (i.e., it was actually in the list and was removed) 436 */ 437 public boolean removeWikiEventListener( final WikiEventListener listener ) { 438 return m_listenerList.removeIf( ref -> ref.get() == listener ); 439 } 440 441 /** 442 * Returns true if there are one or more listeners registered with this instance. 443 */ 444 public boolean isListening() { 445 return !m_listenerList.isEmpty(); 446 } 447 448 /** 449 * Notify all listeners having a registered interest in change events of the supplied WikiEvent. 450 */ 451 public void fireEvent( final WikiEvent event ) { 452 boolean needsCleanup = false; 453 for( final WeakReference< WikiEventListener > wikiEventListenerWeakReference : m_listenerList ) { 454 final WikiEventListener listener = wikiEventListenerWeakReference.get(); 455 if( listener != null ) { 456 listener.actionPerformed( event ); 457 } else { 458 needsCleanup = true; 459 } 460 } 461 462 // Remove all such listeners which have expired 463 if( needsCleanup ) { 464 m_listenerList.removeIf( ref -> ref.get() == null ); 465 } 466 } 467 } 468 469 private static class WikiEventListenerComparator implements Comparator< WikiEventListener > { 470 // TODO: This method is a critical performance bottleneck 471 @Override 472 public int compare( final WikiEventListener w0, final WikiEventListener w1 ) { 473 if( w1 == w0 || w0.equals( w1 ) ) { 474 return 0; 475 } 476 477 return w1.hashCode() - w0.hashCode(); 478 } 479 } 480 481}