Saturday 29 May 2021

Java: ldapsdk: Perform search operation using connection pool

Follow below step-by-step procedure to perform search operation using connection pool.

 

Step 1: Define an instance of SearchRequest.

SearchRequest searchRequest = new SearchRequest(BASE_DN, SearchScope.SUB, FILTER);

 

Step 2: Submit search request to ldapConnectionPool.

SearchResult searchResults = ldapConnectionPool.search(searchRequest);

 

Step 3: Process the search result.

List<SearchResultEntry> searchResultEntries = searchResults.getSearchEntries();

Map<String, List<String>> result = new HashMap<>();

for (SearchResultEntry searchResultEntry : searchResultEntries) {
	Collection<com.unboundid.ldap.sdk.Attribute> attributes = searchResultEntry.getAttributes();

	for (com.unboundid.ldap.sdk.Attribute attribute : attributes) {
		String[] valuesArray = attribute.getValues();
		String attrName = attribute.getName().toLowerCase();

		List<String> valuesList = Arrays.asList(valuesArray);
		result.put(attrName, valuesList);
	}
}

 

Find the below working application.

 

LDAPUtil.java

package com.sample.app.util;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.spi.NamingManager;
import javax.net.ssl.SSLSocketFactory;

import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPConnectionOptions;
import com.unboundid.ldap.sdk.LDAPConnectionPool;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPSearchException;
import com.unboundid.ldap.sdk.RoundRobinServerSet;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SimpleBindRequest;
import com.unboundid.util.ssl.SSLUtil;
import com.unboundid.util.ssl.TrustAllTrustManager;

public class LDAPUtil {

	private static final String LDAP_SERVICE_PREFIX = "dns:///_ldap";
	private static final String[] SRV_ID = { "SRV" };
	private static final String SRV_PROPERTY = "SRV";

	/**
	 * Example:
	 * LDAPUtil.getAllServersBehindThisObject("dns:///_ldap._tcp.ca.sample.com", 4);
	 * This logic will change based on the srvRecords format received from DNS
	 * 
	 * @param ldapDNSURL
	 * @param limitServers
	 * @return
	 * @throws NamingException
	 */
	public static List<String> getAllServersBehindThisObject(String ldapDNSURL, int limitServers)
			throws NamingException {

		if (ldapDNSURL == null || ldapDNSURL.isEmpty()) {
			throw new IllegalArgumentException("ldapDNSURL must not be empty");
		}

		if (!ldapDNSURL.startsWith(LDAP_SERVICE_PREFIX)) {
			throw new IllegalArgumentException("ldapDNSURL must start with " + LDAP_SERVICE_PREFIX);
		}

		List<String> serversBehindThisDNS = new ArrayList<>();

		DirContext context = (DirContext) NamingManager.getURLContext("dns", new Hashtable<String, Object>());
		Attributes attributes = context.getAttributes(ldapDNSURL, SRV_ID);
		Attribute srvRecords = attributes.get(SRV_PROPERTY);

		for (int i = 0; i < srvRecords.size(); i++) {
			if (i > limitServers - 1) {
				break;
			}

			String srvRecord = srvRecords.get(i).toString();
			String serverName = extractServerNameFromSRVRecord(srvRecord);

			if (serverName == null) {
				continue;
			}

			serversBehindThisDNS.add(serverName);

		}

		return serversBehindThisDNS;
	}

	public static LDAPConnection getLDAPConnection(final String host, final int port, final String userName,
			final String password) throws LDAPException, GeneralSecurityException {

		LDAPConnectionOptions ldapConnectionOptions = getDefaultLDAPConnectionOptions();
		SSLSocketFactory sslSocketFactory = getDefaultSSLSocketFactory();

		LDAPConnection ldapConnection = new LDAPConnection(sslSocketFactory, ldapConnectionOptions, host, port,
				userName, password);

		if (ldapConnection == null) {
			throw new IllegalArgumentException("Invalid username or password");
		}

		return ldapConnection;

	}

	public static LDAPConnectionPool getLdapConnectionPool(final String[] serverNames, final int[] ports,
			final String userName, final String password) throws GeneralSecurityException, LDAPException {
		LDAPConnectionOptions ldapConnectionOptions = getDefaultLDAPConnectionOptions();
		SSLSocketFactory sslSocketFactory = getDefaultSSLSocketFactory();

		RoundRobinServerSet roundRobinSet = new RoundRobinServerSet(serverNames, ports, sslSocketFactory,
				ldapConnectionOptions);
		SimpleBindRequest bindRequest = new SimpleBindRequest(userName, password);

		return new LDAPConnectionPool(roundRobinSet, bindRequest, 10, 50, serverNames.length * 2, null, true);
	}

