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.Although this example uses both a state factory and an object factory, the focus is on the state factory. See the Object Factories lesson for a detailed discussion of 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");Sun's LDAP service provider is used for this example. When Context.bind() is invoked on this provider, it uses DirectoryManager.getStateToBind() to retrieve the state of the object to be bound. This example specifies in the jndi.properties file the factories that it uses.
(See the Beyond the Basics trail for details about environment properties.)java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory java.naming.factory.state=PersonStateFactory java.naming.factory.object=PersonObjectFactoryThe PersonStateFactory accepts an instance of Person and returns a DirStateFactory.Result 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"); oc.add("top"); outAttrs.put(oc); } 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 (per.phone != null) { outAttrs.put("telephoneNumber", per.phone); } 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:
- Continue on in this trail to learn how to read Java objects from the directory.
- Go to the Representation in the Directory lesson to read about the physical representation of Java objects in the directory.
State Factories