8.3. Modifying Directory Entry Attribute Values

The Connection.modify() methods let you add, replace, and delete attributes values on an entry. Either the modifications are expressed in LDIF, or you build a ModifyRequest to express the changes.

The following excerpt demonstrates how to replace one attribute value and to add another.

final LDAPConnectionFactory factory = new LDAPConnectionFactory(host, port);
Connection connection = null;
try {
    connection = factory.getConnection();
    // Bind as a user who has the right to modify entries.
    connection.bind(adminDN, adminPwd);

    // Here, entry is a user entry with DN cn=Bob,ou=People,dc=example,dc=com.
    Entry old = TreeMapEntry.deepCopyOfEntry(entry);
    entry = entry.replaceAttribute("mail", "spammer@example.com")
            .addAttribute("description", "I see the fnords.");
    ModifyRequest request = Entries.diffEntries(old, entry);

    connection.modify(request);

} catch (final ErrorResultException e) {
    System.err.println(e.getMessage());
    System.exit(e.getResult().getResultCode().intValue());
    return;
} finally {
    if (connection != null) {
        connection.close();
    }
}