SearchControlsExample.java Source code

Java tutorial

Introduction

Here is the source code for SearchControlsExample.java

Source

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class SearchControlsExample {
    public static void main(String[] argc) throws Exception {
        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");

        DirContext dctx = new InitialDirContext(env);

        String filter = "(&(cn=S*)(account>1005))";

        String[] attrIDs = { "cn", "email" };
        SearchControls sc = new SearchControls();
        sc.setReturningAttributes(attrIDs);

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

        while (result.hasMore()) {
            SearchResult sr = (SearchResult) result.next();
            System.out.println("Result = " + sr.getName());
        }

    }
}