/*
  * Append the supplied (chain of) referrals onto the
  * end of the current (chain of) referrals.
  */
 @Override
 public void appendUnprocessedReferrals(LdapReferralException ex) {
   if (refEx != null) {
     refEx = refEx.appendUnprocessedReferrals(ex);
   } else {
     refEx = ex.appendUnprocessedReferrals(refEx);
   }
 }
  /*
   * Retrieve the next set of entries and/or referrals.
   */
  private void getNextBatch() throws NamingException {

    res = homeCtx.getSearchReply(enumClnt, res);
    if (res == null) {
      limit = posn = 0;
      return;
    }

    entries = res.entries;
    limit = (entries == null) ? 0 : entries.size(); // handle empty set
    posn = 0; // reset

    // minimize the number of calls to processReturnCode()
    // (expensive when batchSize is small and there are many results)
    if ((res.status != LdapClient.LDAP_SUCCESS)
        || ((res.status == LdapClient.LDAP_SUCCESS) && (res.referrals != null))) {

      try {
        // convert referrals into a chain of LdapReferralException
        homeCtx.processReturnCode(res, listArg);

      } catch (LimitExceededException | PartialResultException e) {
        setNamingException(e);
      }
    }

    // merge any newly received referrals with any current referrals
    if (res.refEx != null) {
      if (refEx == null) {
        refEx = res.refEx;
      } else {
        refEx = refEx.appendUnprocessedReferrals(res.refEx);
      }
      res.refEx = null; // reset
    }

    if (res.resControls != null) {
      homeCtx.respCtls = res.resControls;
    }
  }
  /*
   * Iterate through the URLs of a referral. If successful then perform
   * a search operation and merge the received results with the current
   * results.
   */
  protected final boolean hasMoreReferrals() throws NamingException {

    if ((refEx != null) && (refEx.hasMoreReferrals() || refEx.hasMoreReferralExceptions())) {

      if (homeCtx.handleReferrals == LdapClient.LDAP_REF_THROW) {
        throw (NamingException) (refEx.fillInStackTrace());
      }

      // process the referrals sequentially
      while (true) {

        LdapReferralContext refCtx =
            (LdapReferralContext) refEx.getReferralContext(homeCtx.envprops, homeCtx.reqCtls);

        try {

          update(getReferredResults(refCtx));
          break;

        } catch (LdapReferralException re) {

          // record a previous exception
          if (errEx == null) {
            errEx = re.getNamingException();
          }
          refEx = re;
          continue;

        } finally {
          // Make sure we close referral context
          refCtx.close();
        }
      }
      return hasMoreImpl();

    } else {
      cleanup();

      if (errEx != null) {
        throw errEx;
      }
      return (false);
    }
  }