Java Code Examples for org.springframework.data.domain.Pageable#getPageNumber()

The following examples show how to use org.springframework.data.domain.Pageable#getPageNumber() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SearchRequest.java    From es with Apache License 2.0 6 votes vote down vote up
private void merge(Sort sort, Pageable page) {
    if (sort == null) {
        sort = this.sort;
    }
    if (page == null) {
        page = this.page;
    }

    //合并排序
    if (sort == null) {
        this.sort = page != null ? page.getSort() : null;
    } else {
        this.sort = (page != null ? sort.and(page.getSort()) : sort);
    }
    //把排序合并到page中
    if (page != null) {
        this.page = new PageRequest(page.getPageNumber(), page.getPageSize(), this.sort);
    } else {
        this.page = null;
    }
}
 
Example 2
Source File: SysRedisController.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取所有key
 * @param pageable
 * @return
 */
@GetMapping
public R getAllByPage(Pageable pageable) {
    List<RedisVo> redisList = redisUtil.getAll();
    int totalElements = redisList.size();
    if (pageable == null) {
        pageable = PageRequest.of(0, 10);
    }
    int fromIndex = pageable.getPageSize() * pageable.getPageNumber();
    int toIndex = pageable.getPageSize() * (pageable.getPageNumber() + 1);
    if (toIndex > totalElements) {
        toIndex = totalElements;
    }
    List<RedisVo> indexObjects = redisList.subList(fromIndex, toIndex);
    Page<RedisVo> page = new PageImpl<>(indexObjects, pageable, totalElements);
    return R.ok(page);
}
 
Example 3
Source File: JdbcClient.java    From plumdo-work with Apache License 2.0 6 votes vote down vote up
public PageResponse queryForPage(String sql, Pageable pageable, Object... args) {
    PageResponse pageResponse = new PageResponse();

    pageResponse.setTotal(queryForCount("SELECT COUNT(1) AS TOTAL FROM (" + sql + ") temp ", args));

    if (pageResponse.getTotal() <= 0) {
        pageResponse.setData(Collections.emptyList());
    } else {
        StringBuilder pageSql = new StringBuilder();
        pageSql.append("SELECT temp.* FROM (").append(sql).append(") temp ");

        if (pageable.getSort() != null) {
            pageSql.append(getOrderBySql(pageable.getSort()));
        }
        if (pageable.getPageNumber() > 0 && pageable.getPageSize() > 0) {
            pageSql.append(" LIMIT ").append(pageable.getOffset()).append(",").append(pageable.getPageSize());
        }
        pageResponse.setData(queryForList(pageSql.toString(), args));
    }
    return pageResponse;
}
 
Example 4
Source File: SolrPageRequest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object obj) {

	if (this == obj) {
		return true;
	}
	if (obj == null || !(obj instanceof Pageable)) {
		return false;
	}

	Pageable other = (Pageable) obj;
	if (page != other.getPageNumber()) {
		return false;
	}
	if (size != other.getPageSize()) {
		return false;
	}
	if (sort == null) {
		if (other.getSort() != null) {
			return false;
		}
	} else if (!sort.equals(other.getSort())) {
		return false;
	}
	return true;
}
 
Example 5
Source File: AbstractSolrQuery.java    From dubbox with Apache License 2.0 6 votes vote down vote up
protected Pageable getLimitingPageable(final Pageable source, final int limit) {

		if (source == null) {
			return new SolrPageRequest(0, limit);
		}

		return new PageRequest(source.getPageNumber(), source.getPageSize(), source.getSort()) {

			private static final long serialVersionUID = 8100166028148948968L;

			@Override
			public int getOffset() {
				return source.getOffset();
			}

			@Override
			public int getPageSize() {
				return limit;
			}

		};
	}
 
Example 6
Source File: DatasRepository.java    From blog with MIT License 6 votes vote down vote up
@Override
public Page<Message> findAll(Pageable arg0) {
	int pSize = arg0.getPageSize();
	int pNumb = arg0.getPageNumber();
	int pFirst = pNumb * pSize;
	int pLast = pFirst + pSize;
	int total = datas.size();
	List<Message> content = new ArrayList<>();
	for (int i = 0; i < total; i++) {
		if (i >= pFirst && i < pLast) {
			Message data = datas.get(i);
			content.add(data);
		}
	}
	return new PageImpl<>(content, arg0, total);
}
 