	public static Map<String, List<String>> executeQuery(LDAPConnectionPool ldapConnectionPool,
			SearchRequest searchRequest) throws LDAPSearchException {
		SearchResult searchResults = ldapConnectionPool.search(searchRequest);
		List<SearchResultEntry> searchResultEntries = searchResults.getSearchEntries();

		Map<String, List<String>> result = new HashMap<>();

		for (SearchResultEntry searchResultEntry : searchResultEntries) {
			Collection<com.unboundid.ldap.sdk.Attribute> attributes = searchResultEntry.getAttributes();

			for (com.unboundid.ldap.sdk.Attribute attribute : attributes) {
				String[] valuesArray = attribute.getValues();
				String attrName = attribute.getName().toLowerCase();

				List<String> valuesList = Arrays.asList(valuesArray);
				result.put(attrName, valuesList);
			}
		}
		return result;
	}

	public static SSLSocketFactory getDefaultSSLSocketFactory() throws GeneralSecurityException {
		TrustAllTrustManager allTrustManager = new TrustAllTrustManager();
		SSLUtil sslUtil = new SSLUtil(allTrustManager);

		return sslUtil.createSSLSocketFactory();

	}

	public static LDAPConnectionOptions getDefaultLDAPConnectionOptions() {
		LDAPConnectionOptions ldapConnectionOptions = new LDAPConnectionOptions();
		ldapConnectionOptions.setResponseTimeoutMillis(10000);
		ldapConnectionOptions.setUseSynchronousMode(true);
		ldapConnectionOptions.setAllowConcurrentSocketFactoryUse(true);
		ldapConnectionOptions.setConnectTimeoutMillis(10000);
		ldapConnectionOptions.setAbandonOnTimeout(true);
		ldapConnectionOptions.setBindWithDNRequiresPassword(false);
		return ldapConnectionOptions;
	}

	private static String extractServerNameFromSRVRecord(String srvRecord) {
		String[] splits = srvRecord.split(" ");

		if (splits.length != 4) {
			return null;
		}

		String server = splits[3];

		int lastCharIndex = server.lastIndexOf(".");
		if (lastCharIndex == server.length() - 1) {
			server = server.substring(0, server.length() - 1);
		}
		return server;

	}

}

 

HelloWorld.java

package com.sample.app;

import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.NamingException;

import com.sample.app.util.LDAPUtil;
import com.unboundid.ldap.sdk.Attribute;
import com.unboundid.ldap.sdk.LDAPConnectionPool;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;

public class HelloWorld {

	private static final String USER_NAME = "";
	private static final String PASSWORD = "";
	private static final String DOMAIN_NAME = "hr.sample.com";
	private static final String DOMAIN_NAME_WITH_LDAP_TCP = "_ldap._tcp." + DOMAIN_NAME;
	private static final String DOMAIN_NAME_WITH_LDAP_TCP_DNS = "dns:///" + DOMAIN_NAME_WITH_LDAP_TCP;

	// Attributes related to search
	private static final String BASE_DN = "DC=hr,DC=sample,DC=com";
	private static final String FILTER = "(userPrincipalName=krishna@hr.sample.com)";
	private static final String[] ATTRIBUTES_TO_SEARCH = { "displayname", "mail", "memberof" };

	public static void main(String args[]) throws GeneralSecurityException, LDAPException, NamingException {

		List<String> serversBehindThisDomain = LDAPUtil.getAllServersBehindThisObject(DOMAIN_NAME_WITH_LDAP_TCP_DNS, 4);

		int noOfServers = serversBehindThisDomain.size();
		String[] arr = new String[noOfServers];
		String[] serversToConnect = serversBehindThisDomain.toArray(arr);

		int[] ports = new int[noOfServers];
		for (int i = 0; i < noOfServers; i++) {
			ports[i] = 636;
		}

		LDAPConnectionPool ldapConnectionPool = LDAPUtil.getLdapConnectionPool(serversToConnect, ports, USER_NAME,
				PASSWORD);

		SearchRequest searchRequest = new SearchRequest(BASE_DN, SearchScope.SUB, FILTER);
		searchRequest.setAttributes(ATTRIBUTES_TO_SEARCH);

		Map<String, List<String>> result = LDAPUtil.executeQuery(ldapConnectionPool, searchRequest);

		System.out.println(result);

	}

}

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment