In this post, I
am going to explain how to get information of an object from directory. For
example, I am going to retrieve information for the distinguished name
"cn=Hari,ou=people,dc=example,dc=com".
Get data from LDAP.png
import java.util.Objects; import java.util.Properties; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; public class DirectoryUtil { private final static String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory"; private final static String PROVIDER_URL = "ldap://localhost:10389"; private static DirContext context = null; public static DirContext getContext() throws NamingException { if (!Objects.isNull(context)) { return context; } Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY); properties.put(Context.PROVIDER_URL, PROVIDER_URL); DirContext context = new InitialDirContext(properties); return context; } }
import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; public class Test { public static void main(String[] args) throws NamingException { DirContext context = DirectoryUtil.getContext(); Attributes attrs = context .getAttributes("cn=Hari,ou=people,dc=example,dc=com"); System.out.println("Surname: " + attrs.get("sn").get()); System.out.println("Common name : " + attrs.get("cn").get()); System.out.println("Description : " + attrs.get("description").get()); } }
Output
Surname: Gurram
Common name : Hari
Description : Software professional, code for Company
XYZ
Reference
No comments:
Post a Comment