Search code examples
javaldapjndi

Parsing LDAP attributes from String in Java


Is there a way to parse attributes from a String? For example, if I have the following:

CN=Doe, John: Markets (LDN),OU=Users,DC=FOOCORP,DC=COM

and would like to get that into an Attributes or set of Attribute-s, is there a utility class one could use that does all the proper escaping, or should I just knock up some implementation of my own?

I have the following code:

    String cnBase = "CN=Doe\\, John: Markets (LDN),OU=Users,DC=FOOCORP,DC=COM";

    StringTokenizer st = new StringTokenizer(cnBase, "=");

    Attributes attributes = new BasicAttributes();

    String attributeId = null;
    String attributeValue = null;
    String previousToken = null;

    while (st.hasMoreTokens())
    {
        String token = st.nextToken();

        if (previousToken == null && attributeId == null)
        {
            // Get the attribute's id
            attributeId = token;
            continue;
        }

        if (attributeId != null)
        {
            if (token.contains(","))
            {
                attributeValue = token.substring(0, token.lastIndexOf(","));
            }
            else
            {
                attributeValue = token;
            }
        }

        if (attributeId != null && attributeValue != null)
        {
            // Add a new Attribute to the attributes object
            Attribute attribute = new BasicAttribute(attributeId, attributeValue);
            attributes.put(attribute);

            System.out.println(attribute.toString());

            attributeId = token.substring(token.lastIndexOf(",") + 1, token.length());
            attributeValue = null;
        }

        previousToken = token;
    }

Which I think can be re-written in a smarter way.


Solution

  • JNDI has a class called LdapName (misnamed), which represents a distinguished name. It's based on an obsolete RFC but it might be satisfactory.

    see also