In this post under Java LDAP, I will show how to lookup for an entry in LDAP directory tree using ldap distinguished name.
Below is the complete main class for your reference
Main class
1 package package2;
2
3 import java.util.Hashtable;
4
5 import javax.naming.Context;
6 import javax.naming.NamingException;
7 import javax.naming.directory.DirContext;
8 import javax.naming.directory.InitialDirContext;
9 import javax.naming.ldap.LdapContext;
10
11 public class LDAPDemo2 {
12 public static void main(String[] args) {
13 Hashtable<String, Object> env = new Hashtable<String, Object>();
14 env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
15 env.put(Context.PROVIDER_URL, "ldap://localhost:1389");
16 env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=example,dc=org");
17 env.put(Context.SECURITY_CREDENTIALS, "adminpassword");
18 DirContext ctx = null;
19 try {
20 ctx = new InitialDirContext(env);
21 LdapContext dirContext = (LdapContext)ctx.lookup("cn=user3,ou=dev,dc=example,dc=org");
22 System.out.println("Lookup successful");
23 } catch(NamingException excep) {
24 excep.printStackTrace();
25 } finally {
26 if(ctx != null) {
27 try {
28 ctx.close();
29 } catch(NamingException excep) {
30 excep.printStackTrace();
31 }
32 }
33 }
34 }
35 }
We use the “lookup” method to retrieve an ldap entry using the distinguished name. Refer to line 21.
This method works only if we know the full DN and it returns a context object using which we can perform other operations.
The difference between “ctx” object and “dirContext” is that “ctx” object points to root of directory tree, whereas “dirContext” points to subtree/subcontext that has the “cn=user3,ou=dev,dc=example,dc=org” dn
In this way we can lookup for an ldap entry using the distinguished name.