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

how to retrieve your ip address with powershell...

update: this is how it’s performed in powershell v3 as demonstrated here.(get-netadapter | get-netipaddress | ? addressfamily -eq'IPv4').ipaddress update: this is by far the easiest.PS C:\temp> (gwmi Win32_NetworkAdapterConfiguration | ? { $_.IPAddress -ne $null }).ipaddress
192.168.1.101
are you laughing yet?  i know you probably find this topic amusing.  it's really interesting though.  whenever you get over it, i'll do this in the standard cmd.exe interpreter and then in powershell to show you what kind of coolness powershell does.done?  okay, good.  this is an interpretation of a demo that bob wells did at our smug meeting.  hope you like it.i should tell you, it's not as simple as the title would lead you to believe.  i like doing that little slight-of-hand thing since it gives the impression that i'm painting a very easy target on my back for your criticism (though it's probably true in other ways)!  the idea is that we want to retrieve just the ip ad…

understanding the “ad op master is inconsistent” alert

i use the term “understanding” loosely.  this is by far no definitive guide on this particular alert, just a few things i have picked up in my attempt to understand it.let’s look at the context of the alert:The Domain Controller's Op Master is inconsitent. See additional alerts for details.
first of all, it gives very little information.  the only particularly useful detail is that it indicates which server is having the issue.  other than that, just a spelling error as there are no additional critical alerts to look at for details.this rule, as you know, comes from a sealed mp.  therefore, we can’t modify anything in it except the overrides.  the couple i’ve tinkered with are:interval (sec) log success event to begin with, interval (sec) is just set way too high.  the default is 60 seconds.  why on earth would anyone want to know that your op master consistency may be off, every minute?  actually, i could think of a few reasons, but really, it’s overkill.  the way the script works…

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.DETECTIONstatus messagestake 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 material to …