Search in sources :

Example 1 with SearchCursor

use of org.apache.directory.api.ldap.model.cursor.SearchCursor in project ldapchai by ldapchai.

the class ApacheLdapProviderImpl method searchImpl.

private Map<String, Map<String, List<String>>> searchImpl(final String baseDN, final SearchHelper searchHelper, final boolean multivalued) throws ChaiUnavailableException, ChaiOperationException {
    try {
        final SearchRequest searchRequest = new SearchRequestImpl();
        searchRequest.setBase(new Dn(baseDN));
        searchRequest.setFilter(searchHelper.getFilter());
        searchRequest.setScope(figureSearchScope(searchHelper.getSearchScope()));
        searchRequest.setSizeLimit(searchHelper.getMaxResults());
        searchRequest.setTimeLimit(searchHelper.getTimeLimit());
        final SearchCursor searchCursor = connection.search(searchRequest);
        final Map<String, Map<String, List<String>>> returnObj = new LinkedHashMap<String, Map<String, List<String>>>();
        while (searchCursor.next()) {
            final Entry entry = searchCursor.getEntry();
            final String dnValue = entry.getDn().getName();
            final Map<String, List<String>> entryMap = new HashMap<String, List<String>>();
            for (Attribute returnAttr : entry) {
                final String attrName = returnAttr.getId();
                final List<String> valueList = new ArrayList<String>();
                if (multivalued) {
                    for (Value value : returnAttr) {
                        valueList.add(value.getString());
                    }
                } else {
                    final String value = returnAttr.iterator().next().getString();
                    valueList.add(value);
                }
                entryMap.put(attrName, Collections.unmodifiableList(valueList));
            }
            returnObj.put(dnValue, Collections.unmodifiableMap(entryMap));
        }
        return Collections.unmodifiableMap(returnObj);
    } catch (CursorException e) {
        throw ChaiOperationException.forErrorMessage(e.getMessage());
    } catch (LdapException e) {
        throw ChaiOperationException.forErrorMessage(e.getMessage());
    }
}
Also used : SearchRequest(org.apache.directory.api.ldap.model.message.SearchRequest) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute) Attribute(org.apache.directory.api.ldap.model.entry.Attribute) ArrayList(java.util.ArrayList) SearchRequestImpl(org.apache.directory.api.ldap.model.message.SearchRequestImpl) SearchCursor(org.apache.directory.api.ldap.model.cursor.SearchCursor) Dn(org.apache.directory.api.ldap.model.name.Dn) LinkedHashMap(java.util.LinkedHashMap) DefaultEntry(org.apache.directory.api.ldap.model.entry.DefaultEntry) Entry(org.apache.directory.api.ldap.model.entry.Entry) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) BinaryValue(org.apache.directory.api.ldap.model.entry.BinaryValue) Value(org.apache.directory.api.ldap.model.entry.Value) StringValue(org.apache.directory.api.ldap.model.entry.StringValue) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LdapException(org.apache.directory.api.ldap.model.exception.LdapException)

Example 2 with SearchCursor

use of org.apache.directory.api.ldap.model.cursor.SearchCursor in project jackrabbit-oak by apache.

the class LdapIdentityProvider method getDeclaredGroupRefs.

// -----------------------------------------------------------< internal >---
/**
 * Collects the declared (direct) groups of an identity
 * @param ref reference to the identity
 * @return map of identities where the key is the DN of the LDAP entity
 */
Map<String, ExternalIdentityRef> getDeclaredGroupRefs(ExternalIdentityRef ref) throws ExternalIdentityException {
    if (!isMyRef(ref)) {
        return Collections.emptyMap();
    }
    String searchFilter = config.getMemberOfSearchFilter(ref.getId());
    LdapConnection connection = null;
    SearchCursor searchCursor = null;
    try {
        // Create the SearchRequest object
        SearchRequest req = new SearchRequestImpl();
        req.setScope(SearchScope.SUBTREE);
        String idAttribute = config.getGroupConfig().getIdAttribute();
        req.addAttributes(idAttribute == null ? SchemaConstants.NO_ATTRIBUTE : idAttribute);
        req.setTimeLimit((int) config.getSearchTimeout());
        req.setBase(new Dn(config.getGroupConfig().getBaseDN()));
        req.setFilter(searchFilter);
        if (log.isDebugEnabled()) {
            log.debug("getDeclaredGroupRefs: using SearchRequest {}.", req);
        }
        Map<String, ExternalIdentityRef> groups = new HashMap<String, ExternalIdentityRef>();
        DebugTimer timer = new DebugTimer();
        connection = connect();
        timer.mark("connect");
        searchCursor = connection.search(req);
        timer.mark("search");
        while (searchCursor.next()) {
            Response response = searchCursor.get();
            if (response instanceof SearchResultEntry) {
                Entry resultEntry = ((SearchResultEntry) response).getEntry();
                ExternalIdentityRef groupRef = new ExternalIdentityRef(resultEntry.getDn().toString(), this.getName());
                groups.put(groupRef.getId(), groupRef);
            }
        }
        timer.mark("iterate");
        if (log.isDebugEnabled()) {
            log.debug("getDeclaredGroupRefs: search below {} with {} found {} entries. {}", config.getGroupConfig().getBaseDN(), searchFilter, groups.size(), timer.getString());
        }
        return groups;
    } catch (Exception e) {
        log.error("Error during ldap membership search.", e);
        throw new ExternalIdentityException("Error during ldap membership search.", e);
    } finally {
        if (searchCursor != null) {
            try {
                searchCursor.close();
            } catch (IOException e) {
                log.warn("Failed to close search cursor.", e);
            }
        }
        disconnect(connection);
    }
}
Also used : SearchRequest(org.apache.directory.api.ldap.model.message.SearchRequest) ExternalIdentityRef(org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityRef) HashMap(java.util.HashMap) SearchCursor(org.apache.directory.api.ldap.model.cursor.SearchCursor) SearchRequestImpl(org.apache.directory.api.ldap.model.message.SearchRequestImpl) Dn(org.apache.directory.api.ldap.model.name.Dn) IOException(java.io.IOException) LoginException(javax.security.auth.login.LoginException) LdapInvalidAttributeValueException(org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException) LdapAuthenticationException(org.apache.directory.api.ldap.model.exception.LdapAuthenticationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) ExternalIdentityException(org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) DebugTimer(org.apache.jackrabbit.oak.commons.DebugTimer) Response(org.apache.directory.api.ldap.model.message.Response) Entry(org.apache.directory.api.ldap.model.entry.Entry) SearchResultEntry(org.apache.directory.api.ldap.model.message.SearchResultEntry) ExternalIdentityException(org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityException) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection) SearchResultEntry(org.apache.directory.api.ldap.model.message.SearchResultEntry)

Example 3 with SearchCursor

use of org.apache.directory.api.ldap.model.cursor.SearchCursor in project directory-ldap-api by apache.

the class Dsmlv2Engine method processRequest.

/**
 * Processes a single request
 *
 * @param request the request to process
 * @param respWriter The writer used to store the DSML response
 * @exception Exception If we had an error while processing the request
 */
