Mozilla LDAP SDK Programmer's Guide/Adding, Updating, and Deleting Entries With LDAP Java SDK

From MozillaWiki
Jump to: navigation, search

This section explains how to use the LDAP Java classes to add, modify, delete, and rename entries in the directory.

Adding an Entry With LDAP Java SDK

To add an entry to the directory, follow this general procedure:

  1. Create individual attributes for the entry.
  2. Create the set of attributes that make up the entry and add each of the attributes to this set.
  3. Create the new entry, specifying a unique distinguished name (DN) to identify the entry and the set of attributes that make up the entry.
  4. Add the new entry to directory.

Creating a New Attribute

An attribute can have a single value or multiple values. An attribute can contain string values or binary data. In the LDAP Java classes, an attribute is represented by an LDAPAttribute object.

To create a new attribute, use the LDAPAttribute constructor.

You can specify a single string value, multiple string values, or a binary value when constructing the object.

For example, the following section of code creates a new object for the attribute cn with the value Jane St. Clair.

LDAPAttribute attr = new LDAPAttribute("cn", "Jane St. Clair");

The following section of code creates an attribute objectclass with the values top, person, organizationalPerson, and inetOrgPerson.

String objectclasses[] = {"top", "person", "organizationalPerson",
    "inetOrgPerson"};
LDAPAttribute attr = new LDAPAttribute("objectclass", objectclasses);

You can also add string or binary values to an LDAPAttribute object by invoking the addValue method.

Creating a New Attribute Set

To specify the set of attributes in an entry, you need to create an attribute set. In the LDAP Java classes, a set of one or more attributes is represented by an LDAPAttributeSet object.

To create a new attribute set, use the LDAPAttributeSet constructor.

Invoke the add method to add LDAPAttribute objects to the set.

LDAPAttribute attr1 = new LDAPAttribute("cn", "Jane St. Clair");
String objectclasses[] = {"top", "person", "organizationalPerson",
    "inetOrgPerson"};
LDAPAttribute attr2 = new LDAPAttribute("objectclass", objectclasses);
LDAPAttributeSet attrSet = new LDAPAttributeSet();
attrSet.add(attr1);
attrSet.add(attr2);

Creating a New Entry

An entry contains a distinguished name (DN), which identifies the entry in the directory, and a set of attributes. In the LDAP Java classes, an entry is represented by an LDAPEntry object.

To create a new entry, use the LDAPEntry constructor.

LDAPAttribute attr1 = new LDAPAttribute("cn", "Jane St. Clair");
String objectclasses[] = {"top", "person", "organizationalPerson",
    "inetOrgPerson"};
LDAPAttribute attr2 = new LDAPAttribute("objectclass", objectclasses);
LDAPAttributeSet attrSet = new LDAPAttributeSet();
attrSet.add(attr1);
attrSet.add(attr2);
String dn = "uid=jsclair,ou=People,dc=example,dc=com";
LDAPEntry newEntry = new LDAPEntry(dn, attrs);

Adding the New Entry to the Directory

Before you add an entry to the directory, make sure that you have done the following:

  • You have specified the object classes of the entry using the objectclass attribute, and have specified the required attributes for those object classes.
    For example, organizational units might be represented by entries of the organizationalUnit object class. To add an entry for an organizational unit, you need to specify the following attributes in the entry:
    • objectclass with value top
    • objectclass with value organizationalUnit
    • ou with the value for the organizational unit, such as People
  • You have authenticated as a user who has the access permissions to add the entry to the directory.
    If you do not have permission to add the entry, an LDAPException is returned with result code LDAPException.INSUFFICIENT_ACCESS_RIGHTS.

To add the entry to the directory, invoke the add method of the LDAPConnection object.

try {
    LDAPConnection ld = new LDAPConnection();
    ld.connect("localhost", LDAPv3.DEFAULT_PORT); 
    ld.authenticate(bindDNWithWriteAccess, bindPassword);
    LDAPEntry newEntry = new LDAPEntry(dn, attrs);
    ld.add(newEntry);
} catch (LDAPException e) {
    System.err.println("Could not add " + dn + ":" + e.toString());
}

Example of Adding an Entry

The following example adds a new entry to the directory for the user who is named William Jensen.

