Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract data from NamingEnumeration

Tags:

java

list

ldap

My application searches an LDAP server for people.

return ldapTemplate.search("", "(objectclass=person)", new AttributesMapper() {
      public Object mapFromAttributes(Attributes attrs) 
                                                     throws NamingException {

        return attrs.get("cn").getAll();
      }
    });

It returns list of NamingEnumeration object, which contains vectors in it. Each vector may contain one or more values. I can print person names by this code

for(NamingEnumeration ne : list){
  while (ne.hasMore()) {
      System.out.println("name is : " + ne.next().toString());
    }
  }

As my ldap search can contain mutiple values so that comes in vector inside NamingEnumeration object. How can I get multiple values out of it.

like image 297
Muhammad Imran Tariq Avatar asked Dec 13 '11 10:12

Muhammad Imran Tariq


2 Answers

As you are using a java.util.List of javax.naming.NamingEnumeration<java.util.Vector> such as this,

List<NamingEnumeration<Vector>> list

You should be able to iterate over the Vector in each NamingEnumeration:

for (NamingEnumeration<Vector> ne : list) {
    while (ne.hasMore()) {
        Vector vector = ne.next();
        for (Object object : vector) {
            System.out.println(object);
        }
    }
}

Note that Vector is considered by many to be obsolescent, although not deprecated. Also, the enclosed collection could use a type parameter. If you have a choice, consider one of these alternatives:

List<NamingEnumeration<Vector<T>>>
List<NamingEnumeration<List<T>>>
like image 61
trashgod Avatar answered Sep 23 '22 21:09

trashgod


While iterating a list using the forsyntax introduced with Java5

You shouldn't call hasMore()

for(NamingEnumeration ne : list){   
    System.out.println("name is : " + ne.toString());     
}

In case your list does not support the Iterator interface you need to use the old form:

for ( Enumeration e = v.elements() ; e.hasMoreElements() ; ) {
    String a = (String) e.nextElement();
    System.out.println( a );
}
like image 41
stacker Avatar answered Sep 24 '22 21:09

stacker