Renaming an ldap entry

In this post under Java LDAP, I will show with example how to rename an ldap entry.

To rename an ldap entry, Java LDAP api provides “rename” method which takes two arguments
1) the current name/fully qualified dn
2) the new name/fully qualified dn

Below is the complete main code for your reference

Main class

1  package package9;
2  
3  import javax.naming.Context;
4  import javax.naming.NamingException;
5  import javax.naming.directory.*;
6  import javax.naming.ldap.LdapContext;
7  import java.util.Hashtable;
8  
9  public class LDAPDemo9 {
10     public static void main(String[] args) {
11         Hashtable<String, Object> env = new Hashtable<String, Object>();
12         env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
13         env.put(Context.PROVIDER_URL, "ldap://localhost:1389");
14         env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=example,dc=org");
15         env.put(Context.SECURITY_CREDENTIALS, "adminpassword");
16 
17         DirContext ctx = null;
18         try {
19             ctx = new InitialDirContext(env);
20             //first approach
21             ctx.rename("ou=testing,dc=example,dc=org", "ou=tester,dc=example,dc=org");
22 
23             //second approach
24             DirContext dirContext = (DirContext) ctx.lookup("ou=dev,dc=example,dc=org");
25             dirContext.rename("cn=user1", "cn=jack");
26         } catch(Exception excep) {
27             excep.printStackTrace();
28         } finally {
29             if(ctx != null) {
30                 try {
31                     ctx.close();
32                 } catch(NamingException excep) {
33                     excep.printStackTrace();
34                 }
35             }
36         }
37     }
38 }

In the above code, at line 19, I create an instance of “InitialDirContext” class. This instance will be pointing to the root of the ldap tree.

At line 21, I follow the first approach, where I provide the fully qualified dn of the ldap entry as the first argument to “rename” method. Then I provide the new fully qualified dn of the ldap entry. In our case, the ldap entry with name “testing” is replaced with name “tester”.

At line 24, I follow the second approach. In this approach, I get a reference to parent of the ldap entry which has to be renamed. So for example I have to rename an ldap entry with
dn “cn=user1,ou=dev,dc=example,dc=org” to dn “cn=jack,ou=dev,dc=example,dc=org”. I get the ldap entry’s parent entry which in this case is “ou=dev,dc=example,dc=org”. I store the reference to the parent
entry in the variable “dirContext”.

At line 25, I call the “rename” method on “dirContext” instance and pass the old and new “cn” names.

In this way we can take any of the above two approaches to rename an ldap entry.

Leave a comment