Search in sources :

Example 16 with PartialResultException

use of javax.naming.PartialResultException in project iaf by ibissource.

the class LdapClient method mapMultipleAttributes.

/**
 * runs a set of attribute values through a Mapper. Only the first value of each attribute is mapped.
 */
public void mapMultipleAttributes(NamingEnumeration<SearchResult> searchResultEnum, Callback<Attribute, Object> callback) throws NamingException {
    try {
        while (searchResultEnum.hasMore()) {
            Attributes attributes = searchResultEnum.next().getAttributes();
            NamingEnumeration<? extends Attribute> attrenum = attributes.getAll();
            try {
                while (attrenum.hasMore()) {
                    Attribute attr = attrenum.next();
                    NamingEnumeration<?> multivalueattribute = attr.getAll();
                    try {
                        if (multivalueattribute.hasMore()) {
                            callback.handle(attr, multivalueattribute.next());
                        }
                    } finally {
                        multivalueattribute.close();
                    }
                }
            } finally {
                attrenum.close();
            }
        }
    } catch (PartialResultException e) {
        if (log.isDebugEnabled())
            log.debug("ignoring Exception: " + e);
    } finally {
        searchResultEnum.close();
    }
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) PartialResultException(javax.naming.PartialResultException)

Example 17 with PartialResultException

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

the class SpringSecurityLdapTemplate method searchForSingleEntryInternal.

/**
 * Internal method extracted to avoid code duplication in AD search.
 */
public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls, String base, String filter, Object[] params) throws NamingException {
    final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace());
    final DistinguishedName searchBaseDn = new DistinguishedName(base);
    final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, buildControls(searchControls));
    logger.trace(LogMessage.format("Searching for entry under DN '%s', base = '%s', filter = '%s'", ctxBaseDn, searchBaseDn, filter));
    Set<DirContextOperations> results = new HashSet<>();
    try {
        while (resultsEnum.hasMore()) {
            SearchResult searchResult = resultsEnum.next();
            DirContextAdapter dca = (DirContextAdapter) searchResult.getObject();
            Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured");
            logger.debug(LogMessage.format("Found DN: %s", dca.getDn()));
            results.add(dca);
        }
    } catch (PartialResultException ex) {
        LdapUtils.closeEnumeration(resultsEnum);
        logger.trace("Ignoring PartialResultException");
    }
    if (results.size() != 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    }
    return results.iterator().next();
}
Also used : DirContextOperations(org.springframework.ldap.core.DirContextOperations) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) DistinguishedName(org.springframework.ldap.core.DistinguishedName) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) SearchResult(javax.naming.directory.SearchResult) PartialResultException(javax.naming.PartialResultException) HashSet(java.util.HashSet)

Example 18 with PartialResultException

use of javax.naming.PartialResultException in project gerrit by GerritCodeReview.

the class Helper method queryForGroups.

Set<AccountGroup.UUID> queryForGroups(final DirContext ctx, String username, LdapQuery.Result account) throws NamingException {
    final LdapSchema schema = getSchema(ctx);
    final Set<String> groupDNs = new HashSet<>();
    if (!schema.groupMemberQueryList.isEmpty()) {
        final HashMap<String, String> params = new HashMap<>();
        if (account == null) {
            try {
                account = findAccount(schema, ctx, username, false);
            } catch (AccountException e) {
                return Collections.emptySet();
            }
        }
        for (String name : schema.groupMemberQueryList.get(0).getParameters()) {
            params.put(name, account.get(name));
        }
        params.put(LdapRealm.USERNAME, username);
        for (LdapQuery groupMemberQuery : schema.groupMemberQueryList) {
            for (LdapQuery.Result r : groupMemberQuery.query(ctx, params, groupSearchLatencyTimer)) {
                try (Timer0.Context ignored = groupExpansionLatencyTimer.start()) {
                    recursivelyExpandGroups(groupDNs, schema, ctx, r.getDN());
                }
            }
        }
    }
    if (schema.accountMemberField != null) {
        if (account == null || account.getAll(schema.accountMemberField) == null) {
            try {
                account = findAccount(schema, ctx, username, true);
            } catch (AccountException e) {
                return Collections.emptySet();
            }
        }
        final Attribute groupAtt = account.getAll(schema.accountMemberField);
        if (groupAtt != null) {
            final NamingEnumeration<?> groups = groupAtt.getAll();
            try {
                while (groups.hasMore()) {
                    final String nextDN = (String) groups.next();
                    recursivelyExpandGroups(groupDNs, schema, ctx, nextDN);
                }
            } catch (PartialResultException e) {
            // Ignored
            }
        }
    }
    final Set<AccountGroup.UUID> actual = new HashSet<>();
    for (String dn : groupDNs) {
        actual.add(AccountGroup.uuid(LDAP_UUID + dn));
    }
    if (actual.isEmpty()) {
        return Collections.emptySet();
    }
    return ImmutableSet.copyOf(actual);
}
Also used : HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) PartialResultException(javax.naming.PartialResultException) ParameterizedString(com.google.gerrit.common.data.ParameterizedString) AccountException(com.google.gerrit.server.account.AccountException) Timer0(com.google.gerrit.metrics.Timer0) HashSet(java.util.HashSet)

Example 19 with PartialResultException

use of javax.naming.PartialResultException in project gerrit by GerritCodeReview.

the class LdapQuery method query.

List<Result> query(DirContext ctx, Map<String, String> params, Timer0 queryTimer) throws NamingException {
    final SearchControls sc = new SearchControls();
    final NamingEnumeration<SearchResult> res;
    sc.setSearchScope(searchScope.scope());
    sc.setReturningAttributes(returnAttributes);
    try (Timer0.Context ignored = queryTimer.start()) {
        res = ctx.search(base, pattern.getRawPattern(), pattern.bind(params), sc);
    }
    try {
        final List<Result> r = new ArrayList<>();
        try {
            while (res.hasMore()) {
                r.add(new Result(res.next()));
            }
        } catch (PartialResultException e) {
        // Ignored
        }
        return r;
    } finally {
        res.close();
    }
}
Also used : ArrayList(java.util.ArrayList) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) Timer0(com.google.gerrit.metrics.Timer0) PartialResultException(javax.naming.PartialResultException) SearchResult(javax.naming.directory.SearchResult)

Example 20 with PartialResultException

use of javax.naming.PartialResultException in project zeppelin by apache.

the class LdapRealm method rolesFor.

protected Set<String> rolesFor(PrincipalCollection principals, String userNameIn, final LdapContext ldapCtx, final LdapContextFactory ldapContextFactory, Session session) throws NamingException {
    final Set<String> roleNames = new HashSet<>();
    final Set<String> groupNames = new HashSet<>();
    final String userName;
    if (getUserLowerCase()) {
        LOGGER.debug("userLowerCase true");
        userName = userNameIn.toLowerCase();
    } else {
        userName = userNameIn;
    }
    String userDn = getUserDnForSearch(userName);
    // Activate paged results
    int pageSize = getPagingSize();
    LOGGER.debug("Ldap PagingSize: {}", pageSize);
    int numResults = 0;
    try {
        ldapCtx.addToEnvironment(Context.REFERRAL, "ignore");
        ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        // ldapsearch -h localhost -p 33389 -D
        // uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password
        // -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)'
        NamingEnumeration<SearchResult> searchResultEnum = null;
        SearchControls searchControls = getGroupSearchControls();
        try {
            if (groupSearchEnableMatchingRuleInChain) {
                searchResultEnum = ldapCtx.search(getGroupSearchBase(), String.format(MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn), searchControls);
                while (searchResultEnum != null && searchResultEnum.hasMore()) {
                    // searchResults contains all the groups in search scope
                    numResults++;
                    final SearchResult group = searchResultEnum.next();
                    Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
                    String groupName = attribute.get().toString();
                    String roleName = roleNameFor(groupName);
                    if (roleName != null) {
                        roleNames.add(roleName);
                    } else {
                        roleNames.add(groupName);
                    }
                }
            } else {
                // Default group search filter
                String searchFilter = String.format("(objectclass=%1$s)", groupObjectClass);
                // If group search filter is defined in Shiro config, then use it
                if (groupSearchFilter != null) {
                    searchFilter = expandTemplate(groupSearchFilter, userName);
                // searchFilter = String.format("%1$s", groupSearchFilter);
                }
                LOGGER.debug("Group SearchBase|SearchFilter|GroupSearchScope: " + "{}|{}|{}", getGroupSearchBase(), searchFilter, groupSearchScope);
                searchResultEnum = ldapCtx.search(getGroupSearchBase(), searchFilter, searchControls);
                while (searchResultEnum != null && searchResultEnum.hasMore()) {
                    // searchResults contains all the groups in search scope
                    numResults++;
                    final SearchResult group = searchResultEnum.next();
                    addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory);
                }
            }
        } catch (PartialResultException e) {
            LOGGER.debug("Ignoring PartitalResultException");
        } finally {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        }
        // Re-activate paged results
        ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, null, Control.CRITICAL) });
    } catch (SizeLimitExceededException e) {
        LOGGER.info("Only retrieved first {} groups due to SizeLimitExceededException.", numResults);
    } catch (IOException e) {
        LOGGER.error("Unabled to setup paged results");
    }
    // save role names and group names in session so that they can be
    // easily looked up outside of this object
    session.setAttribute(SUBJECT_USER_ROLES, roleNames);
    session.setAttribute(SUBJECT_USER_GROUPS, groupNames);
    if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) {
        ((MutablePrincipalCollection) principals).addAll(groupNames, getName());
    }
    LOGGER.debug("User RoleNames: {}::{}", userName, roleNames);
    return roleNames;
}
Also used : Attribute(javax.naming.directory.Attribute) SearchResult(javax.naming.directory.SearchResult) PartialResultException(javax.naming.PartialResultException) IOException(java.io.IOException) MutablePrincipalCollection(org.apache.shiro.subject.MutablePrincipalCollection) SizeLimitExceededException(javax.naming.SizeLimitExceededException) SearchControls(javax.naming.directory.SearchControls) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Aggregations

PartialResultException (javax.naming.PartialResultException)22 SearchResult (javax.naming.directory.SearchResult)14 Attribute (javax.naming.directory.Attribute)12 SearchControls (javax.naming.directory.SearchControls)12 Attributes (javax.naming.directory.Attributes)9 ArrayList (java.util.ArrayList)7 HashSet (java.util.HashSet)7 HashMap (java.util.HashMap)5 CompositeName (javax.naming.CompositeName)5 Name (javax.naming.Name)5 ParameterizedString (com.google.gerrit.common.data.ParameterizedString)4 IOException (java.io.IOException)4 LinkedHashSet (java.util.LinkedHashSet)4 SizeLimitExceededException (javax.naming.SizeLimitExceededException)4 PagedResultsControl (javax.naming.ldap.PagedResultsControl)4 MutablePrincipalCollection (org.apache.shiro.subject.MutablePrincipalCollection)4 Entry (java.util.Map.Entry)3 NameParser (javax.naming.NameParser)3 NamingException (javax.naming.NamingException)3 ImmutableSet (com.google.common.collect.ImmutableSet)2