import netscape.ldap.*;
import java.util.*;

public class Add {
    public static void main(String[] args) {
        /* Specify the DN to add */
        String dn = "uid=wbjensen, ou=People, dc=example,dc=com";

        /* Specify the attributes of the entry */
        String objectclass_values[] =
            {"top", "person", "organizationalPerson", "inetOrgPerson"};
        String cn_values[] =
            {"William B Jensen", "William Jensen", "Bill Jensen"};
        String sn_values[] = {"Jensen"};
        String givenname_values[] = {"William", "Bill"};
        String telephonenumber_values[] = {"+1 800 555 1212"};

        LDAPAttributeSet attrs = new LDAPAttributeSet();
        LDAPAttribute attr = new LDAPAttribute("objectclass");
        for (int i = 0; i  objectclass_values.length; i++) {
            attr.addValue(objectclass_values[i]);
        }
        attrs.add(attr);
        attr = new LDAPAttribute("cn");
        for (int i = 0; i  cn_values.length; i++) {
            attr.addValue(cn_values[i]);
        }
        attrs.add(attr);
        attr = new LDAPAttribute("sn");
        for (int i = 0; i  sn_values.length; i++) {
            attr.addValue(sn_values[i]);
        }
        attrs.add(attr);
        attr = new LDAPAttribute("givenname");
        for (int i = 0; i  givenname_values.length; i++) {
            attr.addValue(givenname_values[i]);
        }
        attrs.add(attr);
        attr = new LDAPAttribute("telephonenumber");
        for (int i = 0; i  telephonenumber_values.length; i++) {
            attr.addValue(telephonenumber_values[i]);
        }
        attrs.add(attr);
        attrs.add(new LDAPAttribute("uid", "wbjensen"));

        /* Create an entry with this DN and these attributes */
        LDAPEntry myEntry = new LDAPEntry(dn, attrs);

        try {
            /* Connect and authenticate as a user with write access. */
            UserArgs userArgs = new UserArgs("Add", args, true);
            LDAPConnection ld = new LDAPConnection();
            ld.connect(userArgs.getHost(), userArgs.getPort());
            ld.authenticate(userArgs.getBindDN(), userArgs.getPassword());

            /* Now add the entry to the directory */
            ld.add(myEntry);
            System.out.println("Entry added");

            ld.disconnect();
        } catch(LDAPException e) {
            if (e.getLDAPResultCode() ==
                LDAPException.ENTRY_ALREADY_EXISTS) {
                System.out.println("Error: Entry already present");
            } else {
                System.out.println("Error: " + e.toString());
            }
        }
    }
}

Modifying an Entry With LDAP Java SDK

To modify an entry in the directory, follow this general procedure:

  1. Specify each attribute change to make.
  2. If you are making only one change to the entry, construct an LDAPModification object that specifies the change that needs to be made.
  3. If you are making more than one change, you need to construct an LDAPModificationSet object that specifies the changes that need to be made.
  4. Use the DN of the entry to find and update the entry in the directory.

Specifying Attribute Changes

You can add new values to an attribute, remove existing attribute values, or change the values of an existing attribute. You can also remove an attribute by removing all values for the attribute or by not providing values for the attribute.

Adding New Attribute Values

To add new values to an attribute in an entry, construct a new LDAPAttribute object. Specify the name of the attribute. Also, specify the values to add. Then, perform one of the following operations:

  • If you are making a single change to the entry, construct a new LDAPModification object to specify that change.
    Pass LDAPModification.ADD and the LDAPAttribute object as arguments to the LDAPModification constructor.
  • If you are collecting multiple changes to an entry in an LDAPModificationSet object, invoke the add method.
    This method adds the change to the set of modifications. Pass LDAPModification.ADD and the LDAPAttribute object as arguments to this method.

For example, the following code excerpt adds the value babs@example.com to the mail attribute:

LDAPModificationSet mods = new LDAPModificationSet();
LDAPAttribute attrMail = new LDAPAttribute("mail", "babs@example.com");
mods.add(LDAPModification.ADD, attrMail);

If the specified attribute does not exist in the entry, the attribute is created for the entry.

Deleting Attribute Values

