Search code examples
unboundid-ldap-sdk

Search with paged control throws LDAPSearchException


I'm using unboundid-ldapsdk-3.1.1 and trying to iterate through entries using SimplePagedResultsControl.

Here is the snippet that I'm using:

...
    searchRequest = new SearchRequest(dn, scope.getLdapSearchScope(), filter);    
    ASN1OctetString resumeCookie = null;
    while (true)
    {
        searchRequest.setControls(new Control[] { new SimplePagedResultsControl(searchLimit, resumeCookie) });
        setControls(searchRequest, controls);
        searchResult = getConnectionPool().search(searchRequest);
        numSearches++;
        totalEntriesReturned += searchResult.getEntryCount();
        for (SearchResultEntry e : searchResult.getSearchEntries()) {
            // Do something with each entry...
        }
        LDAPTestUtils.assertHasControl(searchResult, SimplePagedResultsControl.PAGED_RESULTS_OID);
        try {
            SimplePagedResultsControl responseControl = SimplePagedResultsControl.get(searchResult);
            if (responseControl.moreResultsToReturn())
                resumeCookie = responseControl.getCookie();
            else
                break;
        } catch (LDAPException ex) {
            log.error("Error while accessing cookies" + ex.getMessage());
        }
    }

I keep getting error, when total entries is 100 and searchLimit is 100:

At first iteration responseControl.moreResultsToReturn() returns true, and at second iteration getConnectionPool().search(searchRequest); throws the LDAPSearchException(resultCode=2 (protocol error), numEntries=0, numReferences=0, errorMessage='paged results cookie is invalid')

What could be wrong with my code?


Solution

  • The connection pool typically has multiple connections and may not return the same connection where the initial paged search result request was issued. The solution is

    1. to get a connection from the pool,
    2. page through the results using this connection,
    3. return the connection to the pool