protected void processRequest(DsmlDecorator<? extends Request> request, BufferedWriter respWriter) throws Exception {
    ResultCodeEnum resultCode = null;
    switch(request.getDecorated().getType()) {
        case ABANDON_REQUEST:
            connection.abandon((AbandonRequest) request);
            return;
        case ADD_REQUEST:
            AddResponse response = connection.add((AddRequest) request);
            resultCode = response.getLdapResult().getResultCode();
            AddResponseDsml addResponseDsml = new AddResponseDsml(connection.getCodecService(), response);
            writeResponse(respWriter, addResponseDsml);
            break;
        case BIND_REQUEST:
            BindResponse bindResponse = connection.bind((BindRequest) request);
            resultCode = bindResponse.getLdapResult().getResultCode();
            BindResponseDsml authResponseDsml = new BindResponseDsml(connection.getCodecService(), bindResponse);
            writeResponse(respWriter, authResponseDsml);
            break;
        case COMPARE_REQUEST:
            CompareResponse compareResponse = connection.compare((CompareRequest) request);
            resultCode = compareResponse.getLdapResult().getResultCode();
            CompareResponseDsml compareResponseDsml = new CompareResponseDsml(connection.getCodecService(), compareResponse);
            writeResponse(respWriter, compareResponseDsml);
            break;
        case DEL_REQUEST:
            DeleteResponse delResponse = connection.delete((DeleteRequest) request);
            resultCode = delResponse.getLdapResult().getResultCode();
            DelResponseDsml delResponseDsml = new DelResponseDsml(connection.getCodecService(), delResponse);
            writeResponse(respWriter, delResponseDsml);
            break;
        case EXTENDED_REQUEST:
            ExtendedResponse extendedResponse = connection.extended((ExtendedRequest) request);
            resultCode = extendedResponse.getLdapResult().getResultCode();
            ExtendedResponseDsml extendedResponseDsml = new ExtendedResponseDsml(connection.getCodecService(), extendedResponse);
            writeResponse(respWriter, extendedResponseDsml);
            break;
        case MODIFY_REQUEST:
            ModifyResponse modifyResponse = connection.modify((ModifyRequest) request);
            resultCode = modifyResponse.getLdapResult().getResultCode();
            ModifyResponseDsml modifyResponseDsml = new ModifyResponseDsml(connection.getCodecService(), modifyResponse);
            writeResponse(respWriter, modifyResponseDsml);
            break;
        case MODIFYDN_REQUEST:
            ModifyDnResponse modifyDnResponse = connection.modifyDn((ModifyDnRequest) request);
            resultCode = modifyDnResponse.getLdapResult().getResultCode();
            ModDNResponseDsml modDNResponseDsml = new ModDNResponseDsml(connection.getCodecService(), modifyDnResponse);
            writeResponse(respWriter, modDNResponseDsml);
            break;
        case SEARCH_REQUEST:
            SearchCursor searchResponses = connection.search((SearchRequest) request);
            SearchResponseDsml searchResponseDsml = new SearchResponseDsml(connection.getCodecService());
            if (respWriter != null) {
                StringBuilder sb = new StringBuilder();
                sb.append("<searchResponse");
                if (request.getDecorated().getMessageId() > 0) {
                    sb.append(" requestID=\"");
                    sb.append(request.getDecorated().getMessageId());
                    sb.append('"');
                }
                sb.append('>');
                respWriter.write(sb.toString());
            }
            while (searchResponses.next()) {
                Response searchResponse = searchResponses.get();
                if (searchResponse.getType() == MessageTypeEnum.SEARCH_RESULT_ENTRY) {
                    SearchResultEntry searchResultEntry = (SearchResultEntry) searchResponse;
                    SearchResultEntryDsml searchResultEntryDsml = new SearchResultEntryDsml(connection.getCodecService(), searchResultEntry);
                    searchResponseDsml = new SearchResponseDsml(connection.getCodecService(), searchResultEntryDsml);
                    if (respWriter != null) {
                        writeResponse(respWriter, searchResultEntryDsml);
                    } else {
                        searchResponseDsml.addResponse(searchResultEntryDsml);
                    }
                } else if (searchResponse.getType() == MessageTypeEnum.SEARCH_RESULT_REFERENCE) {
                    SearchResultReference searchResultReference = (SearchResultReference) searchResponse;
                    SearchResultReferenceDsml searchResultReferenceDsml = new SearchResultReferenceDsml(connection.getCodecService(), searchResultReference);
                    searchResponseDsml = new SearchResponseDsml(connection.getCodecService(), searchResultReferenceDsml);
                    if (respWriter != null) {
                        writeResponse(respWriter, searchResultReferenceDsml);
                    } else {
                        searchResponseDsml.addResponse(searchResultReferenceDsml);
                    }
                }
            }
            SearchResultDone srDone = searchResponses.getSearchResultDone();
            if (srDone != null) {
                resultCode = srDone.getLdapResult().getResultCode();
                SearchResultDoneDsml srdDsml = new SearchResultDoneDsml(connection.getCodecService(), srDone);
                if (respWriter != null) {
                    writeResponse(respWriter, srdDsml);
                    respWriter.write("</searchResponse>");
                } else {
                    searchResponseDsml.addResponse(srdDsml);
                    batchResponse.addResponse(searchResponseDsml);
                }
            }
            break;
        case UNBIND_REQUEST:
            connection.unBind();
            break;
        default:
            throw new IllegalStateException("Unexpected request tpye " + request.getDecorated().getType());
    }
    if ((!continueOnError) && (resultCode != null) && (resultCode != ResultCodeEnum.SUCCESS) && (resultCode != ResultCodeEnum.COMPARE_TRUE) && (resultCode != ResultCodeEnum.COMPARE_FALSE) && (resultCode != ResultCodeEnum.REFERRAL)) {
        // Turning on Exit flag
        exit = true;
    }
}
Also used : DelResponseDsml(org.apache.directory.api.dsmlv2.response.DelResponseDsml) SearchCursor(org.apache.directory.api.ldap.model.cursor.SearchCursor) SearchResultReference(org.apache.directory.api.ldap.model.message.SearchResultReference) BindResponse(org.apache.directory.api.ldap.model.message.BindResponse) SearchResultDoneDsml(org.apache.directory.api.dsmlv2.response.SearchResultDoneDsml) ResultCodeEnum(org.apache.directory.api.ldap.model.message.ResultCodeEnum) ModifyResponseDsml(org.apache.directory.api.dsmlv2.response.ModifyResponseDsml) CompareResponseDsml(org.apache.directory.api.dsmlv2.response.CompareResponseDsml) ModifyDnResponse(org.apache.directory.api.ldap.model.message.ModifyDnResponse) ModifyResponse(org.apache.directory.api.ldap.model.message.ModifyResponse) CompareResponse(org.apache.directory.api.ldap.model.message.CompareResponse) SearchResponseDsml(org.apache.directory.api.dsmlv2.response.SearchResponseDsml) SearchResultEntryDsml(org.apache.directory.api.dsmlv2.response.SearchResultEntryDsml) AddResponseDsml(org.apache.directory.api.dsmlv2.response.AddResponseDsml) SearchResultReferenceDsml(org.apache.directory.api.dsmlv2.response.SearchResultReferenceDsml) SearchResultDone(org.apache.directory.api.ldap.model.message.SearchResultDone) AddResponse(org.apache.directory.api.ldap.model.message.AddResponse) BindResponseDsml(org.apache.directory.api.dsmlv2.response.BindResponseDsml) ErrorResponse(org.apache.directory.api.dsmlv2.response.ErrorResponse) ExtendedResponse(org.apache.directory.api.ldap.model.message.ExtendedResponse) CompareResponse(org.apache.directory.api.ldap.model.message.CompareResponse) AddResponse(org.apache.directory.api.ldap.model.message.AddResponse) DeleteResponse(org.apache.directory.api.ldap.model.message.DeleteResponse) ModifyResponse(org.apache.directory.api.ldap.model.message.ModifyResponse) Response(org.apache.directory.api.ldap.model.message.Response) ModifyDnResponse(org.apache.directory.api.ldap.model.message.ModifyDnResponse) BindResponse(org.apache.directory.api.ldap.model.message.BindResponse) ExtendedResponseDsml(org.apache.directory.api.dsmlv2.response.ExtendedResponseDsml) DeleteResponse(org.apache.directory.api.ldap.model.message.DeleteResponse) ModDNResponseDsml(org.apache.directory.api.dsmlv2.response.ModDNResponseDsml) ExtendedResponse(org.apache.directory.api.ldap.model.message.ExtendedResponse) SearchResultEntry(org.apache.directory.api.ldap.model.message.SearchResultEntry)

