blogger templates blogger widgets
This is part of a list of blog posts.
To browse the contents go to

LDAP Operation: Store a reference to object

We proceed the same way we did for naming service.

package sample;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.StringRefAddr;

public class Student implements Referenceable {
String msg;
public void setMsg(String msg){
this.msg = msg;
}
public Reference getReference() throws NamingException {
return new Reference(
Student.class.getName(), 
new StringRefAddr("msg", msg), 
StudentFactory.class.getName(),
null);          // factory location
}

public String toString() {
return msg;
}
}


Factory implementation:

package sample;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class StudentFactory implements ObjectFactory {
public Object getObjectInstance(Object obj, Name name, Context ctx,
Hashtable env) throws Exception {
if (obj instanceof Reference) {
Reference ref = (Reference) obj;
if (ref.getClassName().equals(Student.class.getName())) {
RefAddr addr = ref.get("msg");
if (addr != null) {
Student s = new Student();
s.setMsg((String) addr.getContent());
return s;

}
}
}
return null;
}
}

Main code:
try {
//In the main() method of the program, create an initial directory context. 
//This is similar to creating an initial context in the previous naming example, 
//except that you use the constructor for InitialDirContext
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389/o=csRepository");

// Create the initial context
DirContext ctx = new InitialDirContext(env);

// Create attributes to be associated with the new context
Attributes attrs = new BasicAttributes(true); // case-ignore
Attribute objclass = new BasicAttribute("objectclass");
objclass.add("top");
objclass.add("organizationalUnit");
attrs.put(objclass);

Student student = new Student();
student.setMsg("hello World");

// Perform bind
ctx.bind("ou=Students", student, attrs);

// Check that it is bound
Student obj = (Student)ctx.lookup("ou=Students");

System.out.println(obj);

ctx.close();
}catch(NamingException e){
e.printStackTrace();
}

Output:
hello World


No comments:

Post a Comment