Example usage for org.springframework.data.domain Pageable getOffset

List of usage examples for org.springframework.data.domain Pageable getOffset

Introduction

In this page you can find the example usage for org.springframework.data.domain Pageable getOffset.

Prototype

long getOffset();

Source Link

Document

Returns the offset to be taken according to the underlying page and page size.

Usage

From source file:org.wallride.repository.PageRepositoryImpl.java

private FullTextQuery buildFullTextQuery(PageSearchRequest request, Pageable pageable, Criteria criteria) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Page.class).get();

    @SuppressWarnings("rawtypes")
    BooleanJunction<BooleanJunction> junction = qb.bool();
    junction.must(qb.all().createQuery());

    junction.must(qb.keyword().onField("drafted").ignoreAnalyzer().matching("_null_").createQuery());

    if (StringUtils.hasText(request.getKeyword())) {
        Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
        String[] fields = new String[] { "title", "body", "tags.name", };
        MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
        parser.setDefaultOperator(QueryParser.Operator.AND);
        Query query = null;/*from   www . ja va 2s .  c  om*/
        try {
            query = parser.parse(request.getKeyword());
        } catch (ParseException e1) {
            try {
                query = parser.parse(QueryParser.escape(request.getKeyword()));
            } catch (ParseException e2) {
                throw new RuntimeException(e2);
            }
        }
        junction.must(query);
    }
    if (StringUtils.hasText(request.getLanguage())) {
        junction.must(qb.keyword().onField("language").matching(request.getLanguage()).createQuery());
    }

    if (request.getStatus() != null) {
        junction.must(qb.keyword().onField("status").matching(request.getStatus()).createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getCategoryIds())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (long categoryId : request.getCategoryIds()) {
            subJunction.should(qb.keyword().onField("categories.id").matching(categoryId).createQuery());
        }
        junction.must(subJunction.createQuery());
    }
    if (!CollectionUtils.isEmpty(request.getCategoryCodes())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (String categoryCode : request.getCategoryCodes()) {
            subJunction.should(qb.keyword().onField("categories.code").matching(categoryCode).createQuery());
        }
        junction.must(subJunction.createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getTagIds())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (long tagId : request.getTagIds()) {
            subJunction.should(qb.keyword().onField("tags.id").matching(tagId).createQuery());
        }
        junction.must(subJunction.createQuery());
    }
    if (!CollectionUtils.isEmpty(request.getTagNames())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (String tagName : request.getTagNames()) {
            subJunction.should(qb.phrase().onField("tags.name").sentence(tagName).createQuery());
        }
        junction.must(subJunction.createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getCustomFields())) {
        javax.persistence.Query query = entityManager.createQuery(
                "from CustomField where language = :language and code in (:codes)", CustomField.class);
        query.setParameter("language", request.getLanguage()).setParameter("codes",
                request.getCustomFields().keySet());
        List<CustomField> customFields = query.getResultList();

        if (!CollectionUtils.isEmpty(customFields)) {
            Map<String, CustomField> customFieldMap = customFields.stream()
                    .collect(Collectors.toMap(CustomField::getCode, Function.identity()));

            BooleanJunction<BooleanJunction> subJunction = qb.bool();
            for (String key : request.getCustomFields().keySet()) {
                List<Object> values = (List<Object>) request.getCustomFields().get(key);
                CustomField target = customFieldMap.get(key);
                BooleanJunction<BooleanJunction> customFieldJunction = qb.bool();
                switch (target.getFieldType()) {
                case TEXT:
                case TEXTAREA:
                case HTML:
                    for (Object value : values) {
                        customFieldJunction.must(qb.keyword().onField("customFieldValues." + key)
                                .ignoreFieldBridge().matching(value.toString()).createQuery());
                    }
                    break;
                default:
                    for (Object value : values) {
                        customFieldJunction.must(qb.phrase().onField("customFieldValues." + key)
                                .ignoreFieldBridge().sentence(value.toString()).createQuery());
                    }
                }
                subJunction.must(customFieldJunction.createQuery());
            }
            junction.must(subJunction.createQuery());
        }
    }

    if (request.getAuthorId() != null) {
        junction.must(qb.keyword().onField("author.id").matching(request.getAuthorId()).createQuery());
    }

    Query searchQuery = junction.createQuery();

    Sort sort = new Sort(new SortField("sortLft", SortField.Type.INT));

    FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(searchQuery, Page.class)
            .setCriteriaQuery(criteria).setSort(sort);
    if (pageable != null) {
        persistenceQuery.setFirstResult(pageable.getOffset());
        persistenceQuery.setMaxResults(pageable.getPageSize());
    }
    return persistenceQuery;
}

