Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

ldap

jndi

The question says everything. When I am printing an Attribute it is:

cn: WF-008-DAM-PS

The code snippet is:

private void searchGroup() throws NamingException {
    NamingEnumeration<SearchResult> searchResults = getLdapDirContext().search(groupDN, "(objectclass=groupOfUniqueNames)", getSearchControls());
    String searchGroupCn = getCNForBrand(m_binder.getLocal("brandId"), m_binder.getLocal("brandName"));
    Log.info(searchGroupCn);
    while (searchResults.hasMore()) {
        SearchResult searchResult = searchResults.next();
        Attributes attributes = searchResult.getAttributes();
        Attribute groupCn = attributes.get("cn");
        if(groupCn != null) {
            Log.info(groupCn.toString());               
        }
    }
}

How can I only get the value that is: WF-008-DAM-PS, that is without the key portion? Regards.

like image 646
Tapas Bose Avatar asked Aug 28 '12 15:08

Tapas Bose


3 Answers

The solution is:

Attribute groupCn = attributes.get("cn");
String value = groupCn.get();
like image 172
Tapas Bose Avatar answered Sep 23 '22 11:09

Tapas Bose


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

like image 22
Terry Gardner Avatar answered Sep 23 '22 11:09

Terry Gardner


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
}
like image 39
ROMANIA_engineer Avatar answered Sep 24 '22 11:09

ROMANIA_engineer