We have already seen the fundamentals of JNDI along with examples for Naming as well as Directory Services using JNDI. So far, all the JNDI examples using LDAP were fetching/updating a particular user from the DIT. In this section we would list all the users from LDAP using JNDI in “ou=users,ou=system” in a generic way.
List All Users from LDAP using JNDI
The basic setup is same as that of the previous examples.We are using Apache Directory Studio as the LDAP provider .In this case we are searching the users details using the search() method of DirContext object.
DirectorySample.java
import java.util.Enumeration; import java.util.Properties; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.Attribute; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; public class DirectorySample { public DirectorySample() { } public void doLookup() { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); properties.put(Context.PROVIDER_URL, "ldap://localhost:10389"); properties.put(Context.SECURITY_AUTHENTICATION,"simple"); properties.put(Context.SECURITY_PRINCIPAL,"uid=admin,ou=system"); properties.put(Context.SECURITY_CREDENTIALS,"secret"); try { DirContext context = new InitialDirContext(properties); SearchControls searchCtrls = new SearchControls(); searchCtrls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "(objectClass=*)"; NamingEnumeration values = context.search(" ou=users,ou=system",filter,searchCtrls); while (values.hasMoreElements()) { SearchResult result = (SearchResult) values.next(); Attributes attribs = result.getAttributes(); if (null != attribs) { for (NamingEnumeration ae = attribs.getAll(); ae.hasMoreElements();) { Attribute atr = (Attribute) ae.next(); String attributeID = atr.getID(); for (Enumeration vals = atr.getAll(); vals.hasMoreElements(); System.out.println(attributeID +": "+ vals.nextElement())); } } } context.close(); } catch (NamingException e) { e.printStackTrace(); } } public static void main(String[] args) { DirectorySample sample = new DirectorySample(); sample.doLookup(); } }
The code shown here lists all the attributes of all users.This can be controlled by adding returning attributes to search controls .
Example:
String[] attributes = { “cn”, “employeeNumber”, “sn” };
searchCtrls.setReturningAttributes(attributes);
Not able to get all user. Its able to pull only 1000 records.
how to get all with not limit? Please help me!