To remove values from an attribute in an entry, construct a new LDAPAttribute object, specifying the name of the attribute and the values to remove. Then, perform one of the following operations:

  • If you are making a single change to the entry, construct a new LDAPModification object to specify that change.
    Pass LDAPModification.DELETE and the LDAPAttribute object as arguments to the LDAPModification constructor.
  • If you are collecting multiple changes to an entry in an LDAPModificationSet object, invoke the add method.
    The method adds the change to the set of modifications. Pass LDAPModification.DELETE and the LDAPAttribute object as arguments to this method.

For example, the following code excerpt removes the value babs@example.com from the mail attribute:

LDAPModificationSet mods = new LDAPModificationSet();
LDAPAttribute attrMail = new LDAPAttribute("mail", "babs@example.com");
mods.add(LDAPModification.DELETE, attrMail);

If you remove all values from an attribute, the attribute is removed from the entry. If you do not specify any values in the LDAPAttribute object, the attribute is also removed from the entry.

Replacing Attribute Values

To replace values for an attribute in an entry, construct a new LDAPAttribute object, specifying the name of the attribute and the values to replace. Then, perform one of the following operations:

  • If you are making a single change to the entry, construct a new LDAPModification object to specify that change.
    Pass LDAPModification.REPLACE and the LDAPAttribute object as arguments to the LDAPModification constructor.
  • If you are collecting multiple changes to an entry in an LDAPModificationSet object, invoke the add method.
    The method adds the change to the set of modifications. Pass LDAPModification.REPLACE and the LDAPAttribute object as arguments to this method.

For example, the following code excerpt replaces the existing value of the mail attribute with babs@example.com:

LDAPModificationSet mods = new LDAPModificationSet();
LDAPAttribute attrMail = new LDAPAttribute("mail", "babs@example.com");
mods.add(LDAPModification.REPLACE, attrMail);

If the specified attribute does not exist in the entry, the attribute is created for the entry. If you do not specify any values in the LDAPAttribute object, the attribute is removed from the entry.

Removing an Attribute

To remove an attribute from an entry, perform one of the following operations:

  • Replace the values of the attribute with an LDAPAttribute object that contains no values.
  • Remove the values of the attribute with an LDAPAttribute object that contains no values.
  • Remove all values for the attribute.

For example, the following code excerpt demonstrates the first two options by preparing an LDAPModificationSet object to remove the mail and description attributes:

LDAPModificationSet mods = new LDAPModificationSet();
LDAPAttribute attrMail = new LDAPAttribute("mail");
LDAPAttribute attrDesc = new LDAPAttribute("description");
mods.add(LDAPModification.REPLACE, attrMail);
mods.add(LDAPModification.DELETE, attrDesc);

Modifying the Entry in the Directory

Before you modify an entry, make sure of the following:

  • You have not removed any of the required attributes for that object class.
  • You have authenticated as a user who has the access permissions to modify the entry in the directory.
    If you do not have permission to modify the entry, an LDAPException is returned with the result code LDAPException.INSUFFICIENT_ACCESS_RIGHTS.

You specify the change with an LDAPModification object. You specify a list of changes with an LDAPModificationSet object.

When finished specifying the change, pass the object with the DN of the entry to the modify method of the LDAPConnection object.

Example of Modifying an Entry

The following example modifies an entry in the directory.

import netscape.ldap.*;
import java.util.*;

public class ModAttrs {
    public static void main(String[] args) {
        String ENTRYDN = "uid=bjensen, ou=People, dc=example,dc=com";

        LDAPModificationSet mods = new LDAPModificationSet();
        LDAPAttribute attrEmail =
            new LDAPAttribute("mail", "babs@example.com");
        mods.add(LDAPModification.REPLACE, attrEmail);
        LDAPAttribute attrDesc = new LDAPAttribute("description",
            "This entry was modified with the ModAttrs program");
        mods.add(LDAPModification.ADD, attrDesc);

        try {
            /* Connect and authenticate as a user with write access. */
            UserArgs userArgs = new UserArgs("ModAttrs", args, true);
            LDAPConnection ld = new LDAPConnection();
            ld.connect(userArgs.getHost(), userArgs.getPort());
            ld.authenticate(userArgs.getBindDN(), userArgs.getPassword());

            /* Now modify the entry in the directory */
            ld.modify(ENTRYDN, mods);
            System.out.println("Entry modified" );

            ld.disconnect();
        } catch(LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT) {
                System.out.println("Error: No such entry");
            } else if (e.getLDAPResultCode() ==
                LDAPException.INSUFFICIENT_ACCESS_RIGHTS) {
                System.out.println("Error: Insufficient rights");
            } else if (e.getLDAPResultCode() ==
                LDAPException.ATTRIBUTE_OR_VALUE_EXISTS) {
                System.out.println("Error: Attribute or value exists");
            } else {
                System.out.println("Error: " + e.toString());
            }
        }
    }
}

