Listing 5: Add.java — Adds an object to the directory tree

package jndisamples;

import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.*;

public class Add {
  public static void main(String[] args) {
    try{
      InitialDirContext root =
        login("127.0.0.1", 
              "cn=mseaver,ou=HR,o=SLC", "password");

      // Add a new user object to the Engineering container
      DirContext ctx = (DirContext)root.lookup("ou=ENG,o=SLC");
      Attributes attrs = new BasicAttributes();

      // Single Value
      attrs.put("sn", "testusersn");
      attrs.put("objectClass", "User");

      // Multi Value
      Attribute givenName = new BasicAttribute("givenName");
      givenName.add("Michael");
      givenName.add("James");
      attrs.put(givenName);

      // Add Object
      ctx.createSubcontext("cn=testuser", attrs);
      System.out.println("Object Successfully Added");
      root.close();

    }catch(NamingException ex){
      System.out.println("Error: " + ex);
    }
  }

  private static InitialDirContext
  login(String ipaddr, String user, String password)
      throws NamingException{
    Hashtable environment = new Hashtable();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, 
                    "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL, "ldap://" + ipaddr + 
                                                //":389");
    environment.put(Context.SECURITY_PRINCIPAL, user);
    environment.put(Context.SECURITY_CREDENTIALS, password);
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");

    InitialDirContext root = new InitialDirContext(environment);
    System.out.println("Successfully Logged-In");

    return root;
  }
}

/* Output:
Successfully Logged-In
Object Successfully Added
*/
— End of Listing —