Wednesday 25 May 2016

JNDI: get distinguished names


NameClassPair provides getNameInNamespace() method to get the distinguished name from directory.

As you see above figure, ou=people has four persons reside in it.
Following application retrieve all the distinguished names in the context “ou=people,dc=example,dc=com”.

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 final Properties properties = new Properties();

 static {
  initProperties();
 }

 private static void initProperties() {
  properties.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
  properties.put(Context.PROVIDER_URL, PROVIDER_URL);
  properties.put("com.sun.jndi.ldap.connect.pool", "true");
 }

 public static DirContext getContext() throws NamingException {
  DirContext context = new InitialDirContext(properties);
  return context;
 }
}

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class Test {
 public static void printResults(NamingEnumeration<SearchResult> results)
   throws NamingException {
  while (results.hasMoreElements()) {
   SearchResult res = results.next();
   String distinguishedName = res.getNameInNamespace();
   System.out.println(distinguishedName);
  }
 }

 /* Get all people in the context ou=people,dc=example,dc=com */
 public static void getAllDns() throws NamingException {
  DirContext context = DirectoryUtil.getContext();
  SearchControls searcCon = new SearchControls();
  searcCon.setSearchScope(SearchControls.SUBTREE_SCOPE);
  NamingEnumeration<SearchResult> results = context.search(
    "dc=example,dc=com", "sn=*", searcCon);
  printResults(results);
  context.close();
 }

 public static void main(String[] args) throws NamingException {
  getAllDns();
 }
}


Output
cn=Hari,ou=people,dc=example,dc=com
cn=Krishna,ou=people,dc=example,dc=com
cn=Senthil,ou=people,dc=example,dc=com
cn=Sailu,ou=people,dc=example,dc=com



Previous                                                 Next                                                 Home

No comments:

Post a Comment