How to print Attributes enumeration in Java (javax naming directory Attributes)

This is only a little piece of code to print all the IDs and values of a javax.naming.directory.Attributes.

java

If you want to know more about this interface, please see official documentation (http://docs.oracle.com/javase/7/docs/api/javax/naming/directory/Attributes.html), but here, you have a little explanation about it:

This interface represents a collection of attributes.
In a directory, named objects can have associated with them attributes. The Attributes interface represents a collection of attributes. For example, you can request from the directory the attributes associated with an object. Those attributes are returned in an object that implements the Attributes interface.

Attributes in an object that implements the Attributes interface are unordered. The object can have zero or more attributes. Attributes is either case-sensitive or case-insensitive (case-ignore). This property is determined at the time the Attributes object is created. (see BasicAttributes constructor for example). In a case-insensitive Attributes, the case of its attribute identifiers is ignored when searching for an attribute, or adding attributes. In a case-sensitive Attributes, the case is significant.

Note that updates to Attributes (such as adding or removing an attribute) do not affect the corresponding representation in the directory. Updates to the directory can only be effected using operations in the DirContext interface.

public void printAttrs(Attributes attrs)
{
    System.out.println(">> printAttrs()");
    if (attrs == null)
    {
        System.out.println("No attributes");
    }
    else
    {
        // Print every single attribute
        try
        {
            for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();)
            {
                Attribute attr = (Attribute) ae.next();
                System.out.println("Attribute ID: " + attr.getID());

                // Print values of current attribute
                NamingEnumeration e = attr.getAll();
                while(e.hasMore())
                {
                    String value = e.next().toString();
                    System.out.println("Value: " + value);
                }
            }
        } catch (NamingException e) { e.printStackTrace(); }
    }
    System.out.println("<< printAttrs()");
}

That’s it!

Be happy with your code!

Leave a Reply

Your email address will not be published. Required fields are marked *