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

Attributes Example

The attributes example (in the Java Objects and the Directory trail) illustrates how an instance of a DirContext class Drink is stored and subsequently looked up from the directory. When the Drink object's attributes are looked up from the directory, the Context.lookup() (in the API reference documentation) method turned these attributes into an instance of Drink.
Drink d2 = (Drink) ctx.lookup("cn=favDrink");
This was made possible because: DrinkFactory.getObjectInstance() first verifies that the object is intended for its factory. It does this by checking that the object is a DirContext and that it contains an "objectclass" attribute with a value of "drink". If this verification fails, it returns null. Otherwise, it gets the value of the "drinkType" attribute (in this case "water") and uses it to create an instance of Drink. The NamingManager, having gotten a non-null answer from an object factory, will return this value to lookup(). The definition of DrinkFactory.getObjectInstance() is as follows:
public Object getObjectInstance(Object obj, Name name, Context ctx,
    Hashtable env) throws Exception {
    if (obj instanceof DirContext) {
        DirContext thisCtx = (DirContext)obj;
	try {
	    Attributes attrs = thisCtx.getAttributes("");
  	    Attribute oc = attrs.get("objectclass");
	    if (oc != null && oc.contains("drink")) {
		Attribute dt = attrs.get("drinkType");
		String drinkType = (String)dt.get();

		return new Drink(drinkType);
	    }
        } catch (NamingException e) {
	    // debug
   	    System.err.println(e);
	    e.printStackTrace();
	}
    }
    // return null to indicate other factories should be tried
    return null;
}

Object Factories: End of Lesson

What's next? Now you can:


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