Search in sources :

Example 31 with SearchResult

use of com.unboundid.ldap.sdk.SearchResult in project zm-mailbox by Zimbra.

the class UBIDLdapContext method searchPaged.

@Override
public void searchPaged(SearchLdapOptions searchOptions) throws ServiceException {
    int maxResults = searchOptions.getMaxResults();
    String base = searchOptions.getSearchBase();
    ZLdapFilter filter = searchOptions.getFilter();
    Set<String> binaryAttrs = searchOptions.getBinaryAttrs();
    SearchScope searchScope = ((UBIDSearchScope) searchOptions.getSearchScope()).getNative();
    SearchLdapOptions.SearchLdapVisitor visitor = searchOptions.getVisitor();
    SearchGalResult searchGalResult = searchOptions.getSearchGalResult();
    int pageSize = searchOptions.getResultPageSize();
    int offset = 0;
    boolean pagination = false;
    int limit = 0;
    String prevLastReturnedItemCreateDate = null;
    if (searchGalResult != null) {
        offset = searchGalResult.getLdapMatchCount();
        prevLastReturnedItemCreateDate = searchGalResult.getLdapTimeStamp();
        pagination = searchGalResult.getHadMore();
        limit = searchGalResult.getLimit();
    }
    if (GalOp.sync == searchOptions.getGalOp() && !pagination) {
        limit = 0;
    }
    if (limit == 0) {
        limit = Integer.MAX_VALUE;
    }
    int pageCount = 0;
    int pageOffset = 0;
    int currentPage = 0;
    int index = 0;
    if (offset > 0) {
        pageCount = offset / pageSize;
        pageOffset = offset % pageSize;
    }
    String newToken = "";
    // TODO: this is the legacy behavior, we can make it a param
    boolean wantPartialResult = true;
    try {
        SearchRequest searchRequest = new SearchRequest(base, searchScope, derefAliasPolicy, maxResults, 0, false, ((UBIDLdapFilter) filter).getNative());
        searchRequest.setAttributes(searchOptions.getReturnAttrs());
        //Set the page size and initialize the cookie that we pass back in subsequent pages
        ASN1OctetString cookie = null;
        int count = offset;
        do {
            List<Control> controls = Lists.newArrayListWithCapacity(2);
            if (searchOptions.isUseControl()) {
                controls.add(new SimplePagedResultsControl(pageSize, cookie));
            }
            if (searchOptions.isManageDSAit()) {
                controls.add(new ManageDsaITRequestControl(false));
            }
            searchRequest.setControls(controls.toArray(new Control[0]));
            SearchResult result = null;
            try {
                result = UBIDLdapOperation.SEARCH.execute(this, searchRequest, filter);
            } catch (LDAPException e) {
                if (ResultCode.SIZE_LIMIT_EXCEEDED == e.getResultCode() && wantPartialResult) {
                    // if callsite wants partial result, return them
                    LDAPResult ldapResult = e.toLDAPResult();
                    if (ldapResult instanceof SearchResult) {
                        SearchResult searchResult = (SearchResult) ldapResult;
                        for (SearchResultEntry entry : searchResult.getSearchEntries()) {
                            String dn = entry.getDN();
                            UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
                            if (visitor.wantAttrMapOnVisit()) {
                                visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
                            } else {
                                visitor.visit(dn, ubidAttrs);
                            }
                            newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
                        }
                        if (searchGalResult != null) {
                            searchGalResult.setLdapTimeStamp(newToken);
                            searchGalResult.setLdapMatchCount(1);
                            searchGalResult.setHadMore(true);
                        }
                    }
                }
                // always re-throw
                throw e;
            }
            List<SearchResultEntry> entries = result.getSearchEntries();
            boolean hasMore = false;
            int resultSize = entries.size();
            if (resultSize > (limit + pageOffset)) {
                hasMore = true;
            }
            String leCreateDate = null;
            if (currentPage >= pageCount) {
                leCreateDate = getLastEntryCreationDate(limit + pageOffset, entries);
                if (prevLastReturnedItemCreateDate != null && !prevLastReturnedItemCreateDate.equals(leCreateDate)) {
                    count = 0;
                }
                for (index = pageOffset; index < entries.size() && limit > 0; index++) {
                    SearchResultEntry entry = entries.get(index);
                    String dn = entry.getDN();
                    UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
                    if (visitor.wantAttrMapOnVisit()) {
                        visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
                    } else {
                        visitor.visit(dn, ubidAttrs);
                    }
                    limit--;
                    newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
                    if (newToken != null && newToken.equals(leCreateDate)) {
                        count++;
                    }
                }
                prevLastReturnedItemCreateDate = leCreateDate;
                pageOffset = 0;
            }
            cookie = null;
            for (Control c : result.getResponseControls()) {
                if (c instanceof SimplePagedResultsControl) {
                    cookie = ((SimplePagedResultsControl) c).getCookie();
                }
            }
            if (searchGalResult != null && (GalOp.sync == searchOptions.getGalOp())) {
                if (limit == 0 && (((cookie != null) && (cookie.getValueLength() > 0)) || hasMore)) {
                    searchGalResult.setHadMore(true);
                    searchGalResult.setLdapTimeStamp(newToken);
                    searchGalResult.setLdapMatchCount(count);
                } else if (((cookie != null) && (cookie.getValueLength() == 0))) {
                    searchGalResult.setHadMore(false);
                    searchGalResult.setLdapMatchCount(0);
                }
            }
            currentPage++;
        } while ((cookie != null) && (cookie.getValueLength() > 0) && limit > 0);
    } catch (SearchLdapOptions.StopIteratingException e) {
    // break out of the loop and close the ne
    } catch (LDAPException e) {
        throw mapToLdapException("unable to search ldap", e);
    }
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) SearchRequest(com.unboundid.ldap.sdk.SearchRequest) LDAPResult(com.unboundid.ldap.sdk.LDAPResult) SearchResult(com.unboundid.ldap.sdk.SearchResult) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) SearchGalResult(com.zimbra.cs.account.Provisioning.SearchGalResult) SearchLdapOptions(com.zimbra.cs.ldap.SearchLdapOptions) ZLdapFilter(com.zimbra.cs.ldap.ZLdapFilter) Control(com.unboundid.ldap.sdk.Control) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) AssertionRequestControl(com.unboundid.ldap.sdk.controls.AssertionRequestControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) LDAPException(com.unboundid.ldap.sdk.LDAPException) SearchScope(com.unboundid.ldap.sdk.SearchScope) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

Example 32 with SearchResult

use of com.unboundid.ldap.sdk.SearchResult in project cas by apereo.

the class BaseLdapConsentRepositoryTests method verifyConsentDecisionIsStored.

@Test
public void verifyConsentDecisionIsStored() throws Exception {
    final ConsentDecision decision = BUILDER.build(SVC, REG_SVC, USER_CN, ATTR);
    assertTrue(this.repository.storeConsentDecision(decision));
    final SearchResult r = getConnection().search(USER_DN, SearchScope.SUB, DEF_FILTER, ATTR_NAME);
    assertTrue(r.getEntryCount() > 0);
    final ConsentDecision d = MAPPER.readValue(r.getSearchEntry(USER_DN).getAttributeValue(ATTR_NAME), ConsentDecision.class);
    assertNotNull(d);
    assertEquals(USER_CN, d.getPrincipal());
}
Also used : SearchResult(com.unboundid.ldap.sdk.SearchResult) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 33 with SearchResult

use of com.unboundid.ldap.sdk.SearchResult in project cas by apereo.

the class BaseLdapConsentRepositoryTests method verifyConsentDecisionIsUpdated.

@Test
public void verifyConsentDecisionIsUpdated() throws Exception {
    final ConsentDecision decision = BUILDER.build(SVC, REG_SVC, USER_CN, ATTR);
    decision.setId(1);
    final Modification mod = new Modification(ModificationType.ADD, ATTR_NAME, MAPPER.writeValueAsString(decision));
    assertEquals(ResultCode.SUCCESS, getConnection().modify(USER_DN, mod).getResultCode());
    final LocalDateTime t = LocalDateTime.now();
    assertNotEquals(t, decision.getCreatedDate());
    decision.setCreatedDate(t);
    this.repository.storeConsentDecision(decision);
    final SearchResult r2 = getConnection().search(USER_DN, SearchScope.SUB, DEF_FILTER, ATTR_NAME);
    assertTrue(r2.getEntryCount() > 0);
    final ConsentDecision d = MAPPER.readValue(r2.getSearchEntry(USER_DN).getAttributeValue(ATTR_NAME), ConsentDecision.class);
    assertNotNull(d);
    assertEquals(d.getId(), decision.getId());
    assertEquals(d.getCreatedDate(), t);
}
Also used : LocalDateTime(java.time.LocalDateTime) Modification(com.unboundid.ldap.sdk.Modification) SearchResult(com.unboundid.ldap.sdk.SearchResult) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 34 with SearchResult

use of com.unboundid.ldap.sdk.SearchResult in project oxCore by GluuFederation.

the class LdapEntryManager method findEntriesVirtualListView.

@Deprecated
public <T> List<T> findEntriesVirtualListView(String baseDN, Class<T> entryClass, Filter filter, int startIndex, int count, String sortBy, SortOrder sortOrder, ListViewResponse vlvResponse, String[] ldapReturnAttributes) {
    if (StringHelper.isEmptyString(baseDN)) {
        throw new MappingException("Base DN to find entries is null");
    }
    // Check entry class
    checkEntryClass(entryClass, false);
    String[] objectClasses = getTypeObjectClasses(entryClass);
    List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
    String[] currentLdapReturnAttributes = ldapReturnAttributes;
    if (ArrayHelper.isEmpty(currentLdapReturnAttributes)) {
        currentLdapReturnAttributes = getLdapAttributes(null, propertiesAnnotations, false);
    }
    // Find entries
    Filter searchFilter;
    if (objectClasses.length > 0) {
        searchFilter = addObjectClassFilter(filter, objectClasses);
    } else {
        searchFilter = filter;
    }
    SearchResult searchResult = null;
    try {
        searchResult = this.ldapOperationService.searchVirtualListView(baseDN, toLdapFilter(searchFilter), toLdapSearchScope(SearchScope.SUB), startIndex, count, sortBy, sortOrder, vlvResponse, currentLdapReturnAttributes);
        if (!ResultCode.SUCCESS.equals(searchResult.getResultCode())) {
            throw new EntryPersistenceException(String.format("Failed to find entries with baseDN: %s, filter: %s", baseDN, searchFilter));
        }
    } catch (Exception ex) {
        throw new EntryPersistenceException(String.format("Failed to find entries with baseDN: %s, filter: %s", baseDN, searchFilter), ex);
    }
    if (searchResult.getEntryCount() == 0) {
        return new ArrayList<T>(0);
    }
    List<T> entries = createEntitiesVirtualListView(entryClass, propertiesAnnotations, searchResult.getSearchEntries().toArray(new SearchResultEntry[searchResult.getSearchEntries().size()]));
    return entries;
}
Also used : ArrayList(java.util.ArrayList) EntryPersistenceException(org.gluu.persist.exception.mapping.EntryPersistenceException) SearchResult(com.unboundid.ldap.sdk.SearchResult) SearchException(org.gluu.persist.exception.operation.SearchException) AuthenticationException(org.gluu.persist.exception.operation.AuthenticationException) MappingException(org.gluu.persist.exception.mapping.MappingException) SearchScopeException(org.gluu.persist.exception.operation.SearchScopeException) ParseException(java.text.ParseException) EntryPersistenceException(org.gluu.persist.exception.mapping.EntryPersistenceException) ConnectionException(org.gluu.persist.exception.operation.ConnectionException) MappingException(org.gluu.persist.exception.mapping.MappingException) PropertyAnnotation(org.gluu.persist.model.PropertyAnnotation) Filter(org.gluu.search.filter.Filter) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

Example 35 with SearchResult

use of com.unboundid.ldap.sdk.SearchResult in project oxCore by GluuFederation.

the class LdifDataUtility method checkIfSerrverHasEntryFromLDIFFile.

/**
 * Check if DS has at least one DN simular to specified in ldif file.
 *
 * @param connection
 *            Connection to LDAP server
 * @param ldifFileName
 *            LDIF file
 * @return true if server contains at least one DN simular to specified in ldif
 *         file.
 */
public boolean checkIfSerrverHasEntryFromLDIFFile(LDAPConnection connection, String ldifFileName) {
    // Set up the LDIF reader that will be used to read the changes to apply
    LDIFReader ldifReader = createLdifReader(ldifFileName);
    if (ldifReader == null) {
        return true;
    }
    // Check all ldif entries
    while (true) {
        // Read the next change to process.
        Entry entry = null;
        try {
            entry = ldifReader.readEntry();
        } catch (LDIFException le) {
            LOG.error("Malformed ldif record", le);
            if (!le.mayContinueReading()) {
                return true;
            }
        } catch (IOException ioe) {
            LOG.error("I/O error encountered while reading a change record", ioe);
            return true;
        }
        // changes to be processed.
        if (entry == null) {
            break;
        }
        // Search entry in the server.
        try {
            SearchResult sr = connection.search(entry.getDN(), SearchScope.BASE, "objectClass=*");
            if ((sr != null) && (sr.getEntryCount() > 0)) {
                return true;
            }
        } catch (LDAPException le) {
            if (le.getResultCode() != ResultCode.NO_SUCH_OBJECT) {
                LOG.error("Failed to search ldif record", le);
                return true;
            }
        }
    }
    disposeLdifReader(ldifReader);
    return false;
}
Also used : Entry(com.unboundid.ldap.sdk.Entry) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry) LDAPException(com.unboundid.ldap.sdk.LDAPException) LDIFReader(com.unboundid.ldif.LDIFReader) LDIFException(com.unboundid.ldif.LDIFException) SearchResult(com.unboundid.ldap.sdk.SearchResult) IOException(java.io.IOException)

Aggregations

SearchResult (com.unboundid.ldap.sdk.SearchResult)39 SearchResultEntry (com.unboundid.ldap.sdk.SearchResultEntry)24 LDAPException (com.unboundid.ldap.sdk.LDAPException)16 SearchRequest (com.unboundid.ldap.sdk.SearchRequest)14 SearchException (org.gluu.persist.exception.operation.SearchException)10 ArrayList (java.util.ArrayList)9 MappingException (org.gluu.persist.exception.mapping.MappingException)9 ConnectionException (org.gluu.persist.exception.operation.ConnectionException)8 Test (org.junit.Test)7 LdapConnection (com.gitblit.ldap.LdapConnection)6 EntryPersistenceException (org.gluu.persist.exception.mapping.EntryPersistenceException)6 BindResult (com.unboundid.ldap.sdk.BindResult)5 LDAPSearchException (com.unboundid.ldap.sdk.LDAPSearchException)5 TeamModel (com.gitblit.models.TeamModel)4 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)4 LDAPConnection (com.unboundid.ldap.sdk.LDAPConnection)4 SimplePagedResultsControl (com.unboundid.ldap.sdk.controls.SimplePagedResultsControl)4 ParseException (java.text.ParseException)4 AuthenticationException (org.gluu.persist.exception.operation.AuthenticationException)4 SearchScopeException (org.gluu.persist.exception.operation.SearchScopeException)4