Previous Table of Contents Next


...
try
{
    DirContext dctx = new InitialDirContext(env);

    String filter = “(&(cn=E*)(account>1000))”;

    SearchControls sc = new SearchControls();
    sc.setCountLimit(5);

    NamingEnumeration result = 
         dctx.search(“ou=People”, filter, sc );

    while (result.hasMore())
        System.out.println(result.next());
} catch(SizeLimitExceededException se)
{

System.out.println(“More than five objects returned...”);
} catch(NamingException ne)
{
...

By setting the count limit to 5 in this code, only the first five results are returned.

Set a Time Limit on Retrieving Results

SearchControls allows you to limit the amount of waiting time for results. This is useful when you don’t want your program to block for a long time on searches that are taking awhile due to the performance of the server, the network, and so on. To do this, call the SearchControls method setTimeLimit and pass in the number of milliseconds you are willing to wait. Then the search returns results within that span of time, or the exception TimeLimitExceededException is thrown. Set the time limit to 0 to wait forever. Here is an example:

...
try
{
    DirContext dctx = new InitialDirContext(env);

    String filter = “(&(cn=E*)(account>1000))”;

    SearchControls sc = new SearchControls();
    // Wait 2 seconds
    sc.setTimeLimit(2000);

    NamingEnumeration result = 
         dctx.search(“ou=People”, filter, sc );

    while (result.hasMore())
        System.out.println(result.next());
} catch(TimeLimitExceededException te)
{

System.out.println(“More than two seconds have passed...”);
} catch(NamingException ne)
{
...

By setting the time limit, you force a search to return in a fixed amount of time. In this code, the setting of 2000 means that if the query cannot return due to a large number of results or a network failure, the search will be canceled after two seconds, which means the user is not subjected to a long wait for a response.

Modify Attributes

Now that values have been retrieved from the directory, let’s look at techniques for modifying the values of an object in the directory. The DirContext method modifyAttributes can be used for this purpose. Table 5.14 lists the variations of this method.

The simple form of the modifyAttributes method takes a named object (Name or String), a modification operation (listed below), and a list of attributes to modify (instance of Attributes).

Table 5.14 DirContext modifyAttributes Method Variations

METHOD USE

void modifyAttributes(Name name, int mod_op, Attributes attrs) Modifies the attributes contained in attrs of the object described by the non-null name. The operation to perform is ADD_ATTRIBUTE, REPLACE_ATTRIBUTE, or REMOVE_ATTRIBUTE. The operations occur in no particular order.

void modifyAttributes(Name name, ModificationItem[] mods) Performs the modifications of the attributes as specified in mods of the object described by the non-null name. The operations occur in the order they are defined in the ModificationItem array.

void modifyAttributes(String name, int mod_op, Attributes attrs) Modifies the attributes contained in attrs of the object described by the non-null name. The operation to perform is ADD_ATTRIBUTE, REPLACE_ATTRIBUTE, or REMOVE_ATTRIBUTE. The operations occur in no particular order.

void modifyAttributes(String name, ModificationItem[] mods) Performs the modifications of the attributes as specified in mods of the object described by the non-null name. The operations occur in the order they are defined in the ModificationItem array.

The modification operation can be one of the following constants:

  DirContext.ADD_ATTRIBUTE
  DirContext.REPLACE_ATTRIBUTE
  DirContext.REMOVE_ATTRIBUTE

For example, given a person named John, suppose that you want to add an e-mail address john@pri.com and an empty website address attribute. The code below uses the modifyAttributes method of DirContext to specify that a set of attributes should be added to the object John in the current context.

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

public class Modify1Example
{
    public static void main(String args[])
    {
        Hashtable env = new Hashtable(11);


        env.put(Context.INITIAL_CONTEXT_FACTORY,
            “com.sun.jndi.ldap.LdapCtxFactory”);
        env.put(Context.PROVIDER_URL,
            “ldap://MyHost/o=JNDIExample”);
        try
        {
            DirContext dctx = new InitialDirContext(env);
            Attributes attrs = new BasicAttributes(true);
            attrs.put(new BasicAttribute(“email”,“john@pri.com”));
            attrs.put(new BasicAttribute(“website”));

            dctx.modifyAttributes(“cn=John, ou=People”,
                                  DirContext.ADD_ATTRIBUTE,
                                  attrs);
        }catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Using this technique, you can add, modify, and delete attributes. The only problem is that each modify call can perform only a single operation on a set of attributes.

Create a Modification List

The previous modifyAttributes example is useful when you want to perform one atomic operation on one or more attributes. However, it is often more useful to perform several operations at once. For example, let’s say a person named Karen moved from the marketing department to the sales department. The program will need to change Karen’s attributes to reflect the move. Karen may also require a sales quota attribute with an initial value. Maybe she doesn’t have an assistant anymore, so that attribute should be removed. Rather than executing three modifyAttributes calls, you use a ModificationItem list to specify these changes. A ModificationItem consists of one of the operation constants in the preceding example specifying the operation, as well as an Attribute to modify. Modifications are applied in the order in which they appear in the list; either all of the modifications are executed, or none are. The following example performs the position transfer for Karen.

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

public class Modify2Example
{
    public static void main(String args[])
    {
        Hashtable env = new Hashtable(11);

        env.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL,
            "ldap://MyHost/o=JNDIExample");
        try
        {
            DirContext dctx = new InitialDirContext(env);

            ModificationItem[] mods = new ModificationItem[3];
            mods[0] = new ModificationItem(
                DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute("department", "sales"));
            mods[1] = new ModificationItem(
                DirContext.ADD_ATTRIBUTE,
                new BasicAttribute("quota", "$1,000,000"));
            mods[2] = new ModificationItem(
                DirContext.REMOVE_ATTRIBUTE,
                new BasicAttribute("assistant"));

            dctx.modifyAttributes("cn=Karen, ou=People", mods);
        }catch(Exception e)
        {
            System.out.println(e);
        }
    }
}


Previous Table of Contents Next