ds: paged results with jndi ldap (java)
I see this often enough that I thought I'd give myself a reference for when I see a lead on it.
first example is on the forums.sun.com site. http://forums.sun.com/thread.jspa?threadID=578347&tstart=0
second example on the java2s.com site. http://www.java2s.com/Code/Java/JNDI-LDAP/howapagedsearchcanbeperformedusingthePagedResultsControlAPI.htm
since I know nothing about java, I can't validate that this works... but it's good reference.
1: /**
2: * paged.java
3: * 5 July 2001
4: * Sample JNDI application that performs a paged search.
5: *
6: */
7:
8: import java.util.Hashtable;
9: import java.util.Enumeration;
10:
11: import javax.naming.*;
12: import javax.naming.directory.*;
13: import javax.naming.ldap.*;
14: import com.sun.jndi.ldap.ctl.*;
15:
16: class paged {
17:
18: public static void main(String[] args) {
19:
20:
21: Hashtable env = new Hashtable();
22: String adminName = "CN=Administrator,CN=Users,DC=antipodes,DC=com";
23: String adminPassword = "XXXXXXXX";
24: String searchBase = "DC=antipodes,DC=com";
25: String searchFilter = "(&(objectClass=user)(mail=*))";
26:
27: env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
28:
29: //set security credentials, note using simple cleartext authentication
30: env.put(Context.SECURITY_AUTHENTICATION,"simple");
31: env.put(Context.SECURITY_PRINCIPAL,adminName);
32: env.put(Context.SECURITY_CREDENTIALS,adminPassword);
33:
34: //connect to my domain controller
35: env.put(Context.PROVIDER_URL, "ldap://mydc.antipodes.com:389");
36: try {
37:
38: // Create the initial directory context
39: LdapContext ctx = new InitialLdapContext(env,null);
40:
41: // Create the search controls
42: SearchControls searchCtls = new SearchControls();
43:
44: //Specify the attributes to return
45: String returnedAtts[]={"sn","givenName","mail"};
46: searchCtls.setReturningAttributes(returnedAtts);
47:
48: //Specify the search scope
49: searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
50:
51: //Set the page size and initialize the cookie that we pass back in subsequent pages
52: int pageSize = 10;
53: byte[] cookie = null;
54:
55: //Request the paged results control
56: Control[] ctls = new Control[]{new PagedResultsControl(pageSize)};
57: ctx.setRequestControls(ctls);
58:
59: //initialize counter to total the results
60: int totalResults = 0;
61:
62: // Search for objects using the filter
63:
64: do {
65: NamingEnumeration results = ctx.search(searchBase, searchFilter, searchCtls);
66:
67: // loop through the results in each page
68:
69: while (results != null && results.hasMoreElements()) {
70: SearchResult sr = (SearchResult)results.next();
71:
72: //print out the name
73: System.out.println("name: " + sr.getName());
74:
75: //increment the counter
76: totalResults++;
77:
78: }
79:
80:
81: // examine the response controls
82: cookie = parseControls(ctx.getResponseControls());
83:
84: // pass the cookie back to the server for the next page
85: ctx.setRequestControls(new Control[]{new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
86:
87: } while ((cookie != null) && (cookie.length != 0));
88:
89:
90: ctx.close();
91:
92: System.out.println("Total entries: " + totalResults);
93:
94:
95: }
96: catch (NamingException e) {
97: System.err.println("Paged Search failed." + e);
98: }
99: catch (java.io.IOException e) {
100: System.err.println("Paged Search failed." + e);
101: }
102: }
103:
104: static byte[] parseControls(Control[] controls) throws NamingException {
105:
106: byte[] cookie = null;
107:
108: if (controls != null) {
109:
110: for (int i = 0; i < controls.length; i++) {
111: if (controls[i] instanceof PagedResultsResponseControl) {
112: PagedResultsResponseControl prrc = (PagedResultsResponseControl)controls[i];
113: cookie = prrc.getCookie();
114: System.out.println(">>Next Page \n");
115: }
116: }
117: }
118:
119: return (cookie == null) ? new byte[0] : cookie;
120: }
121: }
1: /*
2: * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
3: *
4: * Redistribution and use in source and binary forms, with or without
5: * modification, are permitted provided that the following conditions
6: * are met:
7: *
8: * - Redistributions of source code must retain the above copyright
9: * notice, this list of conditions and the following disclaimer.
10: *
11: * - Redistributions in binary form must reproduce the above copyright
12: * notice, this list of conditions and the following disclaimer in the
13: * documentation and/or other materials provided with the distribution.
14: *
15: * - Neither the name of Sun Microsystems nor the names of its
16: * contributors may be used to endorse or promote products derived
17: * from this software without specific prior written permission.
18: *
19: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20: * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21: * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22: * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23: * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24: * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25: * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26: * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27: * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28: * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29: * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30: */
31:
32: import java.io.IOException;
33: import java.util.Hashtable;
34:
35: import javax.naming.Context;
36: import javax.naming.NamingEnumeration;
37: import javax.naming.NamingException;
38: import javax.naming.directory.SearchControls;
39: import javax.naming.directory.SearchResult;
40: import javax.naming.ldap.Control;
41: import javax.naming.ldap.InitialLdapContext;
42: import javax.naming.ldap.LdapContext;
43: import javax.naming.ldap.PagedResultsControl;
44: import javax.naming.ldap.PagedResultsResponseControl;
45:
46: /**
47: * Shows how a paged search can be performed using the PagedResultsControl API
48: */
49:
50: class PagedSearch {
51:
52: public static void main(String[] args) {
53:
54: Hashtable<String, Object> env = new Hashtable<String, Object>(11);
55: env
56: .put(Context.INITIAL_CONTEXT_FACTORY,
57: "com.sun.jndi.ldap.LdapCtxFactory");
58:
59: /* Specify host and port to use for directory service */
60: env.put(Context.PROVIDER_URL,
61: "ldap://localhost:389/ou=People,o=JNDITutorial");
62:
63: try {
64: LdapContext ctx = new InitialLdapContext(env, null);
65:
66: // Activate paged results
67: int pageSize = 5;
68: byte[] cookie = null;
69: ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize,
70: Control.NONCRITICAL) });
71: int total;
72:
73: do {
74: /* perform the search */
75: NamingEnumeration results = ctx.search("", "(objectclass=*)",
76: new SearchControls());
77:
78: /* for each entry print out name + all attrs and values */
79: while (results != null && results.hasMore()) {
80: SearchResult entry = (SearchResult) results.next();
81: System.out.println(entry.getName());
82: }
83:
84: // Examine the paged results control response
85: Control[] controls = ctx.getResponseControls();
86: if (controls != null) {
87: for (int i = 0; i < controls.length; i++) {
88: if (controls[i] instanceof PagedResultsResponseControl) {
89: PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
90: total = prrc.getResultSize();
91: if (total != 0) {
92: System.out.println("***************** END-OF-PAGE "
93: + "(total : " + total + ") *****************\n");
94: } else {
95: System.out.println("***************** END-OF-PAGE "
96: + "(total: unknown) ***************\n");
97: }
98: cookie = prrc.getCookie();
99: }
100: }
101: } else {
102: System.out.println("No controls were sent from the server");
103: }
104: // Re-activate paged results
105: ctx.setRequestControls(new Control[] { new PagedResultsControl(
106: pageSize, cookie, Control.CRITICAL) });
107:
108: } while (cookie != null);
109:
110: ctx.close();
111:
112: } catch (NamingException e) {
113: System.err.println("PagedSearch failed.");
114: e.printStackTrace();
115: } catch (IOException ie) {
116: System.err.println("PagedSearch failed.");
117: ie.printStackTrace();
118: }
119: }
120: }
Comments
Post a Comment