Skip to content

Instantly share code, notes, and snippets.

@HarlemSquirrel
Created December 11, 2020 22:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarlemSquirrel/5f3be5bf6a2e9f1692cb079c99ce179a to your computer and use it in GitHub Desktop.
Save HarlemSquirrel/5f3be5bf6a2e9f1692cb079c99ce179a to your computer and use it in GitHub Desktop.
Example doing paged search with UnboundID Java SDK and OpenLDAP
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPSearchException;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchScope;
import com.unboundid.ldap.sdk.controls.SimplePagedResultsControl;
import com.unboundid.util.ssl.SSLUtil;
import com.unboundid.util.ssl.TrustAllTrustManager;
import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;
import com.unboundid.asn1.ASN1OctetString;
import java.security.GeneralSecurityException;
/**
* Example code for connecting to an LDAP directory using the UnboundID LDAP SDK. You can
* read the API docs, here:
*
* https://docs.ldap.com/ldap-sdk/docs/javadoc/index.html
*
* This client is similar to a command-line LDAP client, where you provide a
* filter, and attributes that you want to print out.
*
* To use this client, change the values for the "<insert your value here>"
* with the values that were provided to you by the IAM Team.
*
* To complie, you need to have the UnboundID LDAP SDK jar file on your
* classpath. You can download the jar, here:
*
* https://docs.ldap.com/ldap-sdk/files/unboundid-ldapsdk-3.1.0-se.zip
*
* This is just and example of the kind of code you need to write to interact
* with the SDK. By no means should you take this code and try to parse the
* output of it in your own code. Just use the main UnboundID LDAP SDK
* methods like getAttributeValue() and getAttributeValues(). You can see the
* full range of methods from getting values back from an entry, here:
*
* https://docs.ldap.com/ldap-sdk/docs/javadoc/index.html?com/unboundid/ldap/sdk/Entry.html
*
*
* We can create a sample OpenLDAP directory in Bash:
* docker run -p 1389:389 --name openldapserver --detach osixia/openldap:1.4.0
* sleep 5
* for i in {101..200}; do
* ldapmodify -H ldap://localhost:1389 -D "cn=admin,dc=example,dc=org" -w admin -a <<+
* dn: cn=user${i},dc=example,dc=org
* objectClass: person
* cn: user${i}
* sn: someone
* +
* done
*
* Then compile and run:
* jar_path="$HOME/Downloads/unboundid-ldapsdk-5.1.3/unboundid-ldapsdk.jar"; javac -cp .:$jar_path OpenLDAPClient.java && java -cp .:$jar_path OpenLDAPClient "(objectClass=*)" dn
*/
public class OpenLDAPClient {
/* LDAP Hostname */
private final String hostname = "localhost";
/* SSL LDAP Port */
private final int port = 1389;
/* LDAP Bind DN */
private final String bindDN = "cn=admin,dc=example,dc=org";
/* LDAP Bind Password */
private final String bindPWD = "admin";
/* LDAP Base DN - this is set to the DN of ou=people */
private final String baseDN = "dc=example,dc=org";
/* The LDAP connection gets saved in this variable */
private LDAPConnection conn = null;
/**
* Supply a search filter when you run the client, and optionally a
* space-separated list of attribute names.
*/
public static void main(String[] args) {
OpenLDAPClient edc = new OpenLDAPClient();
String filter = "";
if (args != null && args.length > 0) {
filter = args[0];
}
else {
System.out.println(
"You must provide an LDAP Search filter as an argument.");
System.exit(1);
}
List<SearchResultEntry> results = edc.search(filter);
if (results != null) {
System.out.println("");
for (SearchResultEntry entry : results) {
if (args.length == 1) {
System.out.println(entry.toLDIFString());
}
else {
// System.out.println("dn: " + entry.getDN());
// for (String attribute : args) {
// edc.printAttributeValues(entry, attribute);
// }
// System.out.println("");
}
}
System.out.println("Number of results found: " + results.size() +
"\n");
}
else {
System.out.println("No results found");
}
}
/**
* Prints out the name and value of the provided attribute.
*
* @param entry A SearchResultEntry entry
* @param attribute The name of the attribute that you want printed
*/
protected void printAttributeValues(
final SearchResultEntry entry, final String attribute) {
final String[] values = entry.getAttributeValues(attribute);
if (values != null && values.length > 0) {
for (String value : values) {
System.out.println(attribute + ": " + value);
}
}
}
/**
* Searches the directory for the provided filter.
*
* @param filter A valid LDAP filter string
* @return a {@code List} of {@code SearchResultEntry} objects.
*/
protected List<SearchResultEntry> search(final String filter) {
return search(filter, this.baseDN, SearchScope.SUBORDINATE_SUBTREE,
"*");
}
/**
* Searches the directory for the provided filter.
*
* @param filter A valid LDAP filter string
* @param attributes A list of attributes that you want returned from
* LDAP
* @return a {@code List} of {@code SearchResultEntry} objects.
*/
protected List<SearchResultEntry> search(final String filter,
String... attributes) {
return search(filter, this.baseDN, SearchScope.SUBORDINATE_SUBTREE,
attributes);
}
/**
* Searches the directory for the provided filter.
*
* @param filter A valid LDAP filter string
* @param base The LDAP search base you want to use
* @param scope A SearchScope that you want to use
* @param attributes A list of attributes that you want returned from
* LDAP
* @return a {@code List} of {@code SearchResultEntry} objects.
*/
protected List<SearchResultEntry> search(
final String filter, final String base, SearchScope scope,
String... attributes) {
List<SearchResultEntry> entries = new ArrayList<>();
try {
SearchRequest searchRequest = new SearchRequest(base, scope, filter, attributes);
ASN1OctetString resumeCookie = null;
// Perform a search to retrieve all users in the server, but only retrieving
// 500 at a time.
int numSearches = 0;
int totalEntriesReturned = 0;
while(true) {
searchRequest.setControls(new SimplePagedResultsControl(10, resumeCookie));
SearchResult results = conn().search(searchRequest);
numSearches++;
totalEntriesReturned += results.getEntryCount();
entries.addAll(results.getSearchEntries());
SimplePagedResultsControl responseControl =SimplePagedResultsControl.get(results);
if (responseControl.moreResultsToReturn())
{
// The resume cookie can be included in the simple paged results
// control included in the next search to get the next page of results.
resumeCookie = responseControl.getCookie();
System.out.println("Paged cookie: " + resumeCookie);
}
else
{
break;
}
}
} catch (LDAPSearchException e) {
System.out.println("LDAPSearchException: " + e);
} catch (LDAPException e) {
System.out.println("LDAPException: " + e);
}
return entries;
}
/**
* Creates and returns an LDAPConnection from the values of the
* connection properties.
*/
private LDAPConnection conn() {
if (this.conn != null) {
return this.conn;
}
else {
try {
System.out.println("Connecting to LDAPS hostname: " + this.hostname);
this.conn = new LDAPConnection();
this.conn.connect(this.hostname, this.port);
this.conn.bind(this.bindDN, this.bindPWD);
return this.conn;
}
catch (LDAPException e) {
System.out.println("LDAPConnection error: " + e.toString());
return null;
}
}
}
/**
* Disconnct the LDAPConnection.
*/
private void disconnect() {
if (this.conn != null) {
this.conn.close();
}
}
}
@annicarol
Copy link

I used a great piece of your code and it worked for me. Thank you very much

@hritikpgupta
Copy link

Thank you. It helped me .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment