How to extract value from javax.naming.directory.Attribute

The solution is:

Attribute groupCn = attributes.get("cn");
String value = groupCn.get();

Invoke the getValue() method or the getValue(int) method.


General

Let's say that we have:

Attributes attributes;
Attribute a = attributes.get("something");
  • if(a.size() == 1)
    • then you can use a.get() or a.get(0) to get the unique value
  • if(a.size() > 1)

    • iterate through all the values:

      for ( int i = 0 ; i < a.size() ; i++ ) {
          Object currentVal = a.get(i);
          // do something with currentVal
      }
      

      If you use a.get() here, it will return only the first value, because its internal implementation (in BasicAttribute) looks like this:

      public Object get() throws NamingException {
          if (values.size() == 0) {
              throw new NoSuchElementException("Attribute " + getID() + " has no value");
          } else {
              return values.elementAt(0);
          }
      }
      

Both methods (get(int) and get()) throws a NamingException.

Practical example
(when the Attribute instance has multiple values)

LdapContext ctx = new InitialLdapContext(env, null);

Attributes attributes = ctx.getAttributes("", new String[] { "supportedSASLMechanisms" });
System.out.println(attributes); // {supportedsaslmechanisms=supportedSASLMechanisms: GSSAPI, EXTERNAL, DIGEST-MD5}

Attribute a = atts.get("supportedsaslmechanisms");
System.out.println(a); // supportedSASLMechanisms: GSSAPI, EXTERNAL, DIGEST-MD5

System.out.println(a.get()); // GSSAPI

for (int i = 0; i < a.size(); i++) {
    System.out.print(a.get(i) + " "); // GSSAPI EXTERNAL DIGEST-MD5
}

Tags:

Java

Ldap

Jndi