Java DirContext search

Description

Java DirContext search

import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchResult;

public class Main {
   public static void main(String[] args) {
      try {//from  w w w. j a v  a2 s  .c o  m
         DirContext ctx = new InitialDirContext();
         Attributes attrs = new BasicAttributes(true);
         attrs.put(new BasicAttribute("o", "JU"));
         attrs.put(new BasicAttribute("objectclass", "organization"));
         NamingEnumeration result = ctx.search(args[0], attrs);
         while (result.hasMore()) {
            SearchResult sr = (SearchResult) result.next();
            System.out.println("name: " + sr.getName());
            for (NamingEnumeration ne = sr.getAttributes().getAll(); ne.hasMore();) {
               Attribute attr = (Attribute) ne.next();
               System.out.println("attribute: " + attr.getID());
               for (NamingEnumeration e = attr.getAll(); e.hasMore();)
                  System.out.println("value: " + e.next());
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related