Skip to main content

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

Popular posts from this blog

using preloadpkgonsite.exe to stage compressed copies to child site distribution points

UPDATE: john marcum sent me a kind email to let me know about a problem he ran into with preloadpkgonsite.exe in the new SCCM Toolkit V2 where under certain conditions, packages will not uncompress.  if you are using the v2 toolkit, PLEASE read this blog post before proceeding.   here’s a scenario that came up on the mssms@lists.myitforum.com mailing list. when confronted with a situation of large packages and wan links, it’s generally best to get the data to the other location without going over the wire. in this case, 75gb. :/ the “how” you get the files there is really not the most important thing to worry about. once they’re there and moved to the appropriate location, preloadpkgonsite.exe is required to install the compressed source files. once done, a status message goes back to the parent server which should stop the upstream server from copying the package source files over the wan to the child site. anyway, if it’s a relatively small amount of packages, you can

How to Identify Applications Using Your Domain Controller

Problem Everyone has been through it. We've all had to retire or replace a domain controller at some point in our checkered collective experiences. While AD provides very intelligent high availability, some applications are just plain dumb. They do not observe site awareness or participate in locating a domain controller. All they want is the name or IP of one domain controller which gets hardcoded in a configuration file somewhere, deeply embedded in some file folder or setting that you are never going to find. How do you look at a DC and decide which applications might be doing it? Packet trace? Logs? Shut it down and wait for screaming? It seems very tedious and nearly impossible. Potential Solution Obviously I wouldn't even bother posting this if I hadn't run across something interesting. :) I ran across something in draftcalled Domain Controller Isolation. Since it's in draft, I don't know that it's published yet. HOWEVER, the concept is based off

sccm: content hash fails to match

back in 2008, I wrote up a little thing about how distribution manager fails to send a package to a distribution point . even though a lot of what I wrote that for was the failure of packages to get delivered to child sites, the result was pretty much the same. when the client tries to run the advertisement with an old package, the result was a failure because of content mismatch. I went through an ordeal recently capturing these exact kinds of failures and corrected quite a number of problems with these packages. the resulting blog post is my effort to capture how these problems were resolved. if nothing else, it's a basic checklist of things you can use.   DETECTION status messages take a look at your status messages. this has to be the easiest way to determine where these problems exist. unfortunately, it requires that a client is already experiencing problems. there are client logs you can examine as well such as cas, but I wasn't even sure I was going to have enough m