Example 7
Source File: PageableAdapter.java    From springlets with Apache License 2.0 5 votes vote down vote up
@Override
public PageRequestDto marshal(Pageable request) {

  PageRequestDto dto = new PageRequestDto();
  dto.orders = request.getSort() == null ? Collections.<OrderDto>emptyList()
      : SpringDataJaxb.marshal(request.getSort(), OrderAdapter.INSTANCE);
  dto.page = request.getPageNumber();
  dto.size = request.getPageSize();

  return dto;
}
 
Example 8
Source File: FooController.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping("/pageable")
public List<Foo> findPaginatedWithPageable(Pageable pageable, final UriComponentsBuilder uriBuilder,
    final HttpServletResponse response) {
    final Page<Foo> resultPage = service.findPaginated(pageable);
    if (pageable.getPageNumber() > resultPage.getTotalPages()) {
        throw new MyResourceNotFoundException();
    }
    eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response,
        pageable.getPageNumber(), resultPage.getTotalPages(), pageable.getPageSize()));

    return resultPage.getContent();
}
 
Example 9
Source File: FileResource.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
/**
 * check if object pageable is well formated.
 * It should have sort, page number and page size or the method set to default value if necessary
 *
 * @param pageable
 * @return
 */
private Pageable CheckOrUpdatePageable(Pageable pageable) {
    int pageNo = 0;
    int pageSize = Constants.PAGE_SIZE;
    if (pageable != null) {
        pageNo = pageable.getPageNumber();
        pageSize = pageable.getPageSize();
    }
    if (pageable == null || pageable.getSort() == null) {
        pageable = new PageRequest(pageNo, pageSize, new Sort("_score"));
    }
    return pageable;
}
 
Example 10
Source File: FileResource.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
/**
 * GET  /files : get all the files.
 *
 * @param pageable the pagination information
 * @param version the version filter if set
 * @param project the project filter if set
 * @return the ResponseEntity with status 200 (OK) and the list of files in body
 * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
 */
@RequestMapping(value = "/files",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<File>> getAllFiles(@RequestParam(required = false) List<String> version,
                                              @RequestParam(required = false) List<String> project,
                                              @RequestParam(required = false) List<String> extension,
                                              Pageable pageable)
    throws URISyntaxException {
    //check if pageable is ok (has sort, page number, page size) and set to default if necessary
    pageable = CheckOrUpdatePageable(pageable);
    log.debug("REST request to get page {} for All Files with filter version {} and project {}", pageable.getPageNumber() + 1, version, project);

    //verification if we got a request with a big page number wich is greater than the max result search window
    if (pageable.getPageNumber() * pageable.getPageSize() >= Constants.MAX_RESULT_SEARCH_WINDOW) {
        log.warn("getAllFiles : page request too high : {}", pageable.getPageNumber());
        pageable = new PageRequest(0, pageable.getPageSize(), pageable.getSort());
    }
    Page<File> page;
    if (extension != null && extension.contains("empty")) {
        extension.add("");
        extension.remove("empty");
    }

    //page = fileSearchRepository.findAll(pageable);
    page = customSearchRepository.customfindAll(pageable, version, project, extension);
    //page = customSearchRepository.findWithHighlightedSummary(pageable,"",version);
    //Page<File> page = customSearchRepository.findWithHighlightedSummary("", pageable);


    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/files");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 11
Source File: BaseCommentServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Page<BaseCommentVO> pageVosBy(List<COMMENT> comments, Pageable pageable) {
    Assert.notNull(comments, "Comments must not be null");
    Assert.notNull(pageable, "Page info must not be null");

    Comparator<BaseCommentVO> commentComparator = buildCommentComparator(pageable.getSortOr(Sort.by(Sort.Direction.DESC, "createTime")));

    // Convert to vo
    List<BaseCommentVO> topComments = convertToVo(comments, commentComparator);

    List<BaseCommentVO> pageContent;

    // Calc the shear index
    int startIndex = pageable.getPageNumber() * pageable.getPageSize();
    if (startIndex >= topComments.size() || startIndex < 0) {
        pageContent = Collections.emptyList();
    } else {
        int endIndex = startIndex + pageable.getPageSize();
        if (endIndex > topComments.size()) {
            endIndex = topComments.size();
        }

        log.debug("Top comments size: [{}]", topComments.size());
        log.debug("Start index: [{}]", startIndex);
        log.debug("End index: [{}]", endIndex);

        pageContent = topComments.subList(startIndex, endIndex);
    }

    return new CommentPage<>(pageContent, pageable, topComments.size(), comments.size());
}
 
Example 12
Source File: SimpleDbTemplate.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
@Override
public <T> Page<T> executePagedQueryImpl(Class<T> entityClass, String query, Pageable pageable,
                                         boolean consistentRead, SimpleDbEntityInformation<T, ?> entityInformation) {
    Assert.notNull(pageable);
    Assert.isTrue(pageable.getPageNumber() >= 0);
    Assert.isTrue(pageable.getPageSize() > 0);

    final String escapedQuery = getEscapedQuery(query, entityInformation);

    List<T> resultsList;
    String queryWithPageSizeLimit = new QueryBuilder(escapedQuery).with(pageable).toString();

    if (pageable.getPageNumber() > 0) {
        String pageOffsetToken = getPageOffsetToken(pageable, entityInformation, escapedQuery, consistentRead);

        if (pageOffsetToken != null && !pageOffsetToken.isEmpty()) {
            resultsList = find(entityInformation, queryWithPageSizeLimit, pageOffsetToken, consistentRead);
        } else {
            resultsList = Collections.emptyList();
        }

    } else {
        resultsList = find(entityClass, queryWithPageSizeLimit, consistentRead);
    }

    final String countQuery = new QueryBuilder(escapedQuery, true).toString();

    Long totalCount = count(countQuery, entityClass, consistentRead);

    return new PageImpl<T>(resultsList, pageable, totalCount);
}
 
Example 13
Source File: PageUtil.java    From jhipster with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link org.springframework.data.domain.Page} from a {@link java.util.List} of objects
 *
 * @param list list of objects
 * @param pageable pagination information.
 * @param <T> type of object
 * @return page containing objects, and attributes set according to pageable
 * @throws java.lang.IllegalArgumentException - if list is null
 */
static <T> Page<T> createPageFromList(List<T> list, Pageable pageable) {
    if (list == null) {
        throw new IllegalArgumentException("To create a Page, the list mustn't be null!");
    }

    int startOfPage = pageable.getPageNumber() * pageable.getPageSize();
    if (startOfPage > list.size()) {
        return new PageImpl<>(new ArrayList<>(), pageable, 0);
    }

    int endOfPage = Math.min(startOfPage + pageable.getPageSize(), list.size());
    return new PageImpl<>(list.subList(startOfPage, endOfPage), pageable, list.size());
}
 
Example 14
Source File: DatastorePageable.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
private DatastorePageable(Pageable pageable, String urlSafeCursor, Long totalCount) {
	super(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort());
	this.urlSafeCursor = urlSafeCursor;
	this.totalCount = totalCount;
}
 
Example 15
Source File: BookRepository.java    From tutorials with MIT License 4 votes vote down vote up
public Page<Book> getBooks(Pageable pageable) {
    int toSkip = pageable.getPageSize() * pageable.getPageNumber();
    List<Book> result = books.values().stream().skip(toSkip).limit(pageable.getPageSize()).collect(toList());

    return new PageImpl<>(result, pageable, books.size());
}
 
Example 16
Source File: DatatablesPageable.java    From springlets with Apache License 2.0 4 votes vote down vote up
public DatatablesPageable(Pageable pageable) {
  super(pageable.getPageNumber() / pageable.getPageSize(), pageable.getPageSize(),
      pageable.getSort());
}
 
Example 17
Source File: QueryDslRepositorySupportExt.java    From springlets with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the given {@link Pageable} to the given {@link JPQLQuery}.
 * Allows to map the attributes to order as provided in the {@link Pageable}
 * to real entity attributes. This might be used to work with projections
 * or DTOs whose attributes don't have the same name as the entity ones.
 *
 * It allows to map to more than one entity attribute. As an example, if
 * the DTO used to create the {@link Pageable} has a fullName attribute, you
 * could map that attribute to two entity attributes: name and surname.
 * In this case, the {@link Pageable} defines an order by a fullName
 * attribute, but que query will order by name and surname instead.
 *
 * @param pageable the ordering and paging
 * @param query
 * @param attributeMapping definition of a mapping of order attribute names
 *        to real entity ones
 * @return the updated query
 */
protected JPQLQuery<T> applyPagination(Pageable pageable, JPQLQuery<T> query,
    Map<String, Path<?>[]> attributeMapping) {

  if (pageable == null) {
    return query;
  }

  Pageable mappedPageable;
  Sort sort = pageable.getSort();
  if (sort != null) {
    List<Sort.Order> mappedOrders = new ArrayList<Sort.Order>();
    for (Sort.Order order : sort) {
      if (!attributeMapping.containsKey(order.getProperty())) {
        LOG.warn(
            "The property (%1) is not included in the attributeMapping, will order "
                + "using the property as it is",
            order.getProperty());
        mappedOrders.add(order);
      } else {
        Path<?>[] paths = attributeMapping.get(order.getProperty());
        for (Path<?> path : paths) {
          Sort.Order mappedOrder =
              new Sort.Order(order.getDirection(), preparePropertyPath(path));
          mappedOrders.add(mappedOrder);
        }
      }
    }
    if (mappedOrders.isEmpty()) {
      // No properties to order by are available, so don't apply ordering and return the query
      // as it is
      return query;
    }
    mappedPageable =
        new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(mappedOrders));
    return applyPagination(mappedPageable, query);
  } else {
    return applyPagination(pageable, query);
  }

}
 
Example 18
Source File: BookController.java    From Spring with Apache License 2.0 3 votes vote down vote up
/**
 *  Pageable и Sort передается в аргументе метода благодаря:
 *
 *  <mvc:annotation-driven conversion-service="conversionService">
 *         <mvc:argument-resolvers>
 *
 *             <bean class="org.springframework.data.web.PageableHandlerMethodArgumentResolver">
 *                 <property name="maxPageSize" value="3"/>
 *             </bean>

 *             <bean class="org.springframework.data.web.SortHandlerMethodArgumentResolver"/>
 *         </mvc:argument-resolvers>
 *     </mvc:annotation-driven>
 */
@RequestMapping("/books")
public String showBooksPageable(Model model, Pageable pageable, Sort sort) {
    final PageRequest pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
    final Page<Book> books = repository.findAll(pageRequest);
    model.addAttribute("page", books);
    model.addAttribute("sort", (sort != null) ? sort.iterator().next().getProperty(): "");
    return "books";
}
 
Example 19
Source File: SimpleDbTemplate.java    From spring-data-simpledb with MIT License 3 votes vote down vote up
private <T> String getPageOffsetToken(final Pageable pageable, SimpleDbEntityInformation<T, ?> entityInformation,
                                      String query, boolean consistentRead) {

	int endOfPreviousPageLimit = pageable.getPageNumber() * pageable.getPageSize();

    final String escapedQuery = getEscapedQuery(query, entityInformation);
    final String countQuery = new QueryBuilder(escapedQuery, true).withLimit(endOfPreviousPageLimit).toString();

    return getNextToken(countQuery, consistentRead);
}
 
Example 20
Source File: PageUtil.java    From beihu-boot with Apache License 2.0 2 votes vote down vote up
/**
 * 分页返回
 *
 * @param page
 * @param pageable
 * @param <T>
 * @return
 */
public static <T> PageResult<T> pageResult(Page<T> page, Pageable pageable) {
    return new PageResult<T>(page.getContent(), pageable.getPageNumber() + 1, pageable.getPageSize(), page.getTotalElements());
}