Wednesday 25 May 2016

JNDI: get all attributes

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 java.util.Objects;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;

public class Test {
 static void printAttrs(Attributes attrs) throws NamingException {
  if (Objects.isNull(attrs)) {
   return;
  }

  NamingEnumeration<?> attributes = attrs.getAll();

  while (attributes.hasMoreElements()) {
   Attribute attr = (Attribute) attributes.next();
   String id = attr.getID();

   System.out.println("attribute : " + id);
   NamingEnumeration<?> values = attr.getAll();
   while (values.hasMoreElements()) {
    System.out.println("Value " + values.next());
   }

  }

 }

 public static void main(String[] args) throws NamingException {
  DirContext context = DirectoryUtil.getContext();
  Attributes attributes = context
    .getAttributes("cn=Krishna,ou=people,dc=example,dc=com");
  printAttrs(attributes);
  context.close();
 }
}


Sample Output
attribute : objectclass
Value top
Value person
attribute : sn
Value Gurram
attribute : cn
Value Krishna



Previous                                                 Next                                                 Home

No comments:

Post a Comment