Deleting an LDAP entry

In this post under Java LDAP, I will explain how to delete an LDAP entry.

The below figure shows the LDAP DIT (Directory Information Tree)

I will show two approaches to delete an ldap entry or sub context.

In the first approach we will delete the ldap entry with dn “cn=user3,ou=dev,dc=example,dc=org”.

In the second approach we will delete the ldap entry with dn “cn=user3,ou=dev,dc=example,dc=org”.

Below is the complete code

Main class

1  package package4;
2  
3  import java.util.Hashtable;
4  
5  import javax.naming.Context;
6  import javax.naming.NamingException;
7  import javax.naming.directory.DirContext;
8  import javax.naming.directory.InitialDirContext;
9  import javax.naming.ldap.LdapContext;
10 
11 public class LDAPDemo4 {
12     public static void main(String[] args) {
13         Hashtable<String, Object> env = new Hashtable<String, Object>();
14         env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
15         env.put(Context.PROVIDER_URL, "ldap://localhost:1389");
16         env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=example,dc=org");
17         env.put(Context.SECURITY_CREDENTIALS, "adminpassword");
18         DirContext ctx = null;
19         try {
20             ctx = new InitialDirContext(env);  //First approach
21             String dn = "cn=user3,ou=dev,dc=example,dc=org";
22             ctx.destroySubcontext(dn);
23             //Second approach
24             ctx = (DirContext) ctx.lookup("ou=dev,dc=example,dc=org");
25             ctx.destroySubcontext("cn=user4");
26         } catch(NamingException 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 first approach we mention the full dn and then call “destroySubcontext”. Refer to line 21 and 22.

In the second approach we retrieve a reference to the parent entry which in this case “ou=dev,dc=example,dc=org” and then call “destroySubcontext” on that parent context and pass only “cn” value of the ldap entry which we want to delete. Refer to line 24 and 25.

In this way we can delete an entry in ldap

Leave a comment