Difference between revisions of "Query AD"
From MyWiki
(Created page with "<source lang="java"> import java.util.Hashtable; import javax.naming.ldap.*; import javax.naming.directory.*; import javax.naming.*; public class queryactivedire...") |
|||
Line 1: | Line 1: | ||
+ | The following was taken from http://www.programming-free.com/2012/09/query-active-directory-from-java-using.html<br> | ||
<source lang="java"> | <source lang="java"> | ||
Latest revision as of 16:59, 18 September 2014
The following was taken from http://www.programming-free.com/2012/09/query-active-directory-from-java-using.html
import java.util.Hashtable; import javax.naming.ldap.*; import javax.naming.directory.*; import javax.naming.*; public class queryactivedirectory { public static void main (String[] args) { Hashtable env = new Hashtable(); String adminName = "CN=Administrator,CN=Users,DC=ANTIPODES,DC=COM"; String adminPassword = "XXXXXXX"; String ldapURL = "ldap://mydc.antipodes.com:636"; env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); //set security credentials env.put(Context.SECURITY_AUTHENTICATION,"simple"); env.put(Context.SECURITY_PRINCIPAL,adminName); env.put(Context.SECURITY_CREDENTIALS,adminPassword); //specify use of ssl env.put(Context.SECURITY_PROTOCOL,"ssl"); //connect to my domain controller env.put(Context.PROVIDER_URL,ldapURL); try { // Create the initial directory context DirContext ctx = new InitialLdapContext(env,null); //Create the search controls SearchControls searchCtls = new SearchControls(); //Specify the attributes to return String returnedAtts[]={"sn","mail","cn","telephonenumber"}; searchCtls.setReturningAttributes(returnedAtts); //Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); //specify the LDAP search filter String searchFilter = "(&(objectClass=user)(mail=*))"; //Specify the Base for the search String searchBase = "DC=ANTIPODES,DC=COM"; //initialize counter to total the results int totalResults = 0; // Search for objects using the filter NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); //Loop through the search results while (answer.hasMoreElements()) { SearchResult sr = (SearchResult)answer.next(); totalResults++; System.out.println(">>>" + sr.getName()); // Print out some of the attributes, catch the exception if the attributes have no values Attributes attrs = sr.getAttributes(); if (attrs != null) { try { System.out.println(" surname: " + attrs.get("sn").get()); System.out.println(" firstname: " + attrs.get("givenName").get()); System.out.println(" mail: " + attrs.get("mail").get()); } catch (NullPointerException e) { System.out.println("Errors listing attributes: " + e); } } } System.out.println("Total results: " + totalResults); ctx.close(); } catch (NamingException e) { System.err.println("Problem searching directory: " + e); } } }