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.
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)
a.get()
or a.get(0)
to get the unique valueif(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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With