gstackoverflow
gstackoverflow

Reputation: 37088

What is the proper way to make a search call in async mode in unboundId ldap sdk for java?

Based on https://docs.ldap.com/ldap-sdk/docs/getting-started/asynchronous.html

I try to implement a function which will return entry by DN in async manner. So my code is:

      val searchRequest = SearchRequest(
           EmptyAsyncListener(),
           dn,
           SearchScope.BASE,
           DereferencePolicy.NEVER,
           1,
           0,
           false,
           Filter.createPresenceFilter("objectClass"),
           *attributes,
       )
       val asyncRequestId = getConnection().asyncSearch(searchRequest)
       val ldapResult = asyncRequestId.get()

But at this case I see that ldapResult has a type SearchResult but I expect to have a SearchResultEntry (or collection of SearchResultEntry)

image

Eventually I was able to imlement working example using concurrent primitives from java.util.concurrent:

        val latch = CountDownLatch(1)
        val ref = AtomicReference<SearchResultEntry>()
        val searchRequest = SearchRequest(
            SimpleAsyncListener(latch, ref),
            dn,
            SearchScope.BASE,
            DereferencePolicy.NEVER,
            1,
            0,
            false,
            Filter.createPresenceFilter("objectClass"),
            *attributes,
        )
        getConnection().asyncSearch(searchRequest)
        latch.await()
        val entry = ref.get()

listener implementation:

class SimpleAsyncListener(private val latch: CountDownLatch, private val ref: AtomicReference<SearchResultEntry>) :
    AsyncSearchResultListener {


    override fun searchEntryReturned(@NotNull searchEntry: SearchResultEntry) {
        ref.set(searchEntry)
        latch.countDown()
    }


    override fun searchReferenceReturned(
        @NotNull searchReference: SearchResultReference
    ) {
        // No implementation required.
    }

    override fun searchResultReceived(
        @NotNull requestID: AsyncRequestID,
        @NotNull searchResult: SearchResult
    ) {

    }
}

It works but I am afraid that it is an overengeeniring. Is there way to achieve the same result in a simpler way ?

P.S. Example is artificial just to investigate async API

Upvotes: 0

Views: 34

Answers (1)

gstackoverflow
gstackoverflow

Reputation: 37088

Example is:

val resultListener = BasicAsyncSearchResultListener()
val searchRequest = SearchRequest(
    resultListener,
    dn,
    SearchScope.BASE,
    DereferencePolicy.NEVER,
    1,
    0,
    false,
    Filter.createPresenceFilter("objectClass"),
    *attributes,
)
val connection: LDAPConnection = getConnection()
val asyncRequestID = connection.asyncSearch(searchRequest)
// DO some staff
// and somewhere when we want to get the result:
asyncRequestID.get() // wai for job is done
val entries = resultListener.searchEntries

Upvotes: 0

Related Questions