Wednesday 25 May 2016

Delete an entry from LDAP using JNDI

In my previous post, I explained how to update attributes of an entry in LDAP using JNDI. In this post, I am going to explain, how to delete an entry from LDAP using JNDI. It is very simple, call the method destroySubcontext of DirContext by passing distinguished name as argument.

Before deletion, I had 5 entries in organizational unit “people”.

import java.util.Objects;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class DirectoryUtil {
    private final static String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
    private final static String PROVIDER_URL = "ldap://localhost:10389";
    private static DirContext context = null;

    public static DirContext getContext() throws NamingException {
        if (!Objects.isNull(context)) {
            return context;
        }

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
        properties.put(Context.PROVIDER_URL, PROVIDER_URL);
        DirContext context = new InitialDirContext(properties);
        return context;
    }
}

import javax.naming.NamingException;
import javax.naming.directory.DirContext;

public class Test {

    public static void main(String[] args) throws NamingException {
        DirContext context = DirectoryUtil.getContext();

        String distinguishedName = "cn=Sandesh,ou=people,dc=example,dc=com";

        context.destroySubcontext(distinguishedName);

    }

}

Run above program, it deletes an entry from LDAP.





Previous                                                 Next                                                 Home

No comments:

Post a Comment