//// The contents of this file are subject to the terms of the Common Development and Distribution License (the License). You may not use this file except in compliance with the License. You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the specific language governing permission and limitations under the License. When distributing Covered Software, include this CDDL Header Notice in each file and include the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL Header, with the fields enclosed by brackets [] replaced by your own identifying information: "Portions copyright [year] [name of copyright owner]". Copyright 2026 3A Systems, LLC. //// :table-caption!: :opendj-sdk-example-version: 5.2.0 :opendj-sdk-javadoc: https://doc.openidentityplatform.org/opendj/apidocs/org/forgerock/opendj :opendj-sdk-examples: https://github.com/OpenIdentityPlatform/OpenDJ/blob/{opendj-sdk-example-version}/opendj-ldap-sdk-examples/src/main/java/org/forgerock/opendj/examples ifndef::env-site[] [#chap-ldap-sdk] endif::[] == Developing Java LDAP Clients ifdef::env-site[] anchor:chap-ldap-sdk[] endif::[] These examples use the OpenDJ LDAP SDK {opendj-sdk-example-version} to read server capabilities, manage directory entries over LDAPS, and reuse connections. [#ldap-sdk-maven] === Add the SDK to a Maven Project Use Java 11 or later and Maven 3. In xref:../getting-started/first-steps.adoc#getting-started-first-directory[Your First Directory], complete *Set Up and Start the Server*. Keep the evaluation server running and retain `quickstart-password.txt` for the Java exercises. If you already completed the Quickstart cleanup, restart the server with `opendj/bin/start-ds` from `opendj-quickstart` and re-create `quickstart-password.txt` there with the same Directory Manager password and permissions readable only by you. From the directory containing `opendj-quickstart`, create the Java project next to it. [source,bash] ---- mkdir -p ldap-client/src/main/java cd ldap-client ---- Save this `pom.xml` in `ldap-client`. The `opendj-grizzly` dependency brings in the `opendj-core` SDK and provides its LDAP network transport. [source,xml,subs="+attributes"] ---- 4.0.0 com.example ldap-client 1.0.0 11 11 org.openidentityplatform.opendj opendj-grizzly {opendj-sdk-example-version} ---- [#ldap-sdk-search] === Read the Root DSE The example reads the root DSE, an entry with server information, anonymously from the evaluation server's LDAP listener on port 1389. Save this class as `src/main/java/ReadCapabilities.java`. [source,java] ---- import org.forgerock.opendj.ldap.Connection; import org.forgerock.opendj.ldap.LDAPConnectionFactory; import org.forgerock.opendj.ldap.RootDSE; public final class ReadCapabilities { public static void main(String[] args) throws Exception { try (LDAPConnectionFactory factory = new LDAPConnectionFactory("localhost", 1389); Connection connection = factory.getConnection()) { RootDSE rootDse = RootDSE.readRootDSE(connection); var versions = rootDse.getSupportedLDAPVersions(); System.out.println("LDAPv3 supported = " + versions.contains(3)); System.out.println("Naming contexts = " + rootDse.getNamingContexts()); } } } ---- Run this command from the Maven project directory. [source,bash] ---- mvn -q compile exec:java -Dexec.mainClass=ReadCapabilities ---- The program prints `LDAPv3 supported = true`. Check that the naming contexts include `dc=example,dc=com`. The link:{opendj-sdk-javadoc}/ldap/RootDSE.html[`RootDSE`] class also exposes supported controls and extended operations. For an existing directory, obtain the server hostname, listener port and TLS mode, trusted CA certificates, service-account DN, and permitted search base from its administrator. Use `getNamingContexts()` on a verified connection to identify the directory suffixes visible to your account. Choose a search base within the suffix that contains the application data. * The *Bind DN* identifies the account whose credentials the client presents. * The *base DN* is the starting point of a search, such as `ou=People,dc=example,dc=com`. * The *entry DN* identifies a particular record, such as `uid=alice,ou=People,dc=example,dc=com`. Its first component, `uid=alice`, is the relative distinguished name (RDN). [#ldap-sdk-entry-operations] === Add, Search, Modify, and Delete Entries Use the running evaluation server with the `dc=example,dc=com` base entry and the `quickstart-password.txt` file created during setup. From `ldap-client`, export the evaluation server's public certificate and import it into a new client truststore. The password in these commands protects the example truststore, which contains only the public certificate. [source,bash] ---- server=../opendj-quickstart/opendj keytool -exportcert -rfc -alias server-cert \ -keystore "$server/config/keystore" -storepass:file "$server/config/keystore.pin" \ -file ldap-server.pem && keytool -importcert -noprompt -alias server-cert -file ldap-server.pem \ -keystore ldap-trust.p12 -storetype PKCS12 -storepass changeit ---- Save the TLS setup as `src/main/java/LocalLdaps.java`. The examples use it to open verified LDAPS connections to the evaluation server. [source,java] ---- import org.forgerock.opendj.ldap.LDAPConnectionFactory; import org.forgerock.opendj.ldap.SSLContextBuilder; import org.forgerock.opendj.ldap.TrustManagers; import org.forgerock.util.Options; final class LocalLdaps { static final String HOST = "localhost"; static final int PORT = 1636; static Options options() throws Exception { var trust = TrustManagers.checkUsingTrustStore( "ldap-trust.p12", "changeit".toCharArray(), "PKCS12"); var trustManager = TrustManagers.checkValidityDates(TrustManagers.checkHostName(HOST, trust)); var sslContext = new SSLContextBuilder().setTrustManager(trustManager).getSSLContext(); return Options.defaultOptions().set(LDAPConnectionFactory.SSL_CONTEXT, sslContext); } } ---- Save the following class as `src/main/java/ManageEntries.java`. The Directory Manager account is for this evaluation server. In an application, use an account with access to the entries and operations it needs. [source,java] ---- import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.UUID; import org.forgerock.opendj.ldap.Connection; import org.forgerock.opendj.ldap.DN; import org.forgerock.opendj.ldap.Filter; import org.forgerock.opendj.ldap.LDAPConnectionFactory; import org.forgerock.opendj.ldap.ModificationType; import org.forgerock.opendj.ldap.SearchScope; import org.forgerock.opendj.ldap.requests.Requests; import org.forgerock.opendj.ldif.ConnectionEntryReader; public final class ManageEntries { public static void main(String[] args) throws Exception { try (LDAPConnectionFactory factory = new LDAPConnectionFactory(LocalLdaps.HOST, LocalLdaps.PORT, LocalLdaps.options()); Connection connection = factory.getConnection()) { char[] password = Files.readAllLines(Path.of("../opendj-quickstart/quickstart-password.txt")) .get(0).toCharArray(); try { connection.bind("cn=Directory Manager", password); } finally { Arrays.fill(password, '\0'); } var identity = connection.extendedRequest(Requests.newWhoAmIExtendedRequest()); System.out.println("Authorization identity = " + identity.getAuthorizationID()); manageEntries(connection); } } private static void manageEntries(Connection connection) throws Exception { String ou = "SdkExample-" + UUID.randomUUID(); String branch = "ou=" + ou + ",dc=example,dc=com"; String person = "uid=sdk-alice," + branch; String newRdn = "uid=sdk-alice-renamed"; String renamed = newRdn + "," + branch; String originalMail = "sdk-alice@example.com"; String updatedMail = "sdk-alice-renamed@example.com"; connection.add(Requests.newAddRequest(branch) .addAttribute("objectClass", "top", "organizationalUnit") .addAttribute("ou", ou)); System.out.println("Created sample branch " + branch); connection.add(Requests.newAddRequest(person) .addAttribute("objectClass", "top", "inetOrgPerson") .addAttribute("uid", "sdk-alice") .addAttribute("cn", "Alice Jensen") .addAttribute("sn", "Jensen") .addAttribute("mail", originalMail)); var search = Requests.newSearchRequest(DN.valueOf(branch), SearchScope.SINGLE_LEVEL, Filter.equality("uid", "sdk-alice"), "cn", "mail"); try (ConnectionEntryReader reader = connection.search(search)) { while (reader.hasNext()) { if (reader.isEntry()) { var entry = reader.readEntry(); System.out.println("Found " + entry.getName() + " (" + entry.parseAttribute("cn").asString() + ", " + entry.parseAttribute("mail").asString() + ")"); } else { System.out.println("Search reference " + reader.readReference().getURIs()); } } } connection.modify(Requests.newModifyRequest(person) .addModification(ModificationType.ADD, "description", "LDAP SDK example") .addModification(ModificationType.REPLACE, "mail", updatedMail) .addModification(ModificationType.DELETE, "description", "LDAP SDK example")); System.out.println("Updated mail matches = " + connection.compare(person, "mail", updatedMail).matched()); System.out.println("Original mail matches = " + connection.compare(person, "mail", originalMail).matched()); connection.modifyDN(Requests.newModifyDNRequest(person, newRdn).setDeleteOldRDN(true)); System.out.println("Renamed to " + connection.readEntry(renamed, "mail").getName()); connection.delete(renamed); connection.delete(branch); System.out.println("Removed sample branch " + branch); } } ---- Run the program from `ldap-client`. [source,bash] ---- mvn -q compile exec:java -Dexec.mainClass=ManageEntries ---- Expect one search match, `true` for the updated email comparison, and `false` for the original email comparison. The program prints the renamed DN and removes its sample branch. If an operation fails after creation, use the printed branch DN to locate any remaining sample entries. Delete children before deleting their parent. * *Bind and extended operations.* Bind sets the connection's authentication state. The Who Am I? extended operation reports the resulting authorization identity. Use `RootDSE.getSupportedExtendedOperations()` to discover optional operations before sending them. To use StartTLS instead of LDAPS, keep the same trust settings, set `LDAPConnectionFactory.SSL_USE_STARTTLS` to `true`, and connect to the LDAP port with StartTLS enabled. The factory negotiates TLS before returning the connection. * *Search.* `readEntry` performs a base-object lookup by DN. `SINGLE_LEVEL` searches the immediate children, `WHOLE_SUBTREE` includes the base and all descendants, and `SUBORDINATES` searches all descendants where the server supports that scope. Use `Filter.equality` or `Filter.format` for application-supplied assertion values. The example reports continuation references. Follow them only to servers your application trusts. See xref:chap-ldap-operations.adoc#search-ldap[Searching the Directory] for the equivalent command-line operations. * *Modify and Modify DN.* Add and delete can change individual values of a multivalued attribute, and replace sets its new value list. Use `ModificationType.INCREMENT` on supported servers for integer increments. To move an entry, set the destination parent with `setNewSuperior` on the Modify DN request. Set `setDeleteOldRDN(true)` to remove the old naming value during a rename. * *Compare and delete.* `CompareResult.matched()` distinguishes the normal LDAP results `COMPARE_TRUE` and `COMPARE_FALSE`. A standard Delete removes a leaf entry. Use `deleteSubtree` only when the application intends to remove the whole branch and the server supports the subtree delete control. * *Abandon and Unbind.* Closing a `ConnectionEntryReader` cancels its search if it is still active. For other asynchronous operations, cancel the returned `LdapPromise` to request abandonment where supported. The Cancel extended operation is a separate request with its own result. Closing a direct LDAP connection sends Unbind when possible and releases the connection. * *Errors.* SDK methods report LDAP failures through `LdapException`. Use `e.getResult().getResultCode()` to distinguish conditions such as `ENTRY_ALREADY_EXISTS`, `NO_SUCH_OBJECT`, and `INSUFFICIENT_ACCESS_RIGHTS`. Use `e.getLocalizedMessage()` for messages presented to users. A search may yield entries before reporting a final LDAP error, such as `SIZE_LIMIT_EXCEEDED`. [#ldap-sdk-choose-search] === Choose a Search Method [cols="2,3",options="header"] |=== |Method |When to use it |`readEntry(dn, attributes)` |You already know the entry DN. A missing entry raises `EntryNotFoundException`. |`searchSingleEntry(request)` |You expect exactly one match, such as a unique login. Zero matches produce `CLIENT_SIDE_NO_RESULTS_RETURNED`. Multiple or otherwise unexpected results raise `MultipleEntriesFoundException`. |`search(request)` |You expect zero or more matches. Consume entries and continuation references through `ConnectionEntryReader`. A successful search can return zero entries. Consume the complete result to detect a final LDAP error. |=== Build filters with methods such as `Filter.equality("uid", login)` so that characters in the supplied value are treated literally. Request the attributes the application uses. For an optional single value, call `entry.parseAttribute("mail").asString("")` to supply a default. For a multivalued attribute, call `entry.parseAttribute("mail").asSetOfString()` and handle an empty set. A missing value can also reflect the account's read permissions. [#ldap-sdk-search-and-bind] === Find a User and Verify a Password Use a service account to find the user's DN, then bind as the user on a separate connection. Both connections use verified TLS. Keep the service account's privileges limited to the search and attributes required by the application. On the evaluation server, create a reader account and two sample records. Run the following Bash block from `ldap-client` after creating the LDAPS truststore. It uses `openssl` to generate temporary passwords and grants the reader search and read access to the sample users' login and object class. [source,bash] ---- sdk_admin() { local tool=$1 shift "../opendj-quickstart/opendj/bin/$tool" --hostname localhost --port 1636 --useSSL \ --trustStorePath ldap-trust.p12 --trustStorePassword changeit \ --bindDN 'cn=Directory Manager' \ --bindPasswordFile ../opendj-quickstart/quickstart-password.txt "$@" } SDK_READER_PASSWORD=$(openssl rand -hex 16) && SDK_USER_PASSWORD=$(openssl rand -hex 16) && export SDK_READER_PASSWORD SDK_USER_PASSWORD && sdk_admin ldapmodify --defaultAdd < { try { return connection.searchSingleEntryAsync(request).thenFinally(connection::close); } catch (RuntimeException e) { connection.close(); throw e; } }); System.out.println(lookup.getOrThrow().getName()); } } } ---- Run `mvn -q compile exec:java -Dexec.mainClass=FindUserAsync`. Expect the DN of `sdk-alice`. Use the link:{opendj-sdk-examples}/SearchAsync.java[`SearchAsync.java`] example for asynchronous searches that deliver multiple entries. Remove the sample entries before the evaluation server cleanup. Run this in the shell where you defined `sdk_admin`. [source,bash] ---- printf '%s\n' \ 'uid=sdk-alice,ou=SdkUsers,dc=example,dc=com' \ 'uid=sdk-bob,ou=SdkUsers,dc=example,dc=com' \ 'ou=SdkUsers,dc=example,dc=com' \ 'uid=sdk-reader,dc=example,dc=com' | sdk_admin ldapdelete unset SDK_READER_PASSWORD SDK_USER_PASSWORD ---- [#ldap-sdk-troubleshooting] === Diagnose Client Errors Log the operation, the result code from `LdapException.getResult()`, and the exception cause when applicable. Keep passwords out of logs. For an application-facing error, show a message appropriate for the failed operation. [cols="2,3",options="header"] |=== |Symptom |First check |Connection refused or `CLIENT_SIDE_CONNECT_ERROR` |Check that the server is running and that the host, port, and LDAP or LDAPS listener match. Run the Root DSE example against the evaluation listener to verify connectivity. |TLS handshake or certificate error |Check the exception cause for an untrusted certificate chain or a hostname mismatch. Verify that the LDAPS or StartTLS mode matches the listener and that the truststore contains the appropriate CA or the evaluation server's certificate. |`INVALID_CREDENTIALS` |Check the Bind DN, its password and the account state. Use a separate Bind to distinguish the service-account login from the user's login. |`INSUFFICIENT_ACCESS_RIGHTS` |Check the account reported by Who Am I? and the access control rules for the requested entry, operation, and attributes. |`NO_SUCH_OBJECT` or zero results |Check the search base or target DN first. If the base exists, check the search scope, filter and the account's search visibility. |`CLIENT_SIDE_TIMEOUT` or a server search limit |Check whether the timeout is on the client or the server. Narrow the scope or filter, and verify that the application handles partial search results before retrying. |=== If a write times out after transmission, read the entry before deciding whether to retry. A sequence of separate LDAP requests can leave changes from earlier requests in place. For integration tests, create a dedicated branch, assert the returned entry and error codes, and remove the branch after each test. Use a test OpenDJ instance for checks that depend on TLS, access controls, or server-side search limits. [#ldap-sdk-connection-settings] === LDAP Connection Settings Pass the server host, port, and an `Options` instance to link:{opendj-sdk-javadoc}/ldap/LDAPConnectionFactory.html[`LDAPConnectionFactory`]. Set each option with `Options.defaultOptions().set(option, value)`. A pool uses the options of its underlying factory when it opens physical connections. The defaults below apply to OpenDJ LDAP SDK {opendj-sdk-example-version}. [cols="2,1,4",options="header"] |=== |Option on `LDAPConnectionFactory` |Default |Effect |`CONNECT_TIMEOUT` |10 seconds |Maximum time to establish a physical connection, including TCP, TLS negotiation, an initial bind, and an initial heartbeat when applicable. Use zero to leave the TCP connection timeout to the operating system and disable the SDK's overall connection deadline. The JVM property `org.forgerock.opendj.io.connectTimeout` sets the default in milliseconds. |`REQUEST_TIMEOUT` |0 (disabled) |Client timeout for an LDAP operation waiting for a response. Grizzly reports `CLIENT_SIDE_TIMEOUT` when it expires. The JVM property `org.forgerock.opendj.io.requestTimeout` sets the default in milliseconds. Its legacy fallback is `org.forgerock.opendj.io.timeout`. |`AUTHN_BIND_REQUEST` |Unset |A `BindRequest` sent when opening each physical connection, after TLS negotiation if configured. A failed bind causes connection acquisition to fail. |`SSL_CONTEXT` |Unset |Supply an `SSLContext` to enable TLS and configure certificate validation. An unset context uses plaintext LDAP. |`SSL_USE_STARTTLS` |`false` |With an SSL context, `false` uses LDAPS and `true` upgrades an LDAP connection using StartTLS. |`SSL_ENABLED_PROTOCOLS` |Empty list |List of TLS protocol names enabled on secure connections. An empty list uses the SSL engine's enabled protocols. |`SSL_ENABLED_CIPHER_SUITES` |Empty list |List of TLS cipher suites enabled on secure connections. An empty list uses the SSL engine's enabled suites. |`HEARTBEAT_ENABLED` |`false` |Enable periodic LDAP searches on idle connections to detect an unresponsive server. |`HEARTBEAT_INTERVAL` |10 seconds |Interval between heartbeat checks. Use a positive duration when heartbeats are enabled. |`HEARTBEAT_TIMEOUT` |3 seconds |Response deadline for a periodic heartbeat. A shorter enabled request timeout can expire first. Use a positive duration when heartbeats are enabled. |`HEARTBEAT_SEARCH_REQUEST` |Root DSE base search |Override the heartbeat `SearchRequest`. The default uses the filter `(objectClass=*)` and requests no attributes (`1.1`). |`HEARTBEAT_SCHEDULER` |Shared SDK scheduler |Supply a `ScheduledExecutorService` for heartbeat work and the SDK's connection setup deadline. |=== Timeout and interval options use `org.forgerock.util.time.Duration`. Set the time unit when creating the duration, for example `Duration.duration(5, TimeUnit.SECONDS)`. The connection factory also accepts these inherited options and the Grizzly transport option. [cols="2,2,4",options="header"] |=== |Option |Default |Effect |`TCP_NO_DELAY` |`true` |Set the `TCP_NODELAY` socket option. The JVM property `org.forgerock.opendj.io.tcpNoDelay` sets the default. |`SO_KEEPALIVE` |`true` |Enable operating-system TCP keepalives through `SO_KEEPALIVE`. The JVM property `org.forgerock.opendj.io.keepAlive` sets the default. |`SO_REUSE_ADDRESS` |`true` |Set the `SO_REUSEADDR` socket option. The JVM property `org.forgerock.opendj.io.reuseAddress` sets the default. |`SO_LINGER_IN_SECONDS` |`-1` (disabled) |Configure how long socket close may wait for queued data. Use a negative value to disable `SO_LINGER`. The JVM property `org.forgerock.opendj.io.linger` sets the default in seconds. |`LDAP_DECODE_OPTIONS` |Default schema and factories |Supply `DecodeOptions` to select the schema resolver, entry factory, and attribute factory for decoding LDAP messages. |`TRANSPORT_PROVIDER` |First discovered provider |Select the `TransportProvider` by name. The `opendj-grizzly` dependency provides `Grizzly`. |`TRANSPORT_PROVIDER_CLASS_LOADER` |Class loader of `TransportProvider` |Specify the class loader used by `ServiceLoader` to find the transport provider. |`GrizzlyLDAPConnectionFactory.GRIZZLY_TRANSPORT` |Shared SDK transport |Supply a Grizzly `TCPNIOTransport` to configure the underlying network transport. |=== [#ldap-sdk-connection-pools] === Reuse LDAP Connections Create a link:{opendj-sdk-javadoc}/ldap/ConnectionPool.html[`ConnectionPool`] once for a workload with the same server and authentication settings. Borrow a connection for each unit of work and close it with try-with-resources to return it to the pool. Complete any asynchronous requests and close any search readers before returning the connection. Close the pool at application shutdown to release its connections and its underlying factory. Choose the pool configuration according to how long the application should keep idle connections and how many concurrent borrowers it can support. All three options create connections on demand. [cols="1,2,3",options="header"] |=== |Pool |Factory method in `Connections` |Behavior |Fixed |`newFixedConnectionPool(factory, 8)` |Keeps up to eight connections. Established idle connections stay in the pool until they become invalid or the pool closes. |Bounded cached |`newCachedConnectionPool(factory, 2, 8, 60, TimeUnit.SECONDS)` |Grows to at most eight connections. Idle connections above the core size of two become eligible for eviction after 60 seconds. The core size does not pre-open connections. |Default cached |`newCachedConnectionPool(factory)` |Uses a core size of zero, an effectively unbounded maximum, and a 60-second idle timeout. A burst can create as many connections as the workload demands within resource limits. |=== [#ldap-sdk-pool-settings] ==== Connection Pool Settings Set pool parameters when calling the factory methods in `Connections`. The cached defaults below apply to `newCachedConnectionPool(factory)`. [cols="1,2,4",options="header"] |=== |Argument |Default |Effect |`factory` |Required |Underlying `ConnectionFactory` used to open physical connections. |`poolSize` |Required for a fixed pool |Positive size passed to `newFixedConnectionPool`. The fixed pool uses this value as both its core and maximum size. |`corePoolSize` |`0` |Minimum number of established connections to retain during idle eviction. Use a value between zero and `maximumPoolSize`. A core size of zero lets an idle pool shrink to zero when eviction is enabled. |`maximumPoolSize` |`Integer.MAX_VALUE` |Positive limit on the number of physical connections in the cached pool. Use an explicit maximum to bound load on the directory server. |`idleTimeout` |60 seconds |Time an idle connection above the core size must wait before it is eligible for eviction. Cleanup runs periodically. Zero disables idle eviction. |`unit` |`TimeUnit.SECONDS` |Unit of the `idleTimeout` argument. Supply a unit whenever the timeout is positive. |`scheduler` |Shared SDK scheduler |The six-argument cached-pool overload accepts a `ScheduledExecutorService` for idle cleanup. The caller manages the lifetime of a supplied executor. |=== When a bounded pool is at maximum size and all its connections are in use, `getConnection()` waits for an available connection. That wait can exceed `CONNECT_TIMEOUT`, which applies to physical connection setup. Use `getConnectionAsync()` to acquire a connection without blocking the caller. Set the application concurrency limit and release connections promptly to control pool contention. Save this class as `src/main/java/ReadWithPool.java`. It borrows and returns a connection twice from the same pool, using the anonymous Root DSE read from the first example. [source,java] ---- import java.util.concurrent.TimeUnit; import org.forgerock.opendj.ldap.Connection; import org.forgerock.opendj.ldap.ConnectionPool; import org.forgerock.opendj.ldap.Connections; import org.forgerock.opendj.ldap.LDAPConnectionFactory; import org.forgerock.opendj.ldap.RootDSE; public final class ReadWithPool { public static void main(String[] args) throws Exception { LDAPConnectionFactory factory = new LDAPConnectionFactory("localhost", 1389); try (ConnectionPool pool = Connections.newCachedConnectionPool(factory, 2, 8, 60, TimeUnit.SECONDS)) { for (int i = 0; i < 2; i++) { try (Connection connection = pool.getConnection()) { var versions = RootDSE.readRootDSE(connection).getSupportedLDAPVersions(); System.out.println("LDAPv3 supported = " + versions.contains(3)); } } } } } ---- Run `mvn -q compile exec:java -Dexec.mainClass=ReadWithPool`. Both reads should print `LDAPv3 supported = true`. To try the other configurations, replace the pool construction with either alternative from the table. For an authenticated pool, configure TLS on the factory and set `LDAPConnectionFactory.AUTHN_BIND_REQUEST` to a bind request for the service account. The factory binds each physical connection before it is available to the pool. Perform per-user binds on separate, unpooled connections, because a bind changes the identity of the underlying connection. [#ldap-sdk-load-balancing] ==== Load Balancing Across Servers Use a pool per server to set its connection limits and reuse connections. Combine the pools with a load-balancing factory from link:{opendj-sdk-javadoc}/ldap/Connections.html[`Connections`] to choose which server or partition receives work. [cols="1,2,3",options="header"] |=== |Strategy |Factory method in `Connections` |Routing behavior |Round robin (RR) |`newRoundRobinLoadBalancer(pools, options)` |Selects a server when the caller borrows a connection. Rotates through the available servers to distribute connection acquisitions across equivalent replicas. |Failover |`newFailoverLoadBalancer(pools, options)` |Selects the first available server in the configured order when the caller borrows a connection. Put the preferred server or site first. |Least requests |`newLeastRequestsLoadBalancer(pools, options)` |Routes each LDAP request to the replica with the fewest in-flight requests tracked by this factory. Use it when concurrent requests have different durations. |DN affinity |`newAffinityRequestLoadBalancer(pools, options)` |Hashes the target DN to prefer the same replica for requests to that DN. Use the same replica order in each client that needs the same routing. |Partitioned distribution |`newFixedSizeDistributionLoadBalancer(partitionBaseDN, partitions, options)` |Uses a `ConsistentHashMap` to map each subtree immediately below the partition base DN to a partition. A search that spans partitions can fan out according to its base DN and scope. |=== Least-connections routing uses open connection counts and requires an external load balancer that supports that policy. With round robin or failover, operations on the borrowed connection use the same server. The request-level strategies borrow a connection for each operation and can send successive operations to different servers. Use a single server connection for operations that depend on the same LDAP session. Searches that span multiple partitions reject simple paged results, server-side sort, and virtual list view controls. Modify DN requests that move an entry across partition boundaries are rejected. The following `Connections` options apply to the four replica strategies. [cols="2,2,4",options="header"] |=== |Option |Default |Effect |`LOAD_BALANCER_MONITORING_INTERVAL` |1 second |Delay between connection attempts to factories marked offline. |`LOAD_BALANCER_EVENT_LISTENER` |`LoadBalancerEventListener.LOG_EVENTS` |Receive online and offline events. The default listener logs state changes. |`LOAD_BALANCER_SCHEDULER` |Shared SDK scheduler |Supply a `ScheduledExecutorService` to run reconnect checks. |=== Close the load-balancing factory at shutdown to close its underlying pools. If a write loses its connection before a response arrives, check the directory state before retrying the write. The link:{opendj-sdk-examples}/Proxy.java[`Proxy.java`] example combines pools with the `least-requests`, `fail-over`, `affinity`, and `distribution` modes. [#ldap-sdk-next-steps] === OpenDJ LDAP SDK Examples The `opendj-ldap-sdk-examples` module contains the following examples for OpenDJ {opendj-sdk-example-version}. Check the class documentation for command-line arguments, sample entries, and required server capabilities. Some of these examples use plaintext LDAP, fixed test credentials, or `TrustManagers.trustAll()`. Use the verified TLS configuration from xref:chap-ldap-sdk.adoc#ldap-sdk-entry-operations[Add, Search, Modify, and Delete Entries] when adapting these clients for application credentials. [cols="2,3",options="header"] |=== |Example |What it demonstrates |link:{opendj-sdk-examples}/GetInfo.java[`GetInfo`] |Reads the root DSE anonymously and prints supported controls, supported extended operations, or operational attributes as LDIF. |link:{opendj-sdk-examples}/SimpleAuth.java[`SimpleAuth`], link:{opendj-sdk-examples}/SimpleAuthAsync.java[`SimpleAuthAsync`] |Perform a simple bind, with options for LDAPS or StartTLS. The asynchronous version chains connection acquisition and bind. |link:{opendj-sdk-examples}/SASLAuth.java[`SASLAuth`] |Constructs a SASL PLAIN bind request and sends it over StartTLS. |link:{opendj-sdk-examples}/SearchBind.java[`SearchBind`], link:{opendj-sdk-examples}/SearchBindAsync.java[`SearchBindAsync`] |Prompt for an email address and password, find the user's DN by email, and bind as that user. The asynchronous version chains search and bind. |link:{opendj-sdk-examples}/Search.java[`Search`] |Searches by base DN, scope, filter, and requested attributes. Writes entries as LDIF and reports continuation references. |link:{opendj-sdk-examples}/SearchAsync.java[`SearchAsync`] |Processes entries and references with an asynchronous result handler and demonstrates the Cancel extended operation. |link:{opendj-sdk-examples}/ShortLife.java[`ShortLife`], link:{opendj-sdk-examples}/ShortLifeAsync.java[`ShortLifeAsync`] |Create, modify, rename, and delete a temporary entry using synchronous calls or a chain of asynchronous requests. |link:{opendj-sdk-examples}/Modify.java[`Modify`] |Applies a stream of LDIF change records from a file or standard input using `ConnectionChangeRecordWriter`. |link:{opendj-sdk-examples}/ModifyAsync.java[`ModifyAsync`] |Builds one Modify request from LDIF read from a file or standard input and submits it with `modifyAsync`. |link:{opendj-sdk-examples}/UpdateGroup.java[`UpdateGroup`], link:{opendj-sdk-examples}/UpdateGroupAsync.java[`UpdateGroupAsync`] |Add or remove a member of a static `groupOfNames` group. Use the Permissive Modify control when supported and otherwise compare membership before changing it. |link:{opendj-sdk-examples}/ParseAttributes.java[`ParseAttributes`] |Updates and reads a test entry, then converts attribute values to Java types such as integers, DNs, and timestamps. |link:{opendj-sdk-examples}/ReadSchema.java[`ReadSchema`] |Reads the server schema and prints a summary and any parsing warnings. |link:{opendj-sdk-examples}/UseSchema.java[`UseSchema`], link:{opendj-sdk-examples}/UseSchemaAsync.java[`UseSchemaAsync`] |Validate an entry from standard input against the server schema before adding it, using synchronous or asynchronous calls. |link:{opendj-sdk-examples}/Controls.java[`Controls`] |Discovers controls through the root DSE and demonstrates paged results, server-side sort, pre-read and post-read, and other controls. Select the method for the control you want to try. |link:{opendj-sdk-examples}/UseGenericControl.java[`UseGenericControl`] |Encodes a Pre-Read request control with ASN.1, attaches it to a Modify request, and decodes the response to retrieve the old attribute value. |link:{opendj-sdk-examples}/ExtendedOperations.java[`ExtendedOperations`] |Discovers supported extended operations and demonstrates Who Am I? and Password Modify. |link:{opendj-sdk-examples}/GetADChangeNotifications.java[`GetADChangeNotifications`] |Watches a naming context for changes using the Microsoft Active Directory notification control. |link:{opendj-sdk-examples}/PasswordResetForAD.java[`PasswordResetForAD`] |Changes or resets an Active Directory password by modifying `unicodePwd` over LDAPS. |link:{opendj-sdk-examples}/Server.java[`Server`] |Exposes entries from an LDIF file through an LDAP listener with an in-memory backend and optional LDAPS. |link:{opendj-sdk-examples}/Proxy.java[`Proxy`] |Starts an LDAP proxy that combines per-server connection pools with least-requests, failover, affinity, or distribution routing. |link:{opendj-sdk-examples}/ProxyBackend.java[`ProxyBackend`] |Implements the per-client request handler used by `Proxy`. It forwards operations with proxied authorization and uses a separate connection factory for binds. |link:{opendj-sdk-examples}/RewriterProxy.java[`RewriterProxy`] |Starts a proxy that rewrites a fixed DN suffix and attribute name between clients and an upstream server. |=== link:{opendj-sdk-examples}/ExampleUtils.java[`ExampleUtils`] provides shared command-line port parsing. link:{opendj-sdk-examples}/package-info.java[`package-info.java`] describes the package.