Example usage for org.springframework.data.domain PageImpl PageImpl

List of usage examples for org.springframework.data.domain PageImpl PageImpl

Introduction

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

Prototype

public PageImpl(List<T> content, Pageable pageable, long total) 

Source Link

Document

Constructor of PageImpl .

Usage

From source file:com.epam.ta.reportportal.database.dao.UserRepositoryCustomImpl.java

@Override
public Page<User> searchForUserLogin(String term, Pageable pageable) {
    final String regex = "(?i).*" + Pattern.quote(term.toLowerCase()) + ".*";
    Criteria login = where(LOGIN).regex(regex);
    Criteria fullName = where(FULLNAME_DB_FIELD).regex(regex);
    Criteria criteria = new Criteria().orOperator(login, fullName);
    Query query = query(criteria).with(pageable);
    query.fields().include(LOGIN);/*from   www  .j ava2 s.c  o m*/
    query.fields().include(FULLNAME_DB_FIELD);
    List<User> users = mongoOperations.find(query, User.class);
    return new PageImpl<>(users, pageable, mongoOperations.count(query, User.class));
}

From source file:org.openlmis.fulfillment.web.OrderController.java

/**
 * Search through orders with given parameters.
 *
 * @param params   order search params//from  w  w  w.j  a  v  a  2  s. c o  m
 * @param pageable pagination parameters
 * @return OrderDtos.
 */
@GetMapping("/orders")
@ResponseBody
public Page<BasicOrderDto> searchOrders(OrderSearchParams params, Pageable pageable) {
    Profiler profiler = new Profiler("SEARCH_ORDERS");
    profiler.setLogger(LOGGER);

    profiler.start("SEARCH_ORDERS_IN_SERVICE");
    Page<Order> orders = orderService.searchOrders(params, pageable);

    profiler.start("TO_DTO");
    List<BasicOrderDto> dtos = basicOrderDtoBuilder.build(orders.getContent());
    Page<BasicOrderDto> dtoPage = new PageImpl<>(dtos, pageable, orders.getTotalElements());

    profiler.stop().log();
    return dtoPage;
}

From source file:org.venice.piazza.common.hibernate.dao.service.ServiceDaoImpl.java

public Page<ServiceEntity> getServiceListByKeyword(String keyword, Pagination pagination) {
    // Query//  w w  w .  j  ava 2 s. c om
    String queryString = String.format(KEYWORD_SERVICE_QUERY, Direction.fromString(pagination.getOrder()));
    Query query = entityManager.createNativeQuery(queryString, ServiceEntity.class);
    query.setParameter(1, String.format(WILDCARD_STRING_QUERY, keyword));
    query.setParameter(2, String.format(WILDCARD_STRING_QUERY, keyword));
    query.setParameter(3, pagination.getSortBy());
    query.setParameter(4, pagination.getPerPage());
    query.setParameter(5, pagination.getPage() * pagination.getPerPage());
    List<ServiceEntity> results = query.getResultList();
    // Count
    query = entityManager.createNativeQuery(KEYWORD_SERVICE_QUERY_COUNT);
    query.setParameter(1, String.format(WILDCARD_STRING_QUERY, keyword));
    query.setParameter(2, String.format(WILDCARD_STRING_QUERY, keyword));
    long count = ((BigInteger) query.getSingleResult()).longValue();
    return new PageImpl<ServiceEntity>(results, null, count);
}

From source file:eu.trentorise.game.managers.DBPlayerManager.java

public Page<PlayerState> loadStates(String gameId, Pageable pageable) {
    StopWatch stopWatch = LogManager.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("perf-file") != null
            ? new Log4JStopWatch()
            : null;//from  w  ww .  java 2s .  c  o  m
    if (stopWatch != null) {
        stopWatch.start("loadStates");
    }
    Page<StatePersistence> states = playerRepo.findByGameId(gameId, pageable);
    List<PlayerState> result = new ArrayList<PlayerState>();
    for (StatePersistence state : states) {
        result.add(initConceptsStructure(new PlayerState(state), gameId));
    }
    PageImpl<PlayerState> res = new PageImpl<PlayerState>(result, pageable, states.getTotalElements());
    if (stopWatch != null) {
        stopWatch.stop("loadStates", "Loaded states of game " + gameId);
    }
    return res;
}

From source file:uk.ac.ebi.ep.data.repositories.UniprotEntryRepositoryImpl.java

@Transactional(readOnly = true)
@Override/*w w w. j  a  v a  2  s. co  m*/
public Page<EnzymeSummary> findEnzymesByAccessions(List<String> accessions, Pageable pageable) {
    JPAQuery query = new JPAQuery(entityManager);
    //CollQueryFactory.
    List<EnzymeSummary> result = query.from($).where($.accession.in(accessions))
            .list(Projections.constructor(EnzymeSummary.class, $));

    return new PageImpl<>(result, pageable, result.size());

}

From source file:com.jiwhiz.rest.site.WebsiteRestControllerTest.java

@Test
public void getApprovedUserCommentPosts_ShouldReturnApprovedComments() throws Exception {
    UserAccount user = getTestLoggedInUser();
    Page<CommentPost> page = new PageImpl<CommentPost>(getTestApprovedCommentPostList(), new PageRequest(0, 10),
            2);//from  ww w. ja  v a  2  s  .com

    when(userAccountServiceMock.loadUserByUserId(USER_USERNAME)).thenReturn(user);
    when(commentPostRepositoryMock.findByAuthorAndStatusOrderByCreatedTimeDesc(eq(user),
            eq(CommentStatusType.APPROVED), any(Pageable.class))).thenReturn(page);

    mockMvc.perform(get(API_ROOT + URL_SITE_PROFILES_USER_COMMENTS, USER_USERNAME)).andExpect(status().isOk())
            .andExpect(content().contentType(MediaTypes.HAL_JSON))
            .andExpect(jsonPath("$._embedded.commentPostList", hasSize(2)))
            .andExpect(jsonPath("$._embedded.commentPostList[0].id", is(COMMENTS_1_ID)))
            .andExpect(jsonPath("$._embedded.commentPostList[0].content", is(COMMENTS_1_CONTENT)))
            .andExpect(jsonPath("$._embedded.commentPostList[1].id", is(COMMENTS_2_ID)))
            .andExpect(jsonPath("$._embedded.commentPostList[1].content", is(COMMENTS_2_CONTENT)))
            .andExpect(jsonPath("$._links.self.templated", is(true)))
            .andExpect(jsonPath("$._links.self.href", endsWith("/comments{?page,size,sort}")))
            .andExpect(jsonPath("$.page.size", is(10))).andExpect(jsonPath("$.page.totalElements", is(2)))
            .andExpect(jsonPath("$.page.totalPages", is(1))).andExpect(jsonPath("$.page.number", is(0)));

    verify(commentPostRepositoryMock, times(1)).findByAuthorAndStatusOrderByCreatedTimeDesc(
            any(UserAccount.class), eq(CommentStatusType.APPROVED), any(Pageable.class));
    verifyNoMoreInteractions(commentPostRepositoryMock);

}

From source file:com.netflix.genie.core.jpa.services.JpaJobSearchServiceImpl.java

/**
 * {@inheritDoc}/*ww w  . j  a v  a 2 s  .  c om*/
 */
@Override
public Page<JobSearchResult> findJobs(final String id, final String jobName, final String user,
        final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final String clusterId,
        final String commandName, final String commandId, final Date minStarted, final Date maxStarted,
        final Date minFinished, final Date maxFinished, @NotNull final Pageable page) {
    log.debug("called");

    final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
    final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    final Root<JobEntity> root = countQuery.from(JobEntity.class);

    final Predicate whereClause = JpaJobSpecs.getFindPredicate(root, cb, id, jobName, user, statuses, tags,
            clusterName, clusterId == null ? null : this.clusterRepository.findOne(clusterId), commandName,
            commandId == null ? null : this.commandRepository.findOne(commandId), minStarted, maxStarted,
            minFinished, maxFinished);

    countQuery.select(cb.count(root)).where(whereClause);

    final Long count = this.entityManager.createQuery(countQuery).getSingleResult();

    // Use the count to make sure we even need to make this query
    if (count > 0) {
        final CriteriaQuery<JobSearchResult> contentQuery = cb.createQuery(JobSearchResult.class);
        contentQuery.from(JobEntity.class);

        contentQuery.multiselect(root.get(JobEntity_.id), root.get(JobEntity_.name), root.get(JobEntity_.user),
                root.get(JobEntity_.status), root.get(JobEntity_.started), root.get(JobEntity_.finished),
                root.get(JobEntity_.clusterName), root.get(JobEntity_.commandName));

        contentQuery.where(whereClause);

        final Sort sort = page.getSort();
        final List<Order> orders = new ArrayList<>();
        sort.iterator().forEachRemaining(order -> {
            if (order.isAscending()) {
                orders.add(cb.asc(root.get(order.getProperty())));
            } else {
                orders.add(cb.desc(root.get(order.getProperty())));
            }
        });

        contentQuery.orderBy(orders);

        final List<JobSearchResult> results = this.entityManager.createQuery(contentQuery)
                .setFirstResult(page.getOffset()).setMaxResults(page.getPageSize()).getResultList();

        return new PageImpl<>(results, page, count);
    } else {
        return new PageImpl<>(Lists.newArrayList(), page, count);
    }
}

From source file:io.kahu.hawaii.util.call.sql.DbRequestBuilderRepository.java

public <T> Page<T> getPage(String count, String fetch, Map<String, Object> params, RowMapper<T> rowMapper,
        Pageable pageable, QueryEnhancer queryEnhancer, Long maxRows) throws ServerException {
    Assert.notNull(pageable);//from w  w w .  j  a v a 2  s  .  c  o  m

    // retrieve query...
    Long rowCount = getCount(count).withParams(params).withQueryEnhancer(queryEnhancer).withPageable(pageable)
            .get();
    if (maxRows != null && (rowCount > maxRows)) {
        // Threshold defined and total number of records is higher
        return new PageImpl<>(new ArrayList<>(), new PageRequest(0, 1), rowCount);
    }

    queryEnhancer.addPaging(params, pageable);

    final List<T> pageItems = getList(fetch, rowMapper).withParams(params).withQueryEnhancer(queryEnhancer)
            .withPageable(pageable).get();

    // return the page
    return new PageImpl<>(pageItems, pageable, rowCount);
}

From source file:com.linkcm.core.dao.BaseJdbcDao.java

/**
 * sql/*w w  w .j  a  va 2  s . com*/
 * 
 * */
public Page<Map<String, Object>> findPageBySql(Pageable pageable, String sql, final Object... values) {
    String countSql = jdbcDialect.getPaginationCountSql(sql);
    long size = getJdbcTemplate().queryForLong(countSql, values);

    String sortSql = getSortSql(pageable.getSort(), sql);

    String querySql = jdbcDialect.getPaginationQuerySql(sortSql,
            pageable.getPageNumber() * pageable.getPageSize(), pageable.getPageSize());

    List<Map<String, Object>> result = getJdbcTemplate().queryForList(querySql, values);
    return new PageImpl<Map<String, Object>>(result, pageable, size);
}

From source file:com.baoqilai.core.dao.BaseJdbcDao.java

/**
 * sql// w w  w.  ja  v  a2 s . co m
 * 
 * */
public Page<Map<String, Object>> findPageBySql(Pageable pageable, String sql, final Object... values) {
    String countSql = jdbcDialect.getPaginationCountSql(sql);
    @SuppressWarnings("deprecation")
    long size = getJdbcTemplate().queryForLong(countSql, values);

    String sortSql = getSortSql(pageable.getSort(), sql);

    String querySql = jdbcDialect.getPaginationQuerySql(sortSql,
            pageable.getPageNumber() * pageable.getPageSize(), pageable.getPageSize());

    List<Map<String, Object>> result = getJdbcTemplate().queryForList(querySql, values);
    return new PageImpl<Map<String, Object>>(result, pageable, size);
}