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, Context.lookup() (in the API reference documentation) turns those attributes into an instance of Drink.
Drink d2 = (Drink) ctx.lookup("cn=favDrink");
This happens because of the following.
  1. The service provider being used (Sun's LDAP provider) invoked DirectoryManager.getObjectInstance() (in the API reference documentation) and supplied to the method the data (a DirContext) that the provider read from the directory for the entry "cn=favDrink".
  2. The client program identified the object factory (DrinkFactory) to use when it created the initial context.
    // Add property so that object factory can be found
    env.put(Context.OBJECT_FACTORIES, "DrinkFactory");
    
  3. DrinkFactory.getObjectInstance() returned an instance of Drink.
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 a "drinkType" attribute. If this verification fails, then the method 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 definition of DrinkFactory.getObjectInstance() is as follows.

public Object getObjectInstance(Object obj, Name name, Context ctx,
    Hashtable env, Attributes inAttrs) throws Exception {
    if (obj instanceof DirContext) {
	try {
	    Attribute dt;
	    if (inAttrs != null && (dt=inAttrs.get("drinktype")) != null) {
	        String drinkType = (String)dt.get();

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


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