8.2. Adding Directory Entries

The Connection.add() methods let you provide the entry to add as an AddRequest, an Entry, or as LDIF. If the changes to make are already expressed in LDIF, then you can also use ChangeRecordReaders, ChangeRecords, and ChangeRecordWriters to handle the changes.

The following excerpt demonstrates how to add a simple user entry under ou=People,dc=example,dc=com.

// An entry to add to the directory
Entry entry = new LinkedHashMapEntry("cn=Bob,ou=People,dc=example,dc=com")
    .addAttribute("cn", "Bob")
    .addAttribute("objectclass", "top")
    .addAttribute("objectclass", "person")
    .addAttribute("objectclass", "organizationalPerson")
    .addAttribute("objectclass", "inetOrgPerson")
    .addAttribute("mail", "subgenius@example.com")
    .addAttribute("sn", "Dobbs");

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

    connection.add(entry);

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