Deleting an Entry With LDAP Java SDK

Before you delete an entry, authenticate as a user who has the access permissions to remove the entry from the directory. If you do not have permission to delete the entry, an LDAPException is returned with result code LDAPException.INSUFFICIENT_ACCESS_RIGHTS.

To remove an entry from the directory, invoke the delete method of the LDAPConnection object. Specify the DN of the entry that you want to remove.

The following example deletes the entry that is added in the previous example.

import netscape.ldap.*;
import java.util.*;

public class Del {
    public static void main(String[] args) {
        try {
            /* Connect and authenticate as a user with write access. */
            UserArgs userArgs = new UserArgs("Del", args, true);
            LDAPConnection ld = new LDAPConnection();
            ld.connect(userArgs.getHost(), userArgs.getPort());
            ld.authenticate(userArgs.getBindDN(), userArgs.getPassword());

            /* Specify the DN we're deleting */
            String dn = "uid=wbjensen, ou=People, dc=example,dc=com";

            ld.delete(dn);
            System.out.println("Entry deleted");

            ld.disconnect();
        } catch(LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT) {
                System.out.println("Error: No such entry");
            } else if (e.getLDAPResultCode() ==
                LDAPException.INSUFFICIENT_ACCESS_RIGHTS) {
                System.out.println("Error: Insufficient rights");
            } else {
                System.out.println("Error: " + e.toString());
            }
        }
    }
}

Renaming an Entry With LDAP Java SDK

Before you rename an entry, authenticate as a user who has the access permissions to perform the operation. If you do not have permission to rename the entry, an LDAPException is returned with result code LDAPException.INSUFFICIENT_ACCESS_RIGHTS.

To rename an entry, invoke the rename method of the LDAPConnection object. With this method, you can change the following:

  • The relative distinguished name (RDN) of the entry
  • The location of the entry in the directory by changing the DN and not just the RDN

Some LDAP servers do not support moving entries by changing their DNs. Check your LDAP server documentation for further information.

Changing the Relative Distinguished Name

When invoking the rename method of the LDAPConnection object, you can specify a deleteoldrdn parameter. The parameter allows you to remove the old RDN from the entry. Suppose an entry has the following values for the uid attribute:

uid: wbjensen
uid: wbj

The following code excerpt changes the user ID value wbjensen to wjensen and removes the wbjensen value:

ld.rename("uid=wbjensen,ou=People,dc=example,dc=com", "uid=wjensen", true);

The resulting values in the entry do not include the old RDN:

uid: wbjensen
uid: wbj

The following code excerpt retains the existing user ID value after the rename operation:

ld.rename("uid=wbjensen,ou=People,dc=example,dc=com", "uid=wjensen", false);

In this case, the resulting values in the entry do include the old RDN:

uid: wbjensen
uid: wjensen
uid: wbj

The DN after the rename operation is, however, uid=wjensen,ou=People,dc=example,dc=com.

The following example creates an entry and then renames it:

import netscape.ldap.*;
import java.util.*;