From source file:org.wallride.repository.ArticleRepositoryImpl.java

private FullTextQuery buildFullTextQuery(ArticleSearchRequest request, Pageable pageable, Criteria criteria) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Article.class)
            .get();// w  ww .ja  v  a2s .  c  o m

    @SuppressWarnings("rawtypes")
    BooleanJunction<BooleanJunction> junction = qb.bool();
    junction.must(qb.all().createQuery());

    junction.must(qb.keyword().onField("drafted").ignoreAnalyzer().matching("_null_").createQuery());

    if (StringUtils.hasText(request.getKeyword())) {
        Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
        String[] fields = new String[] { "title", "body", "categories.name", "tags.name",
                "customFieldValues.value" };
        MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
        parser.setDefaultOperator(QueryParser.Operator.AND);
        Query query = null;
        try {
            query = parser.parse(request.getKeyword());
        } catch (ParseException e1) {
            try {
                query = parser.parse(QueryParser.escape(request.getKeyword()));
            } catch (ParseException e2) {
                throw new RuntimeException(e2);
            }
        }
        junction.must(query);
    }
    if (request.getStatus() != null) {
        junction.must(qb.keyword().onField("status").matching(request.getStatus()).createQuery());
    }
    if (StringUtils.hasText(request.getLanguage())) {
        junction.must(qb.keyword().onField("language").matching(request.getLanguage()).createQuery());
    }

    if (request.getDateFrom() != null) {
        junction.must(qb.range().onField("date").above(request.getDateFrom()).createQuery());
    }
    if (request.getDateTo() != null) {
        junction.must(qb.range().onField("date").below(request.getDateTo()).createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getCategoryIds())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (long categoryId : request.getCategoryIds()) {
            subJunction.should(qb.keyword().onField("categories.id").matching(categoryId).createQuery());
        }
        junction.must(subJunction.createQuery());
    }
    if (!CollectionUtils.isEmpty(request.getCategoryCodes())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (String categoryCode : request.getCategoryCodes()) {
            subJunction.should(qb.keyword().onField("categories.code").matching(categoryCode).createQuery());
        }
        junction.must(subJunction.createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getTagIds())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (long tagId : request.getTagIds()) {
            subJunction.should(qb.keyword().onField("tags.id").matching(tagId).createQuery());
        }
        junction.must(subJunction.createQuery());
    }
    if (!CollectionUtils.isEmpty(request.getTagNames())) {
        BooleanJunction<BooleanJunction> subJunction = qb.bool();
        for (String tagName : request.getTagNames()) {
            subJunction.should(qb.phrase().onField("tags.name").sentence(tagName).createQuery());
        }
        junction.must(subJunction.createQuery());
    }

    if (!CollectionUtils.isEmpty(request.getCustomFields())) {
        javax.persistence.Query query = entityManager.createQuery(
                "from CustomField where language = :language and code in (:codes)", CustomField.class);
        query.setParameter("language", request.getLanguage()).setParameter("codes",
                request.getCustomFields().keySet());
        List<CustomField> customFields = query.getResultList();

        if (!CollectionUtils.isEmpty(customFields)) {
            Map<String, CustomField> customFieldMap = customFields.stream()
                    .collect(Collectors.toMap(CustomField::getCode, Function.identity()));

            BooleanJunction<BooleanJunction> subJunction = qb.bool();
            for (String key : request.getCustomFields().keySet()) {
                List<Object> values = (List<Object>) request.getCustomFields().get(key);
                CustomField target = customFieldMap.get(key);
                BooleanJunction<BooleanJunction> customFieldJunction = qb.bool();
                switch (target.getFieldType()) {
                case TEXT:
                case TEXTAREA:
                case HTML:
                    for (Object value : values) {
                        customFieldJunction.must(qb.keyword().onField("customFieldValues." + key)
                                .ignoreFieldBridge().matching(value.toString()).createQuery());
                    }
                    break;
                default:
                    for (Object value : values) {
                        customFieldJunction.must(qb.phrase().onField("customFieldValues." + key)
                                .ignoreFieldBridge().sentence(value.toString()).createQuery());
                    }
                }
                subJunction.must(customFieldJunction.createQuery());
            }
            junction.must(subJunction.createQuery());
        }
    }

    if (request.getAuthorId() != null) {
        junction.must(qb.keyword().onField("author.id").matching(request.getAuthorId()).createQuery());
    }

    Query searchQuery = junction.createQuery();

    Sort sort = new Sort(new SortField("sortDate", SortField.Type.STRING, true),
            new SortField("sortId", SortField.Type.LONG, true));

    FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(searchQuery, Article.class)
            .setCriteriaQuery(criteria).setSort(sort);
    if (pageable != null) {
        persistenceQuery.setFirstResult(pageable.getOffset());
        persistenceQuery.setMaxResults(pageable.getPageSize());
    }
    return persistenceQuery;
}

