Search in sources :

Example 6 with SearchResultReferenceIOException

use of org.forgerock.opendj.ldap.SearchResultReferenceIOException in project OpenAM by OpenRock.

the class DJLDAPv3Repo method getDN.

private String getDN(IdType type, String name, boolean shouldGenerate, String searchAttr) throws IdRepoException {
    Object cachedDn = null;
    if (dnCacheEnabled) {
        cachedDn = dnCache.get(generateDNCacheKey(name, type));
    }
    if (cachedDn != null) {
        return cachedDn.toString();
    }
    String dn = null;
    DN searchBase = getBaseDN(type);
    if (shouldGenerate) {
        return searchBase.child(getSearchAttribute(type), name).toString();
    }
    if (searchAttr == null) {
        searchAttr = getSearchAttribute(type);
    }
    Filter filter = Filter.and(Filter.equality(searchAttr, name), getObjectClassFilter(type));
    SearchRequest searchRequest = LDAPRequests.newSearchRequest(searchBase, defaultScope, filter, DN_ATTR);
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        ConnectionEntryReader reader = conn.search(searchRequest);
        SearchResultEntry entry = null;
        while (reader.hasNext()) {
            if (reader.isEntry()) {
                if (entry != null) {
                    throw newIdRepoException(ResultCode.CLIENT_SIDE_UNEXPECTED_RESULTS_RETURNED, IdRepoErrorCode.LDAP_EXCEPTION_OCCURRED, CLASS_NAME, ResultCode.CLIENT_SIDE_UNEXPECTED_RESULTS_RETURNED.intValue());
                }
                entry = reader.readEntry();
            } else {
                //ignore references
                reader.readReference();
            }
        }
        if (entry == null) {
            DEBUG.message("Unable to find entry with name: " + name + " under searchbase: " + searchBase + " with scope: " + defaultScope);
            throw new IdentityNotFoundException(IdRepoBundle.BUNDLE_NAME, IdRepoErrorCode.TYPE_NOT_FOUND, ResultCode.CLIENT_SIDE_NO_RESULTS_RETURNED, new Object[] { name, type.getName() });
        }
        dn = entry.getName().toString();
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while querying entry DN", ere);
        handleErrorResult(ere);
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    if (dnCacheEnabled && !shouldGenerate) {
        dnCache.put(generateDNCacheKey(name, type), dn);
    }
    return dn;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Filter(org.forgerock.opendj.ldap.Filter) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 7 with SearchResultReferenceIOException

use of org.forgerock.opendj.ldap.SearchResultReferenceIOException in project OpenAM by OpenRock.

the class DJLDAPv3Repo method getFilteredRoleMembers.

/**
     * Returns the DNs of the members of this filtered role. To do that this will execute a read on the filtered role
     * entry to get the values of the nsRoleFilter attribute, and then it will perform searches using the retrieved
     * filters.
     *
     * @param dn The DN of the filtered role to query.
     * @return The DNs of the members.
     * @throws IdRepoException If there is an error while trying to retrieve the filtered role members.
     */
private Set<String> getFilteredRoleMembers(String dn) throws IdRepoException {
    Set<String> results = new HashSet<String>();
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        SearchResultEntry entry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(dn, roleFilterAttr));
        Attribute filterAttr = entry.getAttribute(roleFilterAttr);
        if (filterAttr != null) {
            for (ByteString byteString : filterAttr) {
                Filter filter = Filter.valueOf(byteString.toString());
                //TODO: would it make sense to OR these filters and run a single search?
                SearchRequest searchRequest = LDAPRequests.newSearchRequest(rootSuffix, defaultScope, filter.toString(), DN_ATTR);
                searchRequest.setTimeLimit(defaultTimeLimit);
                searchRequest.setSizeLimit(defaultSizeLimit);
                ConnectionEntryReader reader = conn.search(searchRequest);
                while (reader.hasNext()) {
                    if (reader.isEntry()) {
                        results.add(reader.readEntry().getName().toString());
                    } else {
                        //ignore search result references
                        reader.readReference();
                    }
                }
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while trying to retrieve filtered role members for " + dn, ere);
        handleErrorResult(ere);
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return results;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Filter(org.forgerock.opendj.ldap.Filter) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 8 with SearchResultReferenceIOException

use of org.forgerock.opendj.ldap.SearchResultReferenceIOException in project OpenAM by OpenRock.

the class DJLDAPv3Repo method search.

/**
     * Performs a search in the directory based on the provided parameters.
     * Using the pattern and avPairs parameters an example search filter would look something like:
     * <code>(&(|(attr1=value1)(attr2=value2))(searchAttr=pattern)(objectclassfilter))</code>.
     *
     * @param token Not used.
     * @param type The type of the identity.
     * @param crestQuery Either a string, coming from something like the CREST endpoint _queryId or a fully
     *                        fledged query filter, coming from a CREST endpoint's _queryFilter
     * @param maxTime The time limit for this search (in seconds). When maxTime &lt; 1, the default time limit will
     * be used.
     * @param maxResults The number of maximum results we should receive for this search. When maxResults &lt; 1 the
     * default sizelimit will be used.
     * @param returnAttrs The attributes that should be returned from the "search hits".
     * @param returnAllAttrs <code>true</code> if all user attribute should be returned.
     * @param filterOp When avPairs is provided, this logical operation will be used between them. Use
     * {@link IdRepo#AND_MOD} or {@link IdRepo#OR_MOD}.
     * @param avPairs Attribute-value pairs based on the search should be performed.
     * @param recursive Deprecated setting, not used.
     * @return The search results based on the provided parameters.
     * @throws IdRepoException Shouldn't be thrown as the returned RepoSearchResults will contain the error code.
     */
@Override
public RepoSearchResults search(SSOToken token, IdType type, CrestQuery crestQuery, int maxTime, int maxResults, Set<String> returnAttrs, boolean returnAllAttrs, int filterOp, Map<String, Set<String>> avPairs, boolean recursive) throws IdRepoException {
    if (DEBUG.messageEnabled()) {
        DEBUG.message("search invoked with type: " + type + " crestQuery: " + crestQuery + " avPairs: " + avPairs + " maxTime: " + maxTime + " maxResults: " + maxResults + " returnAttrs: " + returnAttrs + " returnAllAttrs: " + returnAllAttrs + " filterOp: " + filterOp + " recursive: " + recursive);
    }
    DN baseDN = getBaseDN(type);
    // Recursive is a deprecated setting on IdSearchControl, hence we should use the searchscope defined in the
    // datastore configuration.
    SearchScope scope = defaultScope;
    String searchAttr = getSearchAttribute(type);
    String[] attrs;
    Filter first;
    if (crestQuery.hasQueryId()) {
        first = Filter.valueOf(searchAttr + "=" + crestQuery.getQueryId());
    } else {
        first = crestQuery.getQueryFilter().accept(new LdapFromJsonQueryFilterVisitor(), null);
    }
    Filter filter = Filter.and(first, getObjectClassFilter(type));
    Filter tempFilter = constructFilter(filterOp, avPairs);
    if (tempFilter != null) {
        filter = Filter.and(tempFilter, filter);
    }
    if (returnAllAttrs || (returnAttrs != null && returnAttrs.contains("*"))) {
        Set<String> predefinedAttrs = getDefinedAttributes(type);
        attrs = predefinedAttrs.toArray(new String[predefinedAttrs.size()]);
        returnAllAttrs = true;
    } else if (returnAttrs != null && !returnAttrs.isEmpty()) {
        returnAttrs.add(searchAttr);
        attrs = returnAttrs.toArray(new String[returnAttrs.size()]);
    } else {
        attrs = new String[] { searchAttr };
    }
    SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, scope, filter, attrs);
    searchRequest.setSizeLimit(maxResults < 1 ? defaultSizeLimit : maxResults);
    searchRequest.setTimeLimit(maxTime < 1 ? defaultTimeLimit : maxTime);
    Connection conn = null;
    Set<String> names = new HashSet<String>();
    Map<String, Map<String, Set<String>>> entries = new HashMap<String, Map<String, Set<String>>>();
    int errorCode = RepoSearchResults.SUCCESS;
    try {
        conn = connectionFactory.getConnection();
        ConnectionEntryReader reader = conn.search(searchRequest);
        while (reader.hasNext()) {
            Map<String, Set<String>> attributes = new HashMap<String, Set<String>>();
            if (reader.isEntry()) {
                SearchResultEntry entry = reader.readEntry();
                String name = entry.parseAttribute(searchAttr).asString();
                names.add(name);
                if (returnAllAttrs) {
                    for (Attribute attribute : entry.getAllAttributes()) {
                        LDAPUtils.addAttributeToMapAsString(attribute, attributes);
                    }
                    entries.put(name, attributes);
                } else if (returnAttrs != null && !returnAttrs.isEmpty()) {
                    for (String attr : returnAttrs) {
                        Attribute attribute = entry.getAttribute(attr);
                        if (attribute != null) {
                            LDAPUtils.addAttributeToMapAsString(attribute, attributes);
                        }
                    }
                    entries.put(name, attributes);
                } else {
                //there is no attribute to return, don't populate the entries map
                }
            } else {
                //ignore search result references
                reader.readReference();
            }
        }
    } catch (LdapException ere) {
        ResultCode resultCode = ere.getResult().getResultCode();
        if (resultCode.equals(ResultCode.NO_SUCH_OBJECT)) {
            return new RepoSearchResults(new HashSet<String>(0), RepoSearchResults.SUCCESS, Collections.EMPTY_MAP, type);
        } else if (resultCode.equals(ResultCode.TIME_LIMIT_EXCEEDED) || resultCode.equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
            errorCode = RepoSearchResults.TIME_LIMIT_EXCEEDED;
        } else if (resultCode.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
            errorCode = RepoSearchResults.SIZE_LIMIT_EXCEEDED;
        } else {
            DEBUG.error("Unexpected error occurred during search", ere);
            errorCode = resultCode.intValue();
        }
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return new RepoSearchResults(names, errorCode, entries, type);
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Set(java.util.Set) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) CollectionUtils.asSet(org.forgerock.openam.utils.CollectionUtils.asSet) LdapFromJsonQueryFilterVisitor(org.forgerock.openam.ldap.LdapFromJsonQueryFilterVisitor) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Filter(org.forgerock.opendj.ldap.Filter) SearchScope(org.forgerock.opendj.ldap.SearchScope) RepoSearchResults(com.sun.identity.idm.RepoSearchResults) Map(java.util.Map) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 9 with SearchResultReferenceIOException

use of org.forgerock.opendj.ldap.SearchResultReferenceIOException in project OpenAM by OpenRock.

the class DJLDAPv3Repo method getGroupMemberships.

/**
     * Returns the group membership informations for this given user. In case the memberOf attribute is configured,
     * this will try to query the user entry and return the group DNs found in the memberOf attribute. Otherwise a
     * search request will be issued using the uniqueMember attribute looking for matches with the user DN.
     *
     * @param dn The DN of the user identity.
     * @return The DNs of the groups that the provided user is member of.
     * @throws IdRepoException If there was an error while retrieving the group membership information.
     */
private Set<String> getGroupMemberships(String dn) throws IdRepoException {
    Set<String> results = new HashSet<String>();
    if (memberOfAttr == null) {
        Filter filter = Filter.and(groupSearchFilter, Filter.equality(uniqueMemberAttr, dn));
        SearchRequest searchRequest = LDAPRequests.newSearchRequest(getBaseDN(IdType.GROUP), defaultScope, filter, DN_ATTR);
        searchRequest.setTimeLimit(defaultTimeLimit);
        searchRequest.setSizeLimit(defaultSizeLimit);
        Connection conn = null;
        try {
            conn = connectionFactory.getConnection();
            ConnectionEntryReader reader = conn.search(searchRequest);
            while (reader.hasNext()) {
                if (reader.isEntry()) {
                    results.add(reader.readEntry().getName().toString());
                } else {
                    //ignore search result references
                    reader.readReference();
                }
            }
        } catch (LdapException ere) {
            DEBUG.error("An error occurred while trying to retrieve group memberships for " + dn + " using " + uniqueMemberAttr, ere);
            handleErrorResult(ere);
        } catch (SearchResultReferenceIOException srrioe) {
            //should never ever happen...
            DEBUG.error("Got reference instead of entry", srrioe);
            throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
        } finally {
            IOUtils.closeIfNotNull(conn);
        }
    } else {
        Connection conn = null;
        try {
            conn = connectionFactory.getConnection();
            SearchResultEntry entry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(dn, memberOfAttr));
            Attribute attr = entry.getAttribute(memberOfAttr);
            if (attr != null) {
                results.addAll(LDAPUtils.getAttributeValuesAsStringSet(attr));
            }
        } catch (LdapException ere) {
            DEBUG.error("An error occurred while trying to retrieve group memberships for " + dn + " using " + memberOfAttr + " attribute", ere);
            handleErrorResult(ere);
        } finally {
            IOUtils.closeIfNotNull(conn);
        }
    }
    return results;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Filter(org.forgerock.opendj.ldap.Filter) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 10 with SearchResultReferenceIOException

use of org.forgerock.opendj.ldap.SearchResultReferenceIOException in project OpenAM by OpenRock.

the class SearchResultIterator method hasNext.

public boolean hasNext() {
    try {
        if (results.hasNext()) {
            if (current == null) {
                if (results.isReference()) {
                    debug.warning("SearchResultIterator: ignoring reference: {}", results.readReference());
                    return hasNext();
                }
                SearchResultEntry entry = results.readEntry();
                String dn = entry.getName().toString();
                if (hasExcludeDNs && excludeDNs.contains(dn)) {
                    return hasNext();
                }
                current = new SMSDataEntry(dn, SMSUtils.convertEntryToAttributesMap(entry));
            }
            return true;
        }
    } catch (LdapException e) {
        ResultCode errorCode = e.getResult().getResultCode();
        if (errorCode.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
            debug.message("SearchResultIterator: size limit exceeded");
        } else {
            debug.error("SearchResultIterator.hasNext", e);
        }
    } catch (SearchResultReferenceIOException e) {
        debug.error("SearchResultIterator.hasNext: reference should be already handled", e);
        return hasNext();
    }
    conn.close();
    return false;
}
Also used : SMSDataEntry(com.sun.identity.sm.SMSDataEntry) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Aggregations

LdapException (org.forgerock.opendj.ldap.LdapException)21 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)21 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)18 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)18 Connection (org.forgerock.opendj.ldap.Connection)16 ByteString (org.forgerock.opendj.ldap.ByteString)14 HashSet (java.util.HashSet)10 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)9 LinkedHashSet (java.util.LinkedHashSet)8 Attribute (org.forgerock.opendj.ldap.Attribute)8 ResultCode (org.forgerock.opendj.ldap.ResultCode)7 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)5 Filter (org.forgerock.opendj.ldap.Filter)5 PolicyException (com.sun.identity.policy.PolicyException)4 DN (org.forgerock.opendj.ldap.DN)4 LinkedAttribute (org.forgerock.opendj.ldap.LinkedAttribute)4 SSOException (com.iplanet.sso.SSOException)2 InvalidNameException (com.sun.identity.policy.InvalidNameException)2 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)2 ValidValues (com.sun.identity.policy.ValidValues)2