Example 4 with SearchCursor

use of org.apache.directory.api.ldap.model.cursor.SearchCursor in project directory-fortress-core by apache.

the class AdminRoleDAO method findAssignedRoles.

/**
 * @param userDn
 * @return
 * @throws FinderException
 */
List<String> findAssignedRoles(String userDn, String contextId) throws FinderException {
    List<String> roleNameList = new ArrayList<>();
    LdapConnection ld = null;
    String roleRoot = getRootDn(contextId, GlobalIds.ADMIN_ROLE_ROOT);
    try {
        String filter = GlobalIds.FILTER_PREFIX + GlobalIds.ROLE_OBJECT_CLASS_NM + ")";
        filter += "(" + ROLE_OCCUPANT + "=" + userDn + "))";
        ld = getAdminConnection();
        SearchCursor searchResults = search(ld, roleRoot, SearchScope.ONELEVEL, filter, ROLE_NM_ATR, false, GlobalIds.BATCH_SIZE);
        while (searchResults.next()) {
            roleNameList.add(getAttribute(searchResults.getEntry(), ROLE_NM));
        }
    } catch (LdapException e) {
        String error = "findAssignedRoles userDn [" + userDn + "] caught LdapException=" + e.getMessage();
        throw new FinderException(GlobalErrIds.ARLE_OCCUPANT_SEARCH_FAILED, error, e);
    } catch (CursorException e) {
        String error = "findAssignedRoles userDn [" + userDn + "] caught CursorException=" + e.getMessage();
        throw new FinderException(GlobalErrIds.ARLE_OCCUPANT_SEARCH_FAILED, error, e);
    } finally {
        closeAdminConnection(ld);
    }
    return roleNameList;
}
Also used : FinderException(org.apache.directory.fortress.core.FinderException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) ArrayList(java.util.ArrayList) SearchCursor(org.apache.directory.api.ldap.model.cursor.SearchCursor) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection)

Example 5 with SearchCursor

use of org.apache.directory.api.ldap.model.cursor.SearchCursor in project directory-fortress-core by apache.

the class AdminRoleDAO method getAllDescendants.

/**
 * @param contextId
 * @return
 * @throws FinderException
 */
List<Graphable> getAllDescendants(String contextId) throws FinderException {
    String[] DESC_ATRS = { ROLE_NM, GlobalIds.PARENT_NODES };
    List<Graphable> descendants = new ArrayList<>();
    LdapConnection ld = null;
    String roleRoot = getRootDn(contextId, GlobalIds.ADMIN_ROLE_ROOT);
    String filter = null;
    try {
        filter = GlobalIds.FILTER_PREFIX + GlobalIds.ROLE_OBJECT_CLASS_NM + ")(" + GlobalIds.PARENT_NODES + "=*))";
        ld = getAdminConnection();
        SearchCursor searchResults = search(ld, roleRoot, SearchScope.ONELEVEL, filter, DESC_ATRS, false, GlobalIds.BATCH_SIZE);
        long sequence = 0;
        while (searchResults.next()) {
            descendants.add(unloadDescendants(searchResults.getEntry(), sequence++));
        }
    } catch (LdapException e) {
        String error = "getAllDescendants filter [" + filter + "] caught LdapException=" + e.getMessage();
        throw new FinderException(GlobalErrIds.ARLE_SEARCH_FAILED, error, e);
    } catch (CursorException e) {
        String error = "getAllDescendants filter [" + filter + "] caught CursorException=" + e.getMessage();
        throw new FinderException(GlobalErrIds.ARLE_SEARCH_FAILED, error, e);
    } finally {
        closeAdminConnection(ld);
    }
    return descendants;
}
Also used : FinderException(org.apache.directory.fortress.core.FinderException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) ArrayList(java.util.ArrayList) SearchCursor(org.apache.directory.api.ldap.model.cursor.SearchCursor) Graphable(org.apache.directory.fortress.core.model.Graphable) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection)

Aggregations

SearchCursor (org.apache.directory.api.ldap.model.cursor.SearchCursor)55 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)52 CursorException (org.apache.directory.api.ldap.model.cursor.CursorException)50 LdapConnection (org.apache.directory.ldap.client.api.LdapConnection)49 FinderException (org.apache.directory.fortress.core.FinderException)48 ArrayList (java.util.ArrayList)44 Entry (org.apache.directory.api.ldap.model.entry.Entry)11 DefaultEntry (org.apache.directory.api.ldap.model.entry.DefaultEntry)7 Permission (org.apache.directory.fortress.core.model.Permission)7 Dn (org.apache.directory.api.ldap.model.name.Dn)5 User (org.apache.directory.fortress.core.model.User)5 IOException (java.io.IOException)4 SearchRequest (org.apache.directory.api.ldap.model.message.SearchRequest)4 SearchRequestImpl (org.apache.directory.api.ldap.model.message.SearchRequestImpl)4 HashSet (java.util.HashSet)3 Response (org.apache.directory.api.ldap.model.message.Response)3 SearchResultEntry (org.apache.directory.api.ldap.model.message.SearchResultEntry)3 AuthZ (org.apache.directory.fortress.core.model.AuthZ)3 SDSet (org.apache.directory.fortress.core.model.SDSet)3 HashMap (java.util.HashMap)2