1 /*
   2  * Copyright (c) 1999, 2000, 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 
  26 package com.sun.jndi.ldap;
  27 
  28 import java.util.Hashtable;
  29 import java.util.Vector;
  30 import java.util.Enumeration;
  31 import java.util.EventObject;
  32 
  33 import javax.naming.*;
  34 import javax.naming.directory.*;
  35 import javax.naming.event.*;
  36 import javax.naming.directory.SearchControls;
  37 import javax.naming.ldap.UnsolicitedNotificationListener;
  38 import javax.naming.ldap.UnsolicitedNotificationEvent;
  39 import javax.naming.ldap.UnsolicitedNotification;
  40 
  41 /**
  42  * This is a utility class that can be used by a context that supports
  43  * event notification.  You can use an instance of this class as a member field
  44  * of your context and delegate various work to it.
  45  * It is currently structured so that each context should have its own
  46  * EventSupport (instead of static version shared by all contexts
  47  * of a service provider).
  48  *<p>
  49  * This class supports two types of listeners: those that register for
  50  * NamingEvents, and those for UnsolicitedNotificationEvents (they can be mixed
  51  * into the same listener).
  52  * For NamingEvent listeners, it maintains a hashtable that maps
  53  * registration requests--the key--to
  54  * <em>notifiers</em>--the value. Each registration request consists of:
  55  *<ul>
  56  *<li>The name argument of the registration.
  57  *<li>The filter (default is "(objectclass=*)").
  58  *<li>The search controls (default is null SearchControls).
  59  *<li>The events that the listener is interested in. This is determined by
  60  * finding out which <tt>NamingListener</tt> interface the listener supports.
  61  *</ul>
  62  *<p>
  63  *A notifier (<tt>NamingEventNotifier</tt>) is a worker thread that is responsible
  64  *for gathering information for generating events requested by its listeners.
  65  *Each notifier maintains its own list of listeners; these listeners have
  66  *all made the same registration request (at different times) and implements
  67  *the same <tt>NamingListener</tt> interfaces.
  68  *<p>
  69  *For unsolicited listeners, this class maintains a vector, unsolicited.
  70  *When an unsolicited listener is registered, this class adds itself
  71  *to the context's LdapClient. When LdapClient receives an unsolicited
  72  *notification, it notifies this EventSupport to fire an event to the
  73  *the listeners. Special handling in LdapClient is done for the DISCONNECT
  74  *notification. [It results in the EventSupport firing also a
  75  *NamingExceptionEvent to the unsolicited listeners.]
  76  *<p>
  77  *
  78  *When a context no longer needs this EventSupport, it should invoke
  79  *cleanup() on it.
  80  *<p>
  81  *<h4>Registration</h4>
  82  *When a registration request is made, this class attempts to find an
  83  *existing notifier that's already working on the request. If one is
  84  *found, the listener is added to the notifier's list. If one is not found,
  85  *a new notifier is created for the listener.
  86  *
  87  *<h4>Deregistration</h4>
  88  *When a deregistration request is made, this class attemps to find its
  89  *corresponding notifier. If the notifier is found, the listener is removed
  90  *from the notifier's list. If the listener is the last listener on the list,
  91  *the notifier's thread is terminated and removed from this class's hashtable.
  92  *Nothing happens if the notifier is not found.
  93  *
  94  *<h4>Event Dispatching</h4>
  95  *The notifiers are responsible for gather information for generating events
  96  *requested by their respective listeners. When a notifier gets sufficient
  97  *information to generate an event, it creates invokes the
  98  *appropriate <tt>fireXXXEvent</tt> on this class with the information and list of
  99  *listeners. This causes an event and the list of listeners to be added
 100  *to the <em>event queue</em>.
 101  *This class maintains an event queue and a dispatching thread that dequeues
 102  *events from the queue and dispatches them to the listeners.
 103  *
 104  *<h4>Synchronization</h4>
 105  *This class is used by the main thread (LdapCtx) to add/remove listeners.
 106  *It is also used asynchronously by NamingEventNotifiers threads and
 107  *the context's Connection thread. It is used by the notifier threads to
 108  *queue events and to update the notifiers list when the notifiers exit.
 109  *It is used by the Connection thread to fire unsolicited notifications.
 110  *Methods that access/update the 'unsolicited' and 'notifiers' lists are
 111  *thread-safe.
 112  *
 113  * @author Rosanna Lee
 114  */
 115 final class EventSupport {
 116     final static private boolean debug = false;
 117 
 118     private LdapCtx ctx;
 119 
 120     /**
 121      * NamingEventNotifiers; hashed by search arguments;
 122      */
 123     private Hashtable notifiers = new Hashtable(11);
 124 
 125     /**
 126      * List of unsolicited notification listeners.
 127      */
 128     private Vector unsolicited = null;
 129 
 130     /**
 131      * Constructs EventSupport for ctx.
 132      * <em>Do we need to record the name of the target context?
 133      * Or can we assume that EventSupport is called on a resolved
 134      * context? Do we need other add/remove-NamingListener methods?
 135      * package private;
 136      */
 137     EventSupport(LdapCtx ctx) {
 138         this.ctx = ctx;
 139     }
 140 
 141     /**
 142      * Adds <tt>l</tt> to list of listeners interested in <tt>nm</tt>.
 143      */
 144     /*
 145      * Make the add/removeNamingListeners synchronized to:
 146      * 1. protect usage of 'unsolicited', which may be read by
 147      *    the Connection thread when dispatching unsolicited notification.
 148      * 2. ensure that NamingEventNotifier thread's access to 'notifiers'
 149      *    is safe
 150      */
 151     synchronized void addNamingListener(String nm, int scope,
 152         NamingListener l) throws NamingException {
 153 
 154         if (l instanceof ObjectChangeListener ||
 155             l instanceof NamespaceChangeListener) {
 156             NotifierArgs args = new NotifierArgs(nm, scope, l);
 157 
 158             NamingEventNotifier notifier =
 159                 (NamingEventNotifier) notifiers.get(args);
 160             if (notifier == null) {
 161                 notifier = new NamingEventNotifier(this, ctx, args, l);
 162                 notifiers.put(args, notifier);
 163             } else {
 164                 notifier.addNamingListener(l);
 165             }
 166         }
 167         if (l instanceof UnsolicitedNotificationListener) {
 168             // Add listener to this's list of unsolicited notifiers
 169             if (unsolicited == null) {
 170                 unsolicited = new Vector(3);
 171             }
 172 
 173             unsolicited.addElement(l);
 174         }
 175     }
 176 
 177     /**
 178      * Adds <tt>l</tt> to list of listeners interested in <tt>nm</tt>
 179      * and filter.
 180      */
 181     synchronized void addNamingListener(String nm, String filter,
 182         SearchControls ctls, NamingListener l) throws NamingException {
 183 
 184         if (l instanceof ObjectChangeListener ||
 185             l instanceof NamespaceChangeListener) {
 186             NotifierArgs args = new NotifierArgs(nm, filter, ctls, l);
 187 
 188             NamingEventNotifier notifier =
 189                 (NamingEventNotifier) notifiers.get(args);
 190             if (notifier == null) {
 191                 notifier = new NamingEventNotifier(this, ctx, args, l);
 192                 notifiers.put(args, notifier);
 193             } else {
 194                 notifier.addNamingListener(l);
 195             }
 196         }
 197         if (l instanceof UnsolicitedNotificationListener) {
 198             // Add listener to this's list of unsolicited notifiers
 199             if (unsolicited == null) {
 200                 unsolicited = new Vector(3);
 201             }
 202             unsolicited.addElement(l);
 203         }
 204     }
 205 
 206     /**
 207      * Removes <tt>l</tt> from all notifiers in this context.
 208      */
 209     synchronized void removeNamingListener(NamingListener l) {
 210         Enumeration allnotifiers = notifiers.elements();
 211         NamingEventNotifier notifier;
 212 
 213         if (debug) System.err.println("EventSupport removing listener");
 214 
 215         // Go through list of notifiers, remove 'l' from each.
 216         // If 'l' is notifier's only listener, remove notifier too.
 217         while (allnotifiers.hasMoreElements()) {
 218             notifier = (NamingEventNotifier)allnotifiers.nextElement();
 219             if (notifier != null) {
 220                 if (debug)
 221                     System.err.println("EventSupport removing listener from notifier");
 222                 notifier.removeNamingListener(l);
 223                 if (!notifier.hasNamingListeners()) {
 224                     if (debug)
 225                         System.err.println("EventSupport stopping notifier");
 226                     notifier.stop();
 227                     notifiers.remove(notifier.info);
 228                 }
 229             }
 230         }
 231 
 232         // Remove from list of unsolicited notifier
 233         if (debug) System.err.println("EventSupport removing unsolicited: " +
 234             unsolicited);
 235         if (unsolicited != null) {
 236             unsolicited.removeElement(l);
 237         }
 238 
 239     }
 240 
 241     synchronized boolean hasUnsolicited() {
 242         return (unsolicited != null && unsolicited.size() > 0);
 243     }
 244 
 245     /**
 246       * package private;
 247       * Called by NamingEventNotifier to remove itself when it encounters
 248       * a NamingException.
 249       */
 250     synchronized void removeDeadNotifier(NotifierArgs info) {
 251         if (debug) {
 252             System.err.println("EventSupport.removeDeadNotifier: " + info.name);
 253         }
 254         notifiers.remove(info);
 255     }
 256 
 257     /**
 258      * Fire an event to unsolicited listeners.
 259      * package private;
 260      * Called by LdapCtx when its clnt receives an unsolicited notification.
 261      */
 262     synchronized void fireUnsolicited(Object obj) {
 263         if (debug) {
 264             System.err.println("EventSupport.fireUnsolicited: " + obj + " "
 265                 + unsolicited);
 266         }
 267         if (unsolicited == null || unsolicited.size() == 0) {
 268             // This shouldn't really happen, but might in case
 269             // there is a timing problem that removes a listener
 270             // before a fired event event reaches here.
 271             return;
 272         }
 273 
 274         if (obj instanceof UnsolicitedNotification) {
 275 
 276             // Fire UnsolicitedNotification to unsolicited listeners
 277 
 278             UnsolicitedNotificationEvent evt =
 279                 new UnsolicitedNotificationEvent(ctx, (UnsolicitedNotification)obj);
 280             queueEvent(evt, unsolicited);
 281 
 282         } else if (obj instanceof NamingException) {
 283 
 284             // Fire NamingExceptionEvent to unsolicited listeners.
 285 
 286             NamingExceptionEvent evt =
 287                 new NamingExceptionEvent(ctx, (NamingException)obj);
 288             queueEvent(evt, unsolicited);
 289 
 290             // When an exception occurs, the unsolicited listeners
 291             // are automatically deregistered.
 292             // When LdapClient.processUnsolicited() fires a NamingException,
 293             // it will update its listener list so we don't have to.
 294             // Likewise for LdapCtx.
 295 
 296             unsolicited = null;
 297         }
 298     }
 299 
 300     /**
 301      * Stops notifier threads that are collecting event data and
 302      * stops the event queue from dispatching events.
 303      * Package private; used by LdapCtx.
 304      */
 305     synchronized void cleanup() {
 306         if (debug) System.err.println("EventSupport clean up");
 307         if (notifiers != null) {
 308             for (Enumeration ns = notifiers.elements(); ns.hasMoreElements(); ) {
 309                 ((NamingEventNotifier) ns.nextElement()).stop();
 310             }
 311             notifiers = null;
 312         }
 313         if (eventQueue != null) {
 314             eventQueue.stop();
 315             eventQueue = null;
 316         }
 317         // %%% Should we fire NamingExceptionEvents to unsolicited listeners?
 318     }
 319 
 320     /*
 321      * The queue of events to be delivered.
 322      */
 323     private EventQueue eventQueue;
 324 
 325     /**
 326      * Add the event and vector of listeners to the queue to be delivered.
 327      * An event dispatcher thread dequeues events from the queue and dispatches
 328      * them to the registered listeners.
 329      * Package private; used by NamingEventNotifier to fire events
 330      */
 331     synchronized void queueEvent(EventObject event, Vector vector) {
 332         if (eventQueue == null)
 333             eventQueue = new EventQueue();
 334 
 335         /*
 336          * Copy the vector in order to freeze the state of the set
 337          * of EventListeners the event should be delivered to prior
 338          * to delivery.  This ensures that any changes made to the
 339          * Vector from a target listener's method during the delivery
 340          * of this event will not take effect until after the event is
 341          * delivered.
 342          */
 343         Vector v = (Vector)vector.clone();
 344         eventQueue.enqueue(event, v);
 345     }
 346 
 347     // No finalize() needed because EventSupport is always owned by
 348     // an LdapCtx. LdapCtx's finalize() and close() always call cleanup() so
 349     // there is no need for EventSupport to have a finalize().
 350 }