I want to add any data(entry) to the LDAP server. I tried the following code. One method to connect which works, and the other to add entry which doesn't work.
Any advice or solutions?
I am attaching the screenshot of my LDAP server:
public static DirContext connectJndi() throws NamingException {
//method to connect to LDAP server using JNDI
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://192.168.0.60:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "******");
env.put(Context.SECURITY_CREDENTIALS, "*******");
//DirContext ctx = new InitialDirContext(env);
LdapContext ctx = new InitialLdapContext(env,null);
return ctx; // connection method works.
}
//this method doesn't work.
public static void insertJndi( ) throws NamingException {
LdapContext ctx = (LdapContext) connectJndi(); //connecting to the server
LDAPAttributeSet attrs = new LDAPAttributeSet();
String objectclass_values[] = { "top", "person", "op","11" };
LDAPAttribute attr = new LDAPAttribute("objectclass",objectclass_values);
//Attribute objectClass = new BasicAttribute("objectClass");
attrs.add(attr);
LDAPEntry myEntry = new LDAPEntry("cn=jin,c=kr", attrs);
ctx.add(myEntry);
I tried other API instead and it worked. I was going to erase this question, but this might help some people, so I am copying my code here. If not, I'll erase it.
public static void insertJndi( ) throws NamingException {
DirContext ctx = connectJndi();
Attributes attributes = new BasicAttributes();
Attribute objectClass = new BasicAttribute("objectClass");
objectClass.add("anything");
attributes.put(objectClass);
Attribute a = new BasicAttribute("a");
Attribute b = new BasicAttribute("b");
a.add("jin");
b.add("lee");
attributes.put(a);
attributes.put(b);
ctx.createSubcontext("cn=a002,ou=b,ou=c,ou=d,o=government of Mars,c=Earth", attributes);
System.out.println("it worked");