import javax.naming.*;
import javax.naming.directory.*;

import java.util.Hashtable;

/**
 * Demonstrates how to search the directory while automatically
 * following referrals.
 *
 * usage: java Follow
 */
class Follow {
    public static void main(String[] args) {


	// Set up environment for creating initial context
	Hashtable env = new Hashtable(11);
	env.put(Context.INITIAL_CONTEXT_FACTORY, 
	    "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.PROVIDER_URL, "ldap://localhost:489/o=JNDITutorial");

	// Set referral property to "follow" referrals automatically
	env.put(Context.REFERRAL, "follow");

	try {
	    // Create initial context
	    DirContext ctx = new InitialDirContext(env);

	    // Set controls for performing subtree search
	    SearchControls ctls = new SearchControls();
	    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

	    // Perform search
	    NamingEnumeration answer = ctx.search("", "(objectclass=*)", ctls);

	    // Print the answer
	    while (answer.hasMore()) {
		System.out.println(">>>" + ((SearchResult)answer.next()).getName());
	    }
	} catch (NamingException e) {
	    e.printStackTrace();
	}
    }
}
