Search in sources :

Example 11 with SearchControls

use of javax.naming.directory.SearchControls in project spring-security by spring-projects.

the class SpringSecurityLdapTemplate method searchForMultipleAttributeValues.

/**
	 * Performs a search using the supplied filter and returns the values of each named
	 * attribute found in all entries matched by the search. Note that one directory entry
	 * may have several values for the attribute. Intended for role searches and similar
	 * scenarios.
	 *
	 * @param base the DN to search in
	 * @param filter search filter to use
	 * @param params the parameters to substitute in the search filter
	 * @param attributeNames the attributes' values that are to be retrieved.
	 *
	 * @return the set of String values for each attribute found in all the matching
	 * entries. The attribute name is the key for each set of values. In addition each map
	 * contains the DN as a String with the key predefined key {@link #DN_KEY}.
	 */
public Set<Map<String, List<String>>> searchForMultipleAttributeValues(final String base, final String filter, final Object[] params, final String[] attributeNames) {
    // Escape the params acording to RFC2254
    Object[] encodedParams = new String[params.length];
    for (int i = 0; i < params.length; i++) {
        encodedParams[i] = LdapEncoder.filterEncode(params[i].toString());
    }
    String formattedFilter = MessageFormat.format(filter, encodedParams);
    logger.debug("Using filter: " + formattedFilter);
    final HashSet<Map<String, List<String>>> set = new HashSet<Map<String, List<String>>>();
    ContextMapper roleMapper = new ContextMapper() {

        public Object mapFromContext(Object ctx) {
            DirContextAdapter adapter = (DirContextAdapter) ctx;
            Map<String, List<String>> record = new HashMap<String, List<String>>();
            if (attributeNames == null || attributeNames.length == 0) {
                try {
                    for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae.hasMore(); ) {
                        Attribute attr = (Attribute) ae.next();
                        extractStringAttributeValues(adapter, record, attr.getID());
                    }
                } catch (NamingException x) {
                    org.springframework.ldap.support.LdapUtils.convertLdapException(x);
                }
            } else {
                for (String attributeName : attributeNames) {
                    extractStringAttributeValues(adapter, record, attributeName);
                }
            }
            record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter)));
            set.add(record);
            return null;
        }
    };
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(searchControls.getSearchScope());
    ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null);
    search(base, formattedFilter, ctls, roleMapper);
    return set;
}
Also used : HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) NamingEnumeration(javax.naming.NamingEnumeration) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) ArrayList(java.util.ArrayList) List(java.util.List) NamingException(javax.naming.NamingException) SearchControls(javax.naming.directory.SearchControls) HashMap(java.util.HashMap) Map(java.util.Map) ContextMapper(org.springframework.ldap.core.ContextMapper) HashSet(java.util.HashSet)

Example 12 with SearchControls

use of javax.naming.directory.SearchControls in project spring-security by spring-projects.

the class SpringSecurityLdapTemplate method compare.

// ~ Methods
// ========================================================================================================
/**
	 * Performs an LDAP compare operation of the value of an attribute for a particular
	 * directory entry.
	 *
	 * @param dn the entry who's attribute is to be used
	 * @param attributeName the attribute who's value we want to compare
	 * @param value the value to be checked against the directory value
	 *
	 * @return true if the supplied value matches that in the directory
	 */
public boolean compare(final String dn, final String attributeName, final Object value) {
    final String comparisonFilter = "(" + attributeName + "={0})";
    class LdapCompareCallback implements ContextExecutor {

        public Object executeWithContext(DirContext ctx) throws NamingException {
            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(NO_ATTRS);
            ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
            NamingEnumeration<SearchResult> results = ctx.search(dn, comparisonFilter, new Object[] { value }, ctls);
            Boolean match = Boolean.valueOf(results.hasMore());
            LdapUtils.closeEnumeration(results);
            return match;
        }
    }
    Boolean matches = (Boolean) executeReadOnly(new LdapCompareCallback());
    return matches.booleanValue();
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) DirContext(javax.naming.directory.DirContext) ContextExecutor(org.springframework.ldap.core.ContextExecutor)

Example 13 with SearchControls

use of javax.naming.directory.SearchControls in project spring-security by spring-projects.

