Wednesday 25 May 2016

Update an Entry using JNDI

In my previous post, I explained how to add new entry using JNDI. In this post, I am going to explain how to update existing entry.

By passing the distinguished name and new attributes, to the method modifyAttributes, you can update existing attributes of entry.

For example, I am going to update description for the entry “cn=Sandesh,ou=people,dc=example,dc=com”. Following is the information for “cn=Sandesh,ou=people,dc=example,dc=com” before updation.


Following application updates the description field.
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.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
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";

        Attributes attributes = new BasicAttributes();
        Attribute description = new BasicAttribute("description",
                "Tech Lead, working for Company ABCD");

        attributes.put(description);

        context.modifyAttributes(distinguishedName,
                DirContext.REPLACE_ATTRIBUTE, attributes);

    }

}

Run above application it updates the description for person Sandesh.




Previous                                                 Next                                                 Home

No comments:

Post a Comment