DirContext: getAttributes(String name, String[] attrIds) : DirContext « javax.naming « Java by API






DirContext: getAttributes(String name, String[] attrIds)

 


import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
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 Main {
  public static String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";
  public static String MY_HOST = "ldap://localhost:1389";

  public static String MY_SEARCHBASE = "o=server.com";

  public static String MY_FILTER = "(sn=Carter)";

  public static String MY_ATTRS[] = { "cn", "mail" };

  public static void main(String args[]) throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, INITCTX);
    env.put(Context.PROVIDER_URL, MY_HOST);
    DirContext ctx = new InitialDirContext(env);
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration results = ctx.search(MY_SEARCHBASE, MY_FILTER, constraints);
    while (results != null && results.hasMore()) {
      SearchResult sr = (SearchResult) results.next();
      String dn = sr.getName() + ", " + MY_SEARCHBASE;

      System.out.println("Distinguished Name is " + dn);
      Attributes ar = ctx.getAttributes(dn, MY_ATTRS);
      if (ar == null) {
        System.out.println("Entry " + dn + " has none of the specified attributes\n");
        return;
      }
      for (int i = 0; i < MY_ATTRS.length; i++) {
        Attribute attr = ar.get(MY_ATTRS[i]);
        if (attr == null) {
          continue;
        }
        System.out.println(MY_ATTRS[i] + ":");
        for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
          System.out.println("\t" + vals.nextElement());

        }
      }
    }
  }
}

   
  








Related examples in the same category

1.DirContext.ADD_ATTRIBUTE
2.DirContext.REMOVE_ATTRIBUTE
3.DirContext.REPLACE_ATTRIBUTE
4.DirContext: getAttributes(String name)
5.DirContext: search(String name, String filter, SearchControls cons)