the class SpringSecurityLdapTemplateITests method nonSpringLdapSearchCodeTestMethod.

@Test
public void nonSpringLdapSearchCodeTestMethod() throws Exception {
    java.util.Hashtable<String, String> env = new java.util.Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:" + ApacheDSServerIntegrationTests.getServerPort());
    env.put(Context.SECURITY_PRINCIPAL, "");
    env.put(Context.SECURITY_CREDENTIALS, "");
    DirContext ctx = new javax.naming.directory.InitialDirContext(env);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    controls.setReturningObjFlag(true);
    controls.setReturningAttributes(null);
    String param = "cn=mouse\\, jerry,ou=people,dc=springframework,dc=org";
    javax.naming.NamingEnumeration<SearchResult> results = ctx.search("ou=groups,dc=springframework,dc=org", "(member={0})", new String[] { param }, controls);
    assertThat(results.hasMore()).as("Expected a result").isTrue();
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) DirContext(javax.naming.directory.DirContext)

Example 14 with SearchControls

use of javax.naming.directory.SearchControls in project nhin-d by DirectProject.

the class LdapPublicCertUtilImpl method getBaseNamingContexts.

/**
	 * Gets the base DNs for a connected LDAP context
	 * @param ctx The LDAP connection context.
	 * @return List of string representing the base DNs of the LDAP server.
	 */
protected List<String> getBaseNamingContexts(InitialDirContext ctx) {
    List<String> dNs = new ArrayList<String>();
    try {
        SearchControls ctls = new SearchControls();
        ctls.setReturningObjFlag(true);
        ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
        ctls.setReturningAttributes(new String[] { BASE_DN_ATTRIBUTE });
        NamingEnumeration<SearchResult> objResults = ctx.search("", "objectclass=*", ctls);
        while (objResults != null && objResults.hasMore()) {
            final SearchResult objEntry = objResults.nextElement();
            final Attributes objAttributes = objEntry.getAttributes();
            if (objAttributes != null) {
                final Attribute objAttribute = objAttributes.get(BASE_DN_ATTRIBUTE);
                NamingEnumeration<? extends Object> allValues = objAttribute.getAll();
                while (allValues.hasMoreElements()) dNs.add((String) allValues.nextElement());
            }
        }
        if (dNs.isEmpty())
            LOGGER.warn("No base DNs could be located for LDAP context");
    } catch (Exception e) {
        // no naming contexts could be located or query error
        LOGGER.warn("ERROR looking up base DNs for LDAP context", e);
    }
    return dNs;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) UnknownHostException(java.net.UnknownHostException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 15 with SearchControls

use of javax.naming.directory.SearchControls in project nhin-d by DirectProject.

the class LDAPResearchTest method searchDNs.

private Set<SearchResult> searchDNs(String filter, String partition, String base, int scope, DirContext appRoot) throws Exception {
    if (appRoot == null)
        appRoot = createContext(partition);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(scope);
    NamingEnumeration<SearchResult> result = appRoot.search(base, filter, controls);
    // collect all results
    Set<SearchResult> entries = new HashSet<SearchResult>();
    while (result.hasMore()) {
        SearchResult entry = (SearchResult) result.next();
        entries.add(entry);
    }
    return entries;
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) HashSet(java.util.HashSet)

Aggregations

SearchControls (javax.naming.directory.SearchControls)59 SearchResult (javax.naming.directory.SearchResult)46 NamingException (javax.naming.NamingException)27 ArrayList (java.util.ArrayList)23 Attributes (javax.naming.directory.Attributes)20 NamingEnumeration (javax.naming.NamingEnumeration)16 Attribute (javax.naming.directory.Attribute)15 DirContext (javax.naming.directory.DirContext)13 InitialDirContext (javax.naming.directory.InitialDirContext)8 LdapContext (javax.naming.ldap.LdapContext)8 HashMap (java.util.HashMap)5 GroupNotFoundException (org.jivesoftware.openfire.group.GroupNotFoundException)5 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)5 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 LinkedHashSet (java.util.LinkedHashSet)4 Map (java.util.Map)4 PartialResultException (javax.naming.PartialResultException)4 Control (javax.naming.ldap.Control)4 PagedResultsControl (javax.naming.ldap.PagedResultsControl)4