public class ModRdn {
    public static void main(String[] args) {
        /* Values for creating the entry */
        String objectclass_values[] =
            {"top", "person", "organizationalPerson", "inetOrgPerson"};
        String cn_values[] = {"Jacques Smith"};
        String sn_values[] = {"Smith"};
        String givenname_values[] = {"Jacques"};

        /* Specify the DN to add */
        String base = "ou=People, dc=example,dc=com";
        String dn = "uid=jsmith" + "," + base;
        String nrdn = "uid=jmsmith";    // The new RDN
        String ndn = nrdn + "," + base; // The target DN

        /* Create an attribute set with all desired attributes */
        LDAPAttributeSet attrs = new LDAPAttributeSet();
        LDAPAttribute attr =
            new LDAPAttribute("objectclass", objectclass_values);
        attrs.add(attr);
        attr = new LDAPAttribute("cn", cn_values);
        attrs.add(attr);
        attr = new LDAPAttribute("sn", sn_values);
        attrs.add(attr);
        attr = new LDAPAttribute("givenname", givenname_values);
        attrs.add(attr);
        attrs.add(new LDAPAttribute("uid", nrdn));

        /* Create an entry with this DN and these attributes */
        LDAPEntry myEntry = new LDAPEntry(dn, attrs);

        try {
            /* Connect and authenticate as a user with write access. */
            UserArgs userArgs = new UserArgs("ModRdn", args, true);
            LDAPConnection ld = new LDAPConnection();
            ld.connect(userArgs.getHost(), userArgs.getPort());
            ld.authenticate(userArgs.getBindDN(), userArgs.getPassword());

            /* Add the entry */
            try {
                ld.add(myEntry);
            } catch(LDAPException e) {
                /* If entry exists already, fine.  Ignore this error. */
                if (e.getLDAPResultCode() !=
                    LDAPException.ENTRY_ALREADY_EXISTS) throw e;
            }

            /* Delete the destination entry, for this example */
            try {
                ld.delete(ndn);
            }
            catch(LDAPException e) {
                /* If entry does not exist, fine.  Ignore this error. */
                if (e.getLDAPResultCode() != LDAPException.NO_SUCH_OBJECT)
                    throw e;
            }

            /* Do the modrdn operation */
            ld.rename(dn, nrdn, false);
            System.out.println("The modrdn operation was successful. ");
            System.out.println(
                "Entry " + dn + " has been changed to " + ndn);

            ld.disconnect();
        }
        catch(LDAPException e) {
            if (e.getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT) {
                System.out.println("Error: No such entry");
            } else if (e.getLDAPResultCode() ==
                LDAPException.INSUFFICIENT_ACCESS_RIGHTS) {
                System.out.println("Error: Insufficient rights");
            } else if (e.getLDAPResultCode() ==
                LDAPException.ATTRIBUTE_OR_VALUE_EXISTS) {
                System.out.println("Error: Attribute or value exists");
            } else {
                System.out.println("Error: " + e.toString());
            }
        }
    }
}

Changing the Distinguished Name

When invoking the rename method of the LDAPConnection object, you can specify a newParentDN parameter.

The parameter allows you to move the entry from one part of the directory to another part by changing its DN. You can use the parameter even if the RDN does not change.

The following example moves Sam Carter's entry from the organizational unit People, to the organizational unit Special Users:

import netscape.ldap.*;
import java.util.*;

public class ModDn {
    public static void main(String[] args) {
        try {
            /* Connect and authenticate as a user with write access. */
            UserArgs userArgs = new UserArgs("ModDn", args, true);
            LDAPConnection ld = new LDAPConnection();
            ld.connect(userArgs.getHost(), userArgs.getPort());
            ld.authenticate(3, userArgs.getBindDN(),userArgs.getPassword());

            /* Elevate Sam Carter from mere person to Special User. */
            String rdn = "uid=scarter";
            String oldParent = "ou=people,dc=example,dc=com";
            String newParent = "ou=special users,dc=example,dc=com";
            String dn = rdn + "," + oldParent;
            String ndn = rdn + "," + newParent;

            /* Read Sam's entry to make sure it exists before moving it. */
            try {
                LDAPEntry le = ld.read(dn);
            }
            catch(LDAPException e) {
                System.err.println(
                    "Cannot read " + dn + ": " + e.toString());
                throw e;
            }

            /* Delete the moved entry if it already exists. */
            try {
                ld.delete(ndn);
            }
            catch(LDAPException e) {
                /* Ignore notification that the new entry is not there. */
                if (e.getLDAPResultCode() != e.NO_SUCH_OBJECT) throw e;
            }

            /* Move Sam's entry. */
            ld.rename(dn, rdn, newParent, false);
            System.out.println("Entry " + dn + " has moved to " + ndn);

            ld.disconnect();
        }
        catch(LDAPException e) {
            System.err.println("Error: " + e.toString());
        }
    }
}