Previous | Next | Trail Map | Java Objects and the Directory | State Factories

Custom Object Example

This example illustrates how an arbitrary type (e.g., Person) can be stored and read back from the directory by using custom state and object factories.
// Create the object to be bound
Person john = new Person("Smith", "John Smith");

// Perform the bind
ctx.rebind("cn=John Smith", john);

// Read back the object
Person john2 = (Person) ctx.lookup("cn=John Smith");
Although this example uses both a state factory and an object factory, the focus is on the state factory. See the Object Factories (in the Java Objects and the Directory trail) lesson for a detailed discussion of object factories.

Sun's LDAP service provider is used for this example. When Context.bind()(in the API reference documentation) is invoked on this provider, it uses DirectoryManager.getStateToBind() (in the API reference documentation) to retrieve the state of the object to be bound. This example specifies in the file the factories that it uses.

(See the Beyond the Basics (in the Beyond the Basics trail) trail for details about environment properties.)

The PersonStateFactory accepts an instance of Person and returns a DirStateFactory.Result(in the API reference documentation) instance that contains the attributes representing the Person object.

public DirStateFactory.Result getStateToBind(
    Object obj, Name name, Context ctx, Hashtable env, Attributes inAttrs)
    throws NamingException {

    // Only interested in Person objects
    if (obj instanceof Person) {

        Attributes outAttrs;
        if (inAttrs == null) {
            outAttrs = new BasicAttributes(true);
        } else {
            outAttrs = (Attributes)inAttrs.clone();

        // Set up the object class
        if (outAttrs.get("objectclass") == null) {
            BasicAttribute oc = new BasicAttribute("objectclass", "person");

        Person per = (Person)obj;
        // Mandatory attributes
        if (per.surname != null) {
            outAttrs.put("sn", per.surname);
        } else {
            throw new SchemaViolationException("Person must have surname");
        if (per.commonName != null) {
            outAttrs.put("cn", per.commonName);
        } else {
            throw new SchemaViolationException("Person must have common name");

        // Optional attributes
        if (per.passwd != null) {
            outAttrs.put("userPassword", per.passwd);
        if ( != null) {
        if (per.seeAlso != null) {
            outAttrs.put("seeAlso", per.seeAlso);
        if (per.desc != null) {
            outAttrs.put("description", per.desc);

        //System.out.println("state factory: " + outAttrs);
        return new DirStateFactory.Result(null, outAttrs);
    return null;

State Factories: End of Lesson

What's next? Now you can:

Previous | Next | Trail Map | Java Objects and the Directory | State Factories