LDAP Connection Test

LDAP Connection Test demo program show how to connect LDAP server. Please use this program and

replace your LDAP domain name and port number and it also need valid user id and password to access the record from LDAP server.

LDAP Connection Test program how to connect LDAP system using java:

package com.ldap;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class LDAPConnectionTest {
	public static String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";

	public static String MY_HOST = "ldap://doaminName:389";

	public static String MY_SEARCHBASE = "DC=doaminName,DC=companyName,DC=com";

	public static String MY_FILTER = "(sAMAccountName=${u})";

	public static String PTE_AM_LDAP_VALUE = "LDAP://doaminName/CN=!Res-Test01,OU=Test Accounts,OU=Associates,DC=doaminName,DC=companyName,DC=com";

	public static String MGR_DN = "CN=Service Account\\, userid,OU=ServiceAccounts,OU=ServerAdministration,DC=doaminName,DC=companyName,DC=com";

	public static String MGR_PW = "Password";

	public static void main(String[] args) throws NamingException {
		// Connect to LDAP server.
		Hashtable<String, String> env = new Hashtable<String, String>(11);
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://" + "companyName.com" + ":"
				+ "389");

		InitialDirContext ctx = null;
		try {
			ctx = new InitialDirContext(env);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String[] searchAttrs = { "ldapSearchAttribs" };
		SearchControls constraints1 = new SearchControls();
		constraints1.setSearchScope(SearchControls.SUBTREE_SCOPE);
		constraints1.setCountLimit(0);
		constraints1.setTimeLimit(0);

		constraints1.setReturningAttributes(searchAttrs);

		StringBuffer s = new StringBuffer("ldapSearchTmpl");
		int idx = s.toString().indexOf("?");
		s.replace(idx, idx + 1, "user");

		// Search for user's email given matching user ID.
		String email = null;
		try {
			NamingEnumeration<SearchResult> answer = ctx.search("ldapRootDN",
					s.toString(), constraints1);

			while (answer.hasMore()) {
				SearchResult ldapResult = answer.next();
				Attributes attrs = ldapResult.getAttributes();
				Attribute emailAttr = attrs.get("ldapSearchAttribs");
				email = (String) emailAttr.get();
			}
			ctx.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

 

 

2 thoughts on “LDAP Connection Test”
  1. I developed a JEE Application and I want to know how can I configure two LDAP such a way that, if the first fails utilizing the secondary backup LDAP server.
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *