Object Factories

 


Custom Object Example

The custom object example illustrates how an instance of a user-defined class Person is stored and subsequently looked up from the directory. When the Person object's attributes are looked up from the directory, the Context.lookup() method turns these attributes into an instance of Person.
Person john2 = (Person) ctx.lookup("cn=John Smith");
This was made possible because of the following.
  1. The service provider being used (Sun's LDAP provider) invoked DirectoryManager.getObjectInstance() and supplied to the method the object (an LDAP context object) and attributes that the provider read from the directory for the entry "cn=John Smith".
  2. The client program identified the object factory (PersonObjectFactory) to use by using an application resource file that named PersonObjectFactory as one of the object factories to try.
  3. PersonObjectFactory.getObjectInstance() returned an instance of Person.
PersonObjectFactory.getObjectInstance() first verifies that the object is intended for its factory. It does this by checking that the "objectclass" attribute has a value of "person". If this verification fails, then the method returns null. Otherwise, it constructs an instance of Person by supplying the constructor values obtained from the entry's other attributes, such as the "surname" and "commonname" attributes.

The definition of PersonObjectFactory.getObjectInstance() is as follows.

public Object getObjectInstance(
    Object obj, Name name, Context ctx, Hashtable env, Attributes attrs)
    throws Exception {

    // Only interested in Attributes with "person" objectclass
    // System.out.println("object factory: " + attrs);
    Attribute oc = (attrs != null ? attrs.get("objectclass") : null);
    if (oc != null && oc.contains("person")) {
        Attribute attr;
	String passwd = null;

	// Extract the password
	attr = attrs.get("userPassword");
	if (attr != null) {
	    passwd = new String((byte[])attr.get());
	}
        Person per = new Person(
          (String)attrs.get("sn").get(),
          (String)attrs.get("cn").get(),
	  passwd,
          (attr=attrs.get("telephoneNumber")) != null ? (String)attr.get() : null,
          (attr=attrs.get("seealso")) != null ? (String)attr.get() : null,
          (attr=attrs.get("description")) != null ? (String)attr.get() : null);
        return per;
    }
    return null;
}

Object Factories: End of Lesson

What's next? Now you can:

  • Continue on in this trail lesson to read about the physical representation of Java objects in the directory.
  • Go to the Beyond the Basics trail to learn about advanced JNDI topics.

Object Factories