private void dispatchException(Exception e, Request request) {
   IDSEventListener el = request.getListener();
   debugger.error(
       "EventService.dispatchException() - dispatching "
           + "exception to the listener: "
           + request.getRequestID()
           + " Listener: "
           + request.getListener(),
       e);
   el.eventError(e.toString());
 }
 /**
  * removes the listener from the list of Persistent Search listeners of the asynchronous seach for
  * the given search ID.
  *
  * @param request The request returned by the addListener
  * @supported.api
  */
 protected void removeListener(Request request) {
   LDAPConnection connection = request.getLDAPConnection();
   if (connection != null) {
     if (debugger.messageEnabled()) {
       debugger.message(
           "EventService.removeListener(): Removing "
               + "listener requestID: "
               + request.getRequestID()
               + " Listener: "
               + request.getListener());
     }
     try {
       if ((connection != null) && (connection.isConnected())) {
         connection.abandon(request.getId());
         connection.disconnect();
       }
     } catch (LDAPException le) {
       // Might have to check the reset codes and try to reset
       if (debugger.warningEnabled()) {
         debugger.warning(
             "EventService.removeListener(): " + "LDAPException, when trying to remove listener",
             le);
       }
     }
   }
 }
  /** Create naming event from a change control */
  private DSEvent createDSEvent(LDAPEntry entry, LDAPEntryChangeControl changeCtrl, Request req)
      throws Exception {
    DSEvent dsEvent = new DSEvent();

    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.createDSEvent() - Notifying event " + "to: " + req.getListener());
    }

    // Get the dn from the entry
    String dn = entry.getDN();
    dsEvent.setID(dn);

    // Get information on the type of change made
    int changeType = changeCtrl.getChangeType();
    dsEvent.setEventType(changeType);

    // Pass the search ID as the event's change info
    dsEvent.setSearchID(req.getRequestID());

    // set the object class name
    String className = entry.getAttribute("objectclass").toString();
    dsEvent.setClassName(className);

    return dsEvent;
  }
 /**
  * Response message carries a LDAP error. Response with the code 0 (SUCCESS), should never be
  * received as persistent search never completes, it has to be abandon. Referral messages are
  * ignored
  */
 protected boolean processResponseMessage(LDAPResponse rsp, Request request) {
   _retryErrorCodes = getPropertyRetryErrorCodes(EVENT_CONNECTION_ERROR_CODES);
   int resultCode = rsp.getResultCode();
   if (_retryErrorCodes.contains("" + resultCode)) {
     if (debugger.messageEnabled()) {
       debugger.message(
           "EventService.processResponseMessage() - "
               + "received LDAP Response for requestID: "
               + request.getRequestID()
               + " Listener: "
               + request.getListener()
               + "Need restarting");
     }
     resetErrorSearches(false);
   } else if (resultCode != 0 || resultCode != LDAPException.REFERRAL) {
     // If not neither of the cases then
     if (resultCode == LDAPException.BUSY) {
       debugger.error(
           "EventService.processResponseMessage() - received error BUSY, call retryManager");
       return retryManager(false);
     }
     LDAPException ex =
         new LDAPException(
             "Error result", rsp.getResultCode(), rsp.getErrorMessage(), rsp.getMatchedDN());
     dispatchException(ex, request);
   }
   return true;
 }
 public void run() {
   for (Iterator iter = requests.values().iterator(); iter.hasNext(); ) {
     Request req = (Request) iter.next();
     try {
       // First add a new listener and then remove the old one
       // that we do don't loose any responses to the message
       // Queue. However before adding check if request list
       // already has this listener initialized
       if (!_requestList.containsValue(req)) {
         addListener(
             req.getRequester(),
             req.getListener(),
             req.getBaseDn(),
             req.getScope(),
             req.getFilter(),
             req.getOperations());
       }
       removeListener(req);
       if (clearCaches) {
         // Send all entries changed notifications
         // only after successful establishment of psearch
         req.getListener().allEntriesChanged();
       }
       iter.remove();
     } catch (Exception e) {
       debugger.error("RetryTask", e);
       // Ignore exception and retry as we are in the process of
       // re-establishing the searches. Notify Listeners after the
       // attempt
     }
   }
   if (--numRetries == 0) {
     debugger.error("NumRetries " + numRetries);
     runPeriod = -1;
   }
 }
  /**
   * Reset all searches. Clear cache only if true is passed to argument
   *
   * @param clearCaches
   * @return <code>true</code> if the reset was successful, otherwise <code>false</code>
   */
  public synchronized boolean resetAllSearches(boolean clearCaches) {
    if (_shutdownCalled) {
      return false;
    }

    // Make a copy of the existing psearches
    Hashtable tmpReqList = new Hashtable();
    tmpReqList.putAll(_requestList);
    _requestList.clear(); // Will be updated in addListener method
    Collection reqList = tmpReqList.values();

    // Clear the cache, if parameter is set
    if (clearCaches && !reqList.isEmpty()) {
      for (Iterator iter = reqList.iterator(); iter.hasNext(); ) {
        Request req = (Request) iter.next();
        IDSEventListener el = req.getListener();
        el.allEntriesChanged();
      }
    }

    // Get the list of psearches to be enabled
    getListenerList();
    if (_allDisabled) {
      // All psearches are disabled, remove listeners if any and return
      if (debugger.messageEnabled()) {
        debugger.message("EventService.resetAllSearches(): " + "All psearches have been disabled");
      }
      if (!reqList.isEmpty()) {
        for (Iterator iter = reqList.iterator(); iter.hasNext(); ) {
          Request req = (Request) iter.next();
          removeListener(req);
          if (debugger.messageEnabled()) {
            debugger.message(
                "EventService.resetAllSearches(): "
                    + "Psearch disabled: "
                    + req.getListener().getClass().getName());
          }
        }
      }
      return true;
    }

    // Psearches are enabled, verify and reinitilize
    // Maintain the listeners to reinitialized in tmpListenerList
    Set tmpListenerList = new HashSet();
    Set newListenerList = new HashSet();
    for (int i = 0; i < listeners.length; i++) {
      if (listeners[i] != null) {
        // Check if the listener is present in reqList
        boolean present = false;
        for (Iterator iter = reqList.iterator(); iter.hasNext(); ) {
          Request req = (Request) iter.next();
          IDSEventListener el = req.getListener();
          String listenerClass = el.getClass().getName();
          if (listenerClass.equals(listeners[i])) {
            present = true;
            iter.remove();
            tmpListenerList.add(req);
          }
        }
        if (!present) {
          // Add the listner object
          if (debugger.messageEnabled()) {
            debugger.message(
                "EventService.resetAllSearches(): " + "Psearch being added: " + listeners[i]);
          }
          newListenerList.add(listeners[i]);
        }
      }
    }
    // Remove the listeners not configured
    if (!reqList.isEmpty()) {
      for (Iterator iter = reqList.iterator(); iter.hasNext(); ) {
        Request req = (Request) iter.next();
        removeListener(req);
        if (debugger.messageEnabled()) {
          debugger.message(
              "EventService.resetAllSearches(): "
                  + "Psearch disabled due to configuration changes: "
                  + req.getListener().getClass().getName());
        }
      }
    }
    // Reset the requested list
    reqList = tmpListenerList;

    // Determine the number of retry attempts in case of failure
    // If retry property is set to -1, retries will be done infinitely
    _numRetries = getPropertyIntValue(EVENT_CONNECTION_NUM_RETRIES, _numRetries);
    int retry = 1;
    boolean doItAgain =
        ((_numRetries == -1) || ((_numRetries != 0) && (retry <= _numRetries))) ? true : false;
    while (doItAgain) {
      if (debugger.messageEnabled()) {
        String str = (_numRetries == -1) ? "indefinitely" : Integer.toString(retry);
        debugger.message("EventService.resetAllSearches(): " + "retrying = " + str);
      }

      // Note: Avoid setting the messageQueue to null and just
      // try to disconnect the connections. That way we can be sure
      // that we have not lost any responses.
      for (Iterator iter = reqList.iterator(); iter.hasNext(); ) {
        try {
          Request request = (Request) iter.next();

          // First add a new listener and then remove the old one
          // that we do don't loose any responses to the message
          // Queue.
          addListener(
              request.getRequester(),
              request.getListener(),
              request.getBaseDn(),
              request.getScope(),
              request.getFilter(),
              request.getOperations());
          removeListener(request);
          iter.remove();
        } catch (LDAPServiceException e) {
          // Ignore exception and retry as we are in the process of
          // re-establishing the searches. Notify Listeners after the
          // attempt
          if (retry == _numRetries) {
            processNetworkError(e);
          }
        } catch (LDAPException le) {
          // Ignore exception and retry as we are in the process of
          // re-establishing the searches. Notify Listeners after the
          // attempt
          if (retry == _numRetries) {
            processNetworkError(le);
          }
        }
      }

      // Check if new listeners need to be added
      for (Iterator iter = newListenerList.iterator(); iter.hasNext(); ) {
        String listnerClass = (String) iter.next();
        try {
          Class thisClass = Class.forName(listnerClass);
          IDSEventListener listener = (IDSEventListener) thisClass.newInstance();
          _ideListenersMap.put(listnerClass, listener);
          _instance.addListener(
              getSSOToken(),
              listener,
              listener.getBase(),
              listener.getScope(),
              listener.getFilter(),
              listener.getOperations());
          if (debugger.messageEnabled()) {
            debugger.message(
                "EventService.resetAllSearches() - " + "successfully initialized: " + listnerClass);
          }
          iter.remove();
        } catch (Exception e) {
          debugger.error(
              "EventService.resetAllSearches() " + "Unable to start listener " + listnerClass, e);
        }
      }

      if (reqList.isEmpty() && newListenerList.isEmpty()) {
        return true;
      } else {
        if (_numRetries != -1) {
          doItAgain = (++retry <= _numRetries) ? true : false;
          if (!doItAgain) {
            // remove the requests fail to be resetted
            // would try to reinitialized the next time
            for (Iterator iter = reqList.iterator(); iter.hasNext(); ) {
              Request req = (Request) iter.next();
              removeListener(req);
              debugger.error(
                  "EventService.resetAll"
                      + "Searches(): unable to restart: "
                      + req.getListener().getClass().getName());
            }
            for (Iterator iter = newListenerList.iterator(); iter.hasNext(); ) {
              String req = (String) iter.next();
              debugger.error("EventService.resetAll" + "Searches(): unable add listener: " + req);
            }
          }
        }
      }
      if (doItAgain) {
        // Sleep before retry
        sleepRetryInterval();
      }
    } // end while loop
    return false;
  }
 /** Dispatch naming event to all listeners */
 private void dispatchEvent(DSEvent dirEvent, Request request) {
   IDSEventListener el = request.getListener();
   el.entryChanged(dirEvent);
 }