Name Parser

Whether a context implementation supports a flat or hierarchical namespace depends on the underlying naming/directory service. For example, a context implementation for an LDAP directory service must support a hierarchical namespace, whereas a context implementation for the RMI registry must support a flat namespace because the underlying services dictate that.

A context implementation for a flat or hierarchical namespace needs a name parser, is a class that implements the NameParser interface. The JNDI provides a utility class, CompoundName, for developers to use when implementing NameParser. However, you are not required to use CompoundName. You can implement NameParser in any way as long as its parse() method returns an object that implements the Name interface. You should avoid using the CompositeName class for this purpose because it would be interpreted as a composite name.

The hierarchical namespace example implements a syntax of right-to-left, dot-character (".") separated names. Here is its implementation of the NameParser interface.

class HierParser implements NameParser {

    private static final Properties syntax = new Properties();
    static {
        syntax.put("jndi.syntax.direction", "right_to_left");
	syntax.put("jndi.syntax.separator", ".");
        syntax.put("jndi.syntax.ignorecase", "false");
	syntax.put("jndi.syntax.escape", "\\");
	syntax.put("jndi.syntax.beginquote", "'");
    }

    public Name parse(String name) throws NamingException {
        return new CompoundName(name, syntax);
    }
}
The CompoundName class specifies properties that are used to define a naming syntax. For example, you can specify a syntax's atomic component separator, its escape and quotation characters, and whether the components are parsed right to left or left to right or are flat. Namespace syntax is determined by the underlying naming/directory service. You can use CompoundName only if the syntax of the underlying naming/directory service fits into CompoundName's syntax model.

The API user uses Context.getNameParser() to get a Context instance's name parser. The example implementation first performs a lookup() to verify that the input name is valid. It then returns the constant field myParser.

public NameParser getNameParser(Name name) throws NamingException {
    // Do lookup to verify that the name exists
    Object obj = lookup(name);
    if (obj instanceof Context) {
        ((Context)obj).close();
    }
    return myParser;
}
Each context implementation has only one instance of HierParser:
protected final static NameParser myParser = new HierParser();
This is done to satisfy the JNDI specification, which requires that a context implementation return a NameParser whose equals() method returns true for all Context instances from the same namespace. This requirement is useful for supporting federation. Even though this example does not support federation, the requirement is easy to fulfill.