2012-08-28 15 views
6

La pregunta lo dice todo. Cuando estoy imprimiendo un atributo que es:Cómo extraer el valor de javax.naming.directory.Attribute

cn: WF-008-DAM-PS 

El fragmento de código es:

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());    
     } 
    } 
} 

¿Cómo puedo obtener sólo el valor que es: WF-008-DAM-PS, que es sin la parte de la clave? Saludos.

Respuesta

4

Invoque el método getValue() o el método getValue(int).

+0

son estos dos métodos están presentes en javax.naming.directory.BasicAttribute o javax.naming.directory.Attribute? Hay un método get (int). –

+0

'Attribute' es una interfaz,' BasicAttribute' implementa 'Attribute'. Entonces, 'object final o = groupCn.getValue()', suponiendo que 'groupCn' tiene un solo valor. Si tiene valores múltiples, use el índice entero como el parámetro para 'groupCn.getValue (index)' –

+0

Gracias pero no hay tal método getValue() ni en http://docs.oracle.com/javase/1.4. 2/docs/api/javax/naming/directory/BasicAttribute.html o http://docs.oracle.com/javase/1.4.2/docs/api/javax/naming/directory/Attribute.html –

6

La solución es:

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

general

Digamos que tenemos:

Attributes attributes; 
Attribute a = attributes.get("something"); 
  • if(a.size() == 1)
    • entonces usted puede utilizar a.get() o a.get(0) para obtener el valor único
  • if(a.size() > 1)

    • iterar a través de todos los valores:

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

      Si utiliza a.get() aquí, volverá solo el primer valor, porque su implementación interna (en BasicAttribute) se ve así:

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

Ambos métodos (get(int) y get()) tiros un NamingException.

Ejemplo práctico
(cuando la instancia Attribute tiene múltiples valores)

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 
} 
+0

@Downvoter, por favor agregue una explicación sobre su decisión ... Creo que esta es una muy buena respuesta. –

Cuestiones relacionadas