From source file:org.dspace.app.rest.model.hateoas.FacetsResource.java

private void embedFacetResults(SearchResultsRest data, Pageable page) {
    int i = 0;/*from   www  .j  a  va  2  s  .c o m*/
    for (SearchFacetEntryRest searchFacetEntryRest : CollectionUtils.emptyIfNull(data.getFacets())) {
        if (i >= page.getOffset() && i < page.getOffset() + page.getPageSize()) {
            facetResources.add(new SearchFacetEntryResource(searchFacetEntryRest, data));
        }
    }

    embedResource("facets", facetResources);
}

From source file:org.dspace.app.rest.repository.BrowseEntryLinkRepository.java

public Page<BrowseEntryRest> listBrowseEntries(HttpServletRequest request, String browseName, Pageable pageable,
        String projection) throws BrowseException, SQLException {
    // FIXME this should be bind automatically and available as method
    // argument/*from   w ww. ja  va2 s .co  m*/
    String scope = null;
    if (request != null) {
        scope = request.getParameter("scope");
    }

    Context context = obtainContext();
    BrowseEngine be = new BrowseEngine(context);
    BrowserScope bs = new BrowserScope(context);
    DSpaceObject scopeObj = null;
    if (scope != null) {
        UUID uuid = UUID.fromString(scope);
        scopeObj = communityService.find(context, uuid);
        if (scopeObj == null) {
            scopeObj = collectionService.find(context, uuid);
        }
    }

    // process the input, performing some inline validation
    final BrowseIndex bi;
    if (StringUtils.isNotEmpty(browseName)) {
        bi = BrowseIndex.getBrowseIndex(browseName);
    } else {
        bi = null;
    }
    if (bi == null) {
        throw new IllegalArgumentException("Unknown browse index");
    }
    if (!bi.isMetadataIndex()) {
        throw new IllegalStateException("The requested browse haven't metadata entries");
    }

    // set up a BrowseScope and start loading the values into it
    bs.setBrowseIndex(bi);
    Sort sort = null;
    if (pageable != null) {
        sort = pageable.getSort();
    }
    if (sort != null) {
        Iterator<Order> orders = sort.iterator();
        while (orders.hasNext()) {
            bs.setOrder(orders.next().getDirection().name());
        }
    }
    // bs.setFilterValue(value != null?value:authority);
    // bs.setFilterValueLang(valueLang);
    // bs.setJumpToItem(focus);
    // bs.setJumpToValue(valueFocus);
    // bs.setJumpToValueLang(valueFocusLang);
    // bs.setStartsWith(startsWith);
    if (pageable != null) {
        bs.setOffset(pageable.getOffset());
        bs.setResultsPerPage(pageable.getPageSize());
    }
    // bs.setEtAl(etAl);
    // bs.setAuthorityValue(authority);

    if (scopeObj != null) {
        bs.setBrowseContainer(scopeObj);
    }

    BrowseInfo binfo = be.browse(bs);
    Pageable pageResultInfo = new PageRequest((binfo.getStart() - 1) / binfo.getResultsPerPage(),
            binfo.getResultsPerPage());
    Page<BrowseEntryRest> page = new PageImpl<String[]>(Arrays.asList(binfo.getStringResults()), pageResultInfo,
            binfo.getTotal()).map(converter);
    page.forEach(new Consumer<BrowseEntryRest>() {
        @Override
        public void accept(BrowseEntryRest t) {
            t.setBrowseIndex(bixConverter.convert(bi));
        }
    });
    return page;
}

From source file:org.dspace.app.rest.repository.BrowseItemLinkRepository.java

public Page<ItemRest> listBrowseItems(HttpServletRequest request, String browseName, Pageable pageable,
        String projection) throws BrowseException, SQLException {
    //FIXME these should be bind automatically and available as method arguments
    String scope = null;//from w  ww . ja  va2 s  .co m
    String filterValue = null;
    String filterAuthority = null;

    if (request != null) {
        scope = request.getParameter("scope");
        filterValue = request.getParameter("filterValue");
        filterAuthority = request.getParameter("filterAuthority");
    }
    Context context = obtainContext();
    BrowseEngine be = new BrowseEngine(context);
    BrowserScope bs = new BrowserScope(context);
    DSpaceObject scopeObj = null;
    if (scope != null) {
        UUID uuid = UUID.fromString(scope);
        scopeObj = communityService.find(context, uuid);
        if (scopeObj == null) {
            scopeObj = collectionService.find(context, uuid);
        }
    }

    // process the input, performing some inline validation
    BrowseIndex bi = null;
    if (StringUtils.isNotEmpty(browseName)) {
        bi = BrowseIndex.getBrowseIndex(browseName);
    }
    if (bi == null) {
        throw new IllegalArgumentException("Unknown browse index");
    }
    if (!bi.isItemIndex() && (filterAuthority == null && filterValue == null)) {
        throw new IllegalStateException(
                "The requested browse doesn't provide direct access to items you must specify a filter");
    }

    if (!bi.isMetadataIndex() && (filterAuthority != null || filterValue != null)) {
        throw new IllegalStateException("The requested browse doesn't support filtering");
    }

    // set up a BrowseScope and start loading the values into it
    bs.setBrowseIndex(bi);
    Sort sort = null;
    if (pageable != null) {
        sort = pageable.getSort();
    }
    if (sort != null) {
        Iterator<Order> orders = sort.iterator();
        while (orders.hasNext()) {
            Order order = orders.next();
            bs.setOrder(order.getDirection().name());
            String sortBy;
            if (!StringUtils.equals("default", order.getProperty())) {
                sortBy = order.getProperty();
            } else {
                sortBy = bi.getDefaultOrder();
            }

            try {
                SortOption so = SortOption.getSortOption(sortBy);
                if (so != null) {
                    bs.setSortBy(so.getNumber());
                }
            } catch (SortException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }

    if (filterValue != null || filterAuthority != null) {
        bs.setFilterValue(filterValue);
        bs.setAuthorityValue(filterAuthority);
        bs.setBrowseLevel(1);
    }
    // bs.setFilterValueLang(valueLang);
    // bs.setJumpToItem(focus);
    // bs.setJumpToValue(valueFocus);
    // bs.setJumpToValueLang(valueFocusLang);
    // bs.setStartsWith(startsWith);
    if (pageable != null) {
        bs.setOffset(pageable.getOffset());
        bs.setResultsPerPage(pageable.getPageSize());
    }

    if (scopeObj != null) {
        bs.setBrowseContainer(scopeObj);
    }

    // For second level browses on metadata indexes, we need to adjust the default sorting
    if (bi != null && bi.isMetadataIndex() && bs.isSecondLevel() && bs.getSortBy() <= 0) {
        bs.setSortBy(1);
    }

    BrowseInfo binfo = be.browse(bs);

    Pageable pageResultInfo = new PageRequest((binfo.getStart() - 1) / binfo.getResultsPerPage(),
            binfo.getResultsPerPage());
    Page<ItemRest> page = new PageImpl<Item>(binfo.getBrowseItemResults(), pageResultInfo, binfo.getTotal())
            .map(converter);
    return page;
}

From source file:org.dspace.app.rest.repository.CollectionRestRepository.java

@Override
public Page<CollectionRest> findAll(Context context, Pageable pageable) {
    List<Collection> it = null;
    List<Collection> collections = new ArrayList<Collection>();
    int total = 0;
    try {//from w w w  . ja v  a 2  s. com
        total = cs.countTotal(context);
        it = cs.findAll(context, pageable.getPageSize(), pageable.getOffset());
        for (Collection c : it) {
            collections.add(c);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    Page<CollectionRest> page = new PageImpl<Collection>(collections, pageable, total).map(dsoConverter);
    return page;
}

From source file:org.dspace.app.rest.repository.CommunityRestRepository.java

@Override
public Page<CommunityRest> findAll(Context context, Pageable pageable) {
    List<Community> it = null;
    List<Community> communities = new ArrayList<Community>();
    int total = 0;
    try {/*www . j a  v  a 2s .  c  o  m*/
        total = cs.countTotal(context);
        it = cs.findAll(context, pageable.getPageSize(), pageable.getOffset());
        for (Community c : it) {
            communities.add(c);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    Page<CommunityRest> page = new PageImpl<Community>(communities, pageable, total).map(dsoConverter);
    return page;
}

From source file:org.dspace.app.rest.repository.EPersonRestRepository.java

@Override
public Page<EPersonRest> findAll(Context context, Pageable pageable) {
    List<EPerson> epersons = null;
    int total = 0;
    try {// w  w  w .j ava  2s  .  com
        if (!authorizeService.isAdmin(context)) {
            throw new RESTAuthorizationException(
                    "The EPerson collection endpoint is reserved to system administrators");
        }
        total = es.countTotal(context);
        epersons = es.findAll(context, EPerson.ID, pageable.getPageSize(), pageable.getOffset());
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    Page<EPersonRest> page = new PageImpl<EPerson>(epersons, pageable, total).map(converter);
    return page;
}

From source file:org.dspace.app.rest.repository.EPersonRestRepository.java

/**
 * Find the epersons matching the query q parameter. The search is delegated to the
 * {@link EPersonService#search(Context, String, int, int)} method
 *
 * @param q/* ww w. ja v  a  2s .c  o  m*/
 *            is the *required* query string
 * @param pageable
 *            contains the pagination information
 * @return a Page of EPersonRest instances matching the user query
 */
@SearchRestMethod(name = "byName")
public Page<EPersonRest> findByName(@Parameter(value = "q", required = true) String q, Pageable pageable) {
    List<EPerson> epersons = null;
    int total = 0;
    try {
        Context context = obtainContext();
        epersons = es.search(context, q, pageable.getOffset(), pageable.getOffset() + pageable.getPageSize());
        total = es.searchResultCount(context, q);
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    Page<EPersonRest> page = new PageImpl<EPerson>(epersons, pageable, total).map(converter);
    return page;
}

From source file:org.dspace.app.rest.repository.ItemRestRepository.java

@Override
@PreAuthorize("hasAuthority('ADMIN')")
public Page<ItemRest> findAll(Context context, Pageable pageable) {
    Iterator<Item> it = null;
    List<Item> items = new ArrayList<Item>();
    int total = 0;
    try {//  ww  w .  j av a2s.co m
        total = is.countTotal(context);
        it = is.findAll(context, pageable.getPageSize(), pageable.getOffset());
        while (it.hasNext()) {
            Item i = it.next();
            items.add(i);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    Page<ItemRest> page = new PageImpl<Item>(items, pageable, total).map(dsoConverter);
    return page;
}