Connect Ldap
Below is demo program to show to you 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.
Connect LDAP server using java demo code:
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.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; public class ConnectLdap { public static void main(String[] args) { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://domainName:389"); env.put(Context.SECURITY_PRINCIPAL, "domainName\\userid"); env.put(Context.SECURITY_CREDENTIALS, "password"); DirContext ctx = null; NamingEnumeration results = null; try { ctx = new InitialDirContext(env); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); // results = ctx.search("cn=users,DC=domain,DC=companyname,DC=com", // "(objectclass=top)", controls); results = ctx.search( "ou=Associates,DC=domain,DC=companyname,DC=com", "(objectclass=top)", controls); int count = 0; while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); // System.out.println(attributes+"\n"); Attribute samaccountname = attributes.get("samaccountname"); if (samaccountname != null) { String cn = (String) samaccountname.get(); System.out.println("Count = " + count++); System.out.println("samaccountname = " + cn); } Attribute mail = attributes.get("mail"); if (mail != null) { String cn = (String) mail.get(); System.out.println("mail id = " + cn + "\n"); } else { System.out.println("mail id = \n"); } /* * Attribute mailnickname = attributes.get("mailnickname"); if * (mailnickname!=null) { String cn = (String) * mailnickname.get(); System.out.println("mailnickname = " + * cn); } */ } } catch (NamingException e) { throw new RuntimeException(e); } finally { if (results != null) { try { results.close(); } catch (Exception e) { } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { } } } } }