Java/JNDI LDAP/Search
Содержание
- 1 how a paged search can be performed using the PagedResultsControl API
- 2 how sorted search results can be obtained using SortControl API
- 3 how to do the equivalent of an LDAP "compare"
- 4 how to perform a search and limit the number of results returned
- 5 how to perform a search and limit the time that the search takes
- 6 how to perform a search by specifying a search filter and default search controls
- 7 how to perform a search by specifying a search filter and search controls
- 8 how to perform a search by specifying a search filter and search controls to search an object
- 9 how to perform a search by specifying a search filter and search controls to search a subtree
- 10 how to perform a search by specifying a search filter, objects to fill in filter, andsearch controls
- 11 how to search the directory that ignores referrals returned by the server
- 12 LDAP Search
how a paged search can be performed using the PagedResultsControl API
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.io.IOException; import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.Control; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; import javax.naming.ldap.PagedResultsControl; import javax.naming.ldap.PagedResultsResponseControl; /**
* Shows how a paged search can be performed using the PagedResultsControl API */
class PagedSearch {
public static void main(String[] args) { Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); /* Specify host and port to use for directory service */ env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial"); try { LdapContext ctx = new InitialLdapContext(env, null); // Activate paged results int pageSize = 5; byte[] cookie = null; ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; do { /* perform the search */ NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls()); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult entry = (SearchResult) results.next(); System.out.println(entry.getName()); } // Examine the paged results control response Control[] controls = ctx.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { System.out.println("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { System.out.println("***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { System.out.println("No controls were sent from the server"); } // Re-activate paged results ctx.setRequestControls(new Control[] { new PagedResultsControl( pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); ctx.close(); } catch (NamingException e) { System.err.println("PagedSearch failed."); e.printStackTrace(); } catch (IOException ie) { System.err.println("PagedSearch failed."); ie.printStackTrace(); } }
}
</source>
how sorted search results can be obtained using SortControl API
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.io.IOException; import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.Control; import javax.naming.ldap.HasControls; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; import javax.naming.ldap.SortControl; import javax.naming.ldap.SortResponseControl; /**
* Shows how sorted search results can be obtained using SortControl API */
class SortedResults {
public static void main(String[] args) throws IOException { // Set up environment for creating initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial"); try { // Create initial context with no connection request controls LdapContext ctx = new InitialLdapContext(env, null); // Create a sort control that sorts based on CN String sortKey = "cn"; ctx.setRequestControls(new Control[] { new SortControl(sortKey, Control.CRITICAL) }); // Perform a search NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls()); // Iterate over search results System.out.println("---->sort by cn"); while (results != null && results.hasMore()) { // Display an entry SearchResult entry = (SearchResult) results.next(); System.out.println(entry.getName()); // Handle the entry"s response controls (if any) if (entry instanceof HasControls) { // ((HasControls)entry).getControls(); } } // Examine the sort control response Control[] controls = ctx.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof SortResponseControl) { SortResponseControl src = (SortResponseControl) controls[i]; if (!src.isSorted()) { throw src.getException(); } } else { // Handle other response controls (if any) } } } // Close when no longer needed ctx.close(); } catch (NamingException e) { e.printStackTrace(); } }
}
</source>
how to do the equivalent of an LDAP "compare"
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
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; /**
* Demonstrates how to do the equivalent of an LDAP "compare". * * usage: java Compare */
class Compare {
public static void main(String[] args) { // Set up environment for creating initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Value of attribute byte[] key = { (byte) 0x61, (byte) 0x62, (byte) 0x63, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x67 }; // Set up search controls SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[0]); // return no attrs ctls.setSearchScope(SearchControls.OBJECT_SCOPE); // search object only // Invoke search method that will use the LDAP "compare" operation NamingEnumeration answer = ctx.search("cn=S. User, ou=NewHires", "(mySpecialKey={0})", new Object[] { key }, ctls); // Print the answer // FilterArgs.printSearchEnumeration(answer); // Close the context when we"re done ctx.close(); } catch (NamingException e) { e.printStackTrace(); } }
}
</source>
how to perform a search and limit the number of results returned
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.SizeLimitExceededException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; /**
* Demonstrates how to perform a search and limit the number of results * returned. * * usage: java SearchCountLimit */
class SearchCountLimit {
static int expected = 1; public static void printSearchEnumeration(NamingEnumeration srhEnum) { int count = 0; try { while (srhEnum.hasMore()) { SearchResult sr = (SearchResult) srhEnum.next(); System.out.println(">>>" + sr.getName()); ++count; } System.out.println("number of answers: " + count); } catch (SizeLimitExceededException e) { if (count == expected) System.out.println("number of answers: " + count); else e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } } public static void main(String[] args) { // Set up the environment for creating the initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Set search controls to limit count to "expected" SearchControls ctls = new SearchControls(); ctls.setCountLimit(expected); // Search for objects with those matching attributes NamingEnumeration answer = ctx.search("ou=People", "(sn=M*)", ctls); // Print the answer printSearchEnumeration(answer); // Close the context when we"re done ctx.close(); } catch (Exception e) { System.err.println(e); } }
}
</source>
how to perform a search and limit the time that the search takes
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.TimeLimitExceededException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; /**
* Demonstrates how to perform a search and limit the time that the search * takes. * * usage: java SearchTimeLimit */
class SearchTimeLimit {
static int timeout = 1000; // 1 second == 1000 ms public static void printSearchEnumeration(NamingEnumeration srhEnum) { int count = 0; try { while (srhEnum.hasMore()) { SearchResult sr = (SearchResult) srhEnum.next(); System.out.println(">>>" + sr.getName()); ++count; } System.out.println("number of answers: " + count); } catch (TimeLimitExceededException e) { System.out.println("search took more than " + timeout + "ms"); } catch (NamingException e) { e.printStackTrace(); } } public static void main(String[] args) { // Set up the environment for creating the initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Set search controls to limit count to "timeout" SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setTimeLimit(timeout); // // Search for objects with those matching attributes NamingEnumeration answer = ctx.search("", "(objectclass=*)", ctls); // Print the answer printSearchEnumeration(answer); // Close the context when we"re done ctx.close(); } catch (TimeLimitExceededException e) { System.out.println("time limit exceeded"); } catch (Exception e) { System.err.println(e); } }
}
</source>
how to perform a search by specifying a search filter and default search controls
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; /**
* Demonstrates how to perform a search by specifying a search filter and * default search controls. Functionally identical to SearchRetAll.java. * * usage: java SearchWithFilterRetAll */
class SearchWithFilterRetAll {
public static void main(String[] args) { // Set up the environment for creating the initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Create default search controls SearchControls ctls = new SearchControls(); // Specify the search filter to match // Ask for objects with attribute sn == Geisel and which have // the "mail" attribute. String filter = "(&(sn=Geisel)(mail=*))"; // Search for objects using filter NamingEnumeration answer = ctx.search("ou=People", filter, ctls); // Print the answer // Search.printSearchEnumeration(answer); // Close the context when we"re done ctx.close(); } catch (Exception e) { e.printStackTrace(); } }
}
</source>
how to perform a search by specifying a search filter and search controls
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; /**
* Demonstrates how to perform a search by specifying a search filter and search * controls. Functionally identical to Search.java. * * usage: java SearchWithFilter */
class SearchWithFilter {
public static void main(String[] args) { // Set up the environment for creating the initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Specify the ids of the attributes to return String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); // Specify the search filter to match // Ask for objects with attribute sn == Geisel and which have // the "mail" attribute. String filter = "(&(sn=Geisel)(mail=*))"; // Search for objects using filter NamingEnumeration answer = ctx.search("ou=People", filter, ctls); // Print the answer // Search.printSearchEnumeration(answer); // Close the context when we"re done ctx.close(); } catch (Exception e) { e.printStackTrace(); } }
}
</source>
how to perform a search by specifying a search filter and search controls to search an object
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; /**
* Demonstrates how to perform a search by specifying a search filter and search * controls to search an object. * * usage: java SearchObject */
class SearchObject {
public static void main(String[] args) { // Set up the environment for creating the initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Specify the ids of the attributes to return String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); ctls.setSearchScope(SearchControls.OBJECT_SCOPE); // Specify the search filter to match // Ask for objects with attribute sn == Geisel and which have // the "mail" attribute. String filter = "(&(sn=Geisel)(mail=*))"; // Search subtree for objects using filter NamingEnumeration answer = ctx.search("cn=Ted Geisel, ou=People", filter, ctls); // Print the answer // Search.printSearchEnumeration(answer); // Close the context when we"re done ctx.close(); } catch (Exception e) { e.printStackTrace(); } }
}
</source>
how to perform a search by specifying a search filter and search controls to search a subtree
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; /**
* Demonstrates how to perform a search by specifying a search filter and search * controls to search a subtree. * * usage: java SearchSubtree */
class SearchSubtree {
public static void main(String[] args) { // Set up the environment for creating the initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Specify the ids of the attributes to return String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Specify the search filter to match // Ask for objects with attribute sn == Geisel and which have // the "mail" attribute. String filter = "(&(sn=Geisel)(mail=*))"; // Search subtree for objects using filter NamingEnumeration answer = ctx.search("", filter, ctls); // Print the answer // Search.printSearchEnumeration(answer); // Close the context when we"re done ctx.close(); } catch (Exception e) { e.printStackTrace(); } }
}
</source>
how to perform a search by specifying a search filter, objects to fill in filter, andsearch controls
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; /**
* Demonstrates how to perform a search by specifying a search filter, objects * to fill in filter, andsearch controls. Functionally identical to Search.java. * * usage: java SearchWithFilterObjs */
class SearchWithFilterObjs {
public static void main(String[] args) { // Set up the environment for creating the initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create initial context DirContext ctx = new InitialDirContext(env); // Specify the ids of the attributes to return String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); // Specify the search filter to match // Ask for objects with attribute sn == Geisel and which have // the "mail" attribute. String filter = "(&(sn={0})(mail=*))"; // Search for objects using filter NamingEnumeration answer = ctx.search("ou=People", filter, new Object[] { "Geisel" }, ctls); // Print the answer // Search.printSearchEnumeration(answer); // Close the context when we"re done ctx.close(); } catch (Exception e) { e.printStackTrace(); } }
}
</source>
how to search the directory that ignores referrals returned by the server
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; /**
* Demonstrates how to search the directory that ignores referrals returned by * the server. */
class ManageReferral {
public static void main(String[] args) { // Set up environment for creating initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env .put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:489/o=JNDITutorial"); // env.put(Context.REFERRAL, "follow"); env.put(Context.REFERRAL, "ignore"); try { // Create initial context LdapContext ctx = (LdapContext) new InitialLdapContext(env, null); // ctx.setRequestControls(new Control[] { // new ManageReferralControl() }); // 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()); } // Close the context when we"re done ctx.close(); } catch (NamingException e) { e.printStackTrace(); } }
}
</source>
LDAP Search
<source lang="java">
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; public class LdapSearch {
public static void main(String[] args) throws Exception { Hashtable env = new Hashtable(); String sp = "com.sun.jndi.ldap.LdapCtxFactory"; env.put(Context.INITIAL_CONTEXT_FACTORY, sp); String ldapUrl = "ldap://localhost:389/dc=yourName, dc=com"; env.put(Context.PROVIDER_URL, ldapUrl); DirContext dctx = new InitialDirContext(env); String base = "ou=People"; SearchControls sc = new SearchControls(); String[] attributeFilter = { "cn", "mail" }; sc.setReturningAttributes(attributeFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "(&(sn=W*)(l=Criteria*))"; NamingEnumeration results = dctx.search(base, filter, sc); while (results.hasMore()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); Attribute attr = attrs.get("cn"); System.out.print(attr.get() + ": "); attr = attrs.get("mail"); System.out.println(attr.get()); } dctx.close(); }
}
</source>