Search in sources :

Example 6 with PagedResult

use of io.jans.orm.model.PagedResult in project jans by JanssenProject.

the class LdapEntryManager method findPagedEntries.

@Override
public <T> PagedResult<T> findPagedEntries(String baseDN, Class<T> entryClass, Filter filter, String[] ldapReturnAttributes, String sortBy, SortOrder sortOrder, int start, int count, int chunkSize) {
    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 = getAttributes(null, propertiesAnnotations, false);
    }
    // Find entries
    Filter searchFilter;
    if (objectClasses.length > 0) {
        searchFilter = addObjectClassFilter(filter, objectClasses);
    } else {
        searchFilter = filter;
    }
    List<SearchResultEntry> searchResultEntries;
    PagedResult<T> vlvResponse = new PagedResult<T>();
    try {
        searchResultEntries = getOperationService().searchSearchResultEntryList(baseDN, toLdapFilter(searchFilter), toLdapSearchScope(SearchScope.SUB), start, count, chunkSize, sortBy, sortOrder, vlvResponse, currentLdapReturnAttributes);
    } catch (Exception ex) {
        throw new EntryPersistenceException(String.format("Failed to find entries with baseDN: %s, filter: %s", baseDN, searchFilter), ex);
    }
    List<T> entries = new ArrayList<T>(0);
    if (searchResultEntries.size() > 0) {
        entries = createEntitiesVirtualListView(entryClass, propertiesAnnotations, searchResultEntries.toArray(new SearchResultEntry[] {}));
    }
    vlvResponse.setEntries(entries);
    return vlvResponse;
}
Also used : ArrayList(java.util.ArrayList) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) MappingException(io.jans.orm.exception.MappingException) ParseException(java.text.ParseException) EntryDeleteException(io.jans.orm.exception.EntryDeleteException) SearchScopeException(io.jans.orm.exception.operation.SearchScopeException) EntryPersistenceException(io.jans.orm.exception.EntryPersistenceException) ConnectionException(io.jans.orm.exception.operation.ConnectionException) SearchException(io.jans.orm.exception.operation.SearchException) AuthenticationException(io.jans.orm.exception.AuthenticationException) MappingException(io.jans.orm.exception.MappingException) PropertyAnnotation(io.jans.orm.reflect.property.PropertyAnnotation) Filter(io.jans.orm.search.filter.Filter) PagedResult(io.jans.orm.model.PagedResult) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

Example 7 with PagedResult

use of io.jans.orm.model.PagedResult in project jans by JanssenProject.

the class CouchbaseOperationServiceImpl method searchImpl.

private <O> PagedResult<JsonObject> searchImpl(BucketMapping bucketMapping, String key, ScanConsistency scanConsistency, Expression expression, SearchScope scope, String[] attributes, Sort[] orderBy, CouchbaseBatchOperationWraper<O> batchOperationWraper, SearchReturnDataType returnDataType, int start, int count, int pageSize) throws SearchException {
    Bucket bucket = bucketMapping.getBucket();
    BatchOperation<O> batchOperation = null;
    if (batchOperationWraper != null) {
        batchOperation = (BatchOperation<O>) batchOperationWraper.getBatchOperation();
    }
    if (LOG.isTraceEnabled()) {
        // Find whole DB search
        if (StringHelper.equalsIgnoreCase(key, "_")) {
            LOG.trace("Search in whole DB tree", new Exception());
        }
    }
    Expression finalExpression = expression;
    if (enableScopeSupport) {
        Expression scopeExpression;
        if (scope == null) {
            scopeExpression = null;
        } else if (SearchScope.BASE == scope) {
            scopeExpression = Expression.path("META().id").like(Expression.s(key + "%")).and(Expression.path("META().id").notLike(Expression.s(key + "\\\\_%\\\\_")));
        } else {
            scopeExpression = Expression.path("META().id").like(Expression.s(key + "%"));
        }
        if (scopeExpression != null) {
            finalExpression = scopeExpression.and(expression);
        }
    } else {
        if (scope != null) {
            LOG.debug("Ignoring scope '" + scope + " for expression: " + expression);
        }
    }
    String[] select = attributes;
    if (select == null) {
        select = new String[] { "jans_doc.*", CouchbaseOperationService.DN };
    } else if ((select.length == 1) && StringHelper.isEmpty(select[0])) {
        // Compatibility with base persistence layer when application pass filter new String[] { "" }
        select = new String[] { CouchbaseOperationService.DN };
    } else {
        boolean hasDn = Arrays.asList(select).contains(CouchbaseOperationService.DN);
        if (!hasDn) {
            select = ArrayHelper.arrayMerge(select, new String[] { CouchbaseOperationService.DN });
        }
    }
    GroupByPath selectQuery = Select.select(select).from(Expression.i(bucketMapping.getBucketName())).as("jans_doc").where(finalExpression);
    LimitPath baseQuery = selectQuery;
    if (orderBy != null) {
        baseQuery = selectQuery.orderBy(orderBy);
    }
    List<N1qlQueryRow> searchResultList = new ArrayList<N1qlQueryRow>();
    if ((SearchReturnDataType.SEARCH == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) {
        N1qlQueryResult lastResult = null;
        if (pageSize > 0) {
            boolean collectSearchResult;
            Statement query = null;
            int currentLimit;
            try {
                List<N1qlQueryRow> lastSearchResultList;
                int resultCount = 0;
                do {
                    collectSearchResult = true;
                    currentLimit = pageSize;
                    if (count > 0) {
                        currentLimit = Math.min(pageSize, count - resultCount);
                    }
                    query = baseQuery.limit(currentLimit).offset(start + resultCount);
                    LOG.debug("Execution query: '" + query + "'");
                    lastResult = bucket.query(N1qlQuery.simple(query, N1qlParams.build().consistency(scanConsistency)));
                    if (!lastResult.finalSuccess()) {
                        throw new SearchException(String.format("Failed to search entries. Query: '%s'. Error: '%s', Error count: '%d'", query, lastResult.errors(), lastResult.info().errorCount()), lastResult.errors().get(0).getInt("code"));
                    }
                    lastSearchResultList = lastResult.allRows();
                    if (batchOperation != null) {
                        collectSearchResult = batchOperation.collectSearchResult(lastSearchResultList.size());
                    }
                    if (collectSearchResult) {
                        searchResultList.addAll(lastSearchResultList);
                    }
                    if (batchOperation != null) {
                        List<O> entries = batchOperationWraper.createEntities(lastSearchResultList);
                        batchOperation.performAction(entries);
                    }
                    resultCount += lastSearchResultList.size();
                    if ((count > 0) && (resultCount >= count)) {
                        break;
                    }
                } while (lastSearchResultList.size() > 0);
            } catch (CouchbaseException ex) {
                throw new SearchException("Failed to search entries. Query: '" + query + "'", ex);
            }
        } else {
            try {
                Statement query = baseQuery;
                if (count > 0) {
                    query = ((LimitPath) query).limit(count);
                }
                if (start > 0) {
                    query = ((OffsetPath) query).offset(start);
                }
                LOG.debug("Execution query: '" + query + "'");
                lastResult = bucket.query(N1qlQuery.simple(query, N1qlParams.build().consistency(scanConsistency)));
                if (!lastResult.finalSuccess()) {
                    throw new SearchException(String.format("Failed to search entries. Query: '%s'. Error: '%s', Error count: '%d'", baseQuery, lastResult.errors(), lastResult.info().errorCount()), lastResult.errors().get(0).getInt("code"));
                }
                searchResultList.addAll(lastResult.allRows());
            } catch (CouchbaseException ex) {
                throw new SearchException("Failed to search entries. Query: '" + baseQuery.toString() + "'", ex);
            }
        }
    }
    List<JsonObject> resultRows = new ArrayList<JsonObject>(searchResultList.size());
    for (N1qlQueryRow row : searchResultList) {
        resultRows.add(row.value());
    }
    PagedResult<JsonObject> result = new PagedResult<JsonObject>();
    result.setEntries(resultRows);
    result.setEntriesCount(resultRows.size());
    result.setStart(start);
    if ((SearchReturnDataType.COUNT == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) {
        GroupByPath selectCountQuery = Select.select("COUNT(*) as TOTAL").from(Expression.i(bucketMapping.getBucketName())).where(finalExpression);
        try {
            LOG.debug("Calculating count. Execution query: '" + selectCountQuery + "'");
            N1qlQueryResult countResult = bucket.query(N1qlQuery.simple(selectCountQuery, N1qlParams.build().consistency(scanConsistency)));
            if (!countResult.finalSuccess() || (countResult.info().resultCount() != 1)) {
                throw new SearchException(String.format("Failed to calculate count entries. Query: '%s'. Error: '%s', Error count: '%d'", selectCountQuery, countResult.errors(), countResult.info().errorCount()), countResult.errors().get(0).getInt("code"));
            }
            result.setTotalEntriesCount(countResult.allRows().get(0).value().getInt("TOTAL"));
        } catch (CouchbaseException ex) {
            throw new SearchException("Failed to calculate count entries. Query: '" + selectCountQuery.toString() + "'", ex);
        }
    }
    return result;
}
Also used : Statement(com.couchbase.client.java.query.Statement) MutateLimitPath(com.couchbase.client.java.query.dsl.path.MutateLimitPath) LimitPath(com.couchbase.client.java.query.dsl.path.LimitPath) ArrayList(java.util.ArrayList) SearchException(io.jans.orm.exception.operation.SearchException) JsonObject(com.couchbase.client.java.document.json.JsonObject) N1qlQueryResult(com.couchbase.client.java.query.N1qlQueryResult) DeleteException(io.jans.orm.exception.operation.DeleteException) PersistenceException(io.jans.orm.exception.operation.PersistenceException) DuplicateEntryException(io.jans.orm.exception.operation.DuplicateEntryException) ConnectionException(io.jans.orm.exception.operation.ConnectionException) SearchException(io.jans.orm.exception.operation.SearchException) CouchbaseException(com.couchbase.client.core.CouchbaseException) AuthenticationException(io.jans.orm.exception.AuthenticationException) EntryNotFoundException(io.jans.orm.exception.operation.EntryNotFoundException) N1qlQueryRow(com.couchbase.client.java.query.N1qlQueryRow) CouchbaseException(com.couchbase.client.core.CouchbaseException) Bucket(com.couchbase.client.java.Bucket) Expression(com.couchbase.client.java.query.dsl.Expression) GroupByPath(com.couchbase.client.java.query.dsl.path.GroupByPath) PagedResult(io.jans.orm.model.PagedResult)

Example 8 with PagedResult

use of io.jans.orm.model.PagedResult in project jans by JanssenProject.

the class Fido2DeviceWebService method searchDevices.

private PagedResult<BaseScimResource> searchDevices(String userId, String filter, String sortBy, SortOrder sortOrder, int startIndex, int count) throws Exception {
    Filter ldapFilter = scimFilterParserService.createFilter(filter, Filter.createPresenceFilter("jansId"), Fido2DeviceResource.class);
    log.info("Executing search for fido devices using: ldapfilter '{}', sortBy '{}', sortOrder '{}', startIndex '{}', count '{}', userId '{}'", ldapFilter.toString(), sortBy, sortOrder.getValue(), startIndex, count, userId);
    // Currently, searching with SUB scope in Couchbase requires some help (beyond use of baseDN)
    if (StringUtils.isNotEmpty(userId)) {
        ldapFilter = Filter.createANDFilter(ldapFilter, Filter.createEqualityFilter("personInum", userId));
    }
    PagedResult<GluuFido2Device> list;
    try {
        list = entryManager.findPagedEntries(fidoDeviceService.getDnForFido2Device(null, userId), GluuFido2Device.class, ldapFilter, null, sortBy, sortOrder, startIndex - 1, count, getMaxCount());
    } catch (Exception e) {
        log.info("Returning an empty listViewReponse");
        log.error(e.getMessage(), e);
        list = new PagedResult<>();
        list.setEntries(new ArrayList<>());
    }
    List<BaseScimResource> resources = new ArrayList<>();
    for (GluuFido2Device device : list.getEntries()) {
        Fido2DeviceResource scimDev = new Fido2DeviceResource();
        transferAttributesToFido2Resource(device, scimDev, endpointUrl, userPersistenceHelper.getUserInumFromDN(device.getDn()));
        resources.add(scimDev);
    }
    log.info("Found {} matching entries - returning {}", list.getTotalEntriesCount(), list.getEntries().size());
    PagedResult<BaseScimResource> result = new PagedResult<>();
    result.setEntries(resources);
    result.setTotalEntriesCount(list.getTotalEntriesCount());
    return result;
}
Also used : Fido2DeviceResource(io.jans.scim.model.scim2.fido.Fido2DeviceResource) Filter(io.jans.orm.search.filter.Filter) ArrayList(java.util.ArrayList) GluuFido2Device(io.jans.scim.model.GluuFido2Device) URISyntaxException(java.net.URISyntaxException) SCIMException(io.jans.scim.model.exception.SCIMException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) PagedResult(io.jans.orm.model.PagedResult)

Aggregations

PagedResult (io.jans.orm.model.PagedResult)8 ArrayList (java.util.ArrayList)6 Filter (io.jans.orm.search.filter.Filter)5 SearchException (io.jans.orm.exception.operation.SearchException)4 BaseScimResource (io.jans.scim.model.scim2.BaseScimResource)3 AuthenticationException (io.jans.orm.exception.AuthenticationException)2 ConnectionException (io.jans.orm.exception.operation.ConnectionException)2 EntryConvertationException (io.jans.orm.exception.operation.EntryConvertationException)2 EntryData (io.jans.orm.model.EntryData)2 SCIMException (io.jans.scim.model.exception.SCIMException)2 URISyntaxException (java.net.URISyntaxException)2 LinkedList (java.util.LinkedList)2 InvalidAttributeValueException (javax.management.InvalidAttributeValueException)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 CouchbaseException (com.couchbase.client.core.CouchbaseException)1 Bucket (com.couchbase.client.java.Bucket)1 JsonObject (com.couchbase.client.java.document.json.JsonObject)1 N1qlQueryResult (com.couchbase.client.java.query.N1qlQueryResult)1 N1qlQueryRow (com.couchbase.client.java.query.N1qlQueryRow)1 Statement (com.couchbase.client.java.query.Statement)1