Modify LDAP records with JNDI

[problem]

Need to modify an LDAP record with JNDI, the Java Naming Directory Interface.

Following on from using java to perform LDAP searches, here is a quick demo on modifying records.

[/problem]

[solution]

Here I’m using java to modify John Doe’s record, changing the givenname entry to John A.

As you’ll notice all values are hard coded (such as hostname, port, password, etc). These could be read in from a config file, or passed in through command line arguments.

[/solution]

[example]


$ cat chLdapDetails.java
import java.util.*;
import java.io.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;

public class chLdapDetails {

public static void main(String argv[]) {

String url="ldap://127.0.0.1:389";
Hashtable env=new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,url);
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,
"cn=Manager,dc=demo,dc=net");
env.put(Context.SECURITY_CREDENTIALS,"secret");

try {

DirContext ctx=new InitialDirContext(env);
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("givenname","John A"));
ctx.modifyAttributes("cn=jdoe,dc=demo,dc=net", mods);
ctx.close();

} catch(NamingException ne) { System.err.println(ne.toString()); }

}
}

Heres a run through:


$ java getLdapDetails Doe
John, Doe - [email protected]

$ java chLdapDetails
$ java getLdapDetails Doe
John A, Doe - [email protected]

[/example]

[reference]

[tags]LDAP updates JNDI, JNDI LDAP, JNDI, LDAP Training School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

Your email address will not be published. Required fields are marked *