Java Code Examples for org.springframework.data.domain.Page

The following examples show how to use org.springframework.data.domain.Page. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: cubeai   Source File: PaginationUtilUnitTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, new PageRequest(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 2
Source Project: TeamDojo   Source File: PaginationUtilUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
        + "</api/_search/example?page=5&size=50>; rel=\"prev\","
        + "</api/_search/example?page=7&size=50>; rel=\"last\","
        + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 3
Source Project: spring-cloud-gray   Source File: UserResource.java    License: Apache License 2.0 6 votes vote down vote up
@GetMapping(value = "/page")
public ResponseEntity<ApiRes<List<UserInfo>>> page(
        @RequestParam(value = "key", required = false) String key,
        @RequestParam(value = "status", required = false) Integer status,
        @ApiParam @PageableDefault(sort = "createTime", direction = Sort.Direction.DESC) Pageable pageable) {

    UserQuery userQuery = UserQuery.builder()
            .key(key)
            .status(ObjectUtils.defaultIfNull(status, -1))
            .build();

    Page<UserInfo> userInfoPage = userModule.query(userQuery, pageable);
    HttpHeaders headers = PaginationUtils.generatePaginationHttpHeaders(userInfoPage);
    return new ResponseEntity<>(
            ApiResHelper.successData(userInfoPage.getContent()),
            headers,
            HttpStatus.OK);
}
 
Example 4
@GetMapping
public String manageNotifications(@RequestParam(required = false) Integer page, Model model) {
    model.addAttribute("page_title", "Manage Notifications");
    model.addAttribute("page_subtitle", "Notification Manager");
    model.addAttribute("page_description", "Manage and monitor sent notifications");

    int currentPage = NotificationUtils.normalizePage(page);
    Page<Notification> notificationPage = notificationManagementService.getNotifications(currentPage);

    NotificationUtils.prepareNotifications(model, notificationPage, currentPage);
    List<Notification> notifications = notificationPage.getContent();
    notificationManagementService.setInformation(notifications);
    model.addAttribute("notifications", notifications);

    return "management/manage_notifications";
}
 
Example 5
Source Project: market   Source File: StorageControllerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getStorageUnits_Available() throws Exception {
	PageRequest request = PageRequest.of(0, 3);
	List<Product> products = Collections.singletonList(product1);
	Page<Product> page = new PageImpl<>(products, request, products.size());

	given(productService.findByAvailability(stringCaptor.capture(), pageableCaptor.capture()))
		.willReturn(page);

	mockMvc.perform(
		get("/admin/storage")
			.param("available", "true"))
		.andExpect(status().isOk())
		.andExpect(view().name("admin/storage"))
		.andExpect(model().attribute("page", productAssembler.toModel(page)))
		.andExpect(model().attribute("currentlyAvailable", equalTo("true")));
	assertThat(stringCaptor.getValue(), equalTo("true"));
}
 
Example 6
Source Project: youkefu   Source File: EkmKnowledgeTimesRepositoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Page<EkmKnowledgeTimes> findByOrgi(String orgi, Pageable pageable) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	
	boolQueryBuilder.must(QueryBuilders.termQuery("orgi", orgi)) ;
	HasParentQueryBuilder hasParentQueryBuilder=QueryBuilders.hasParentQuery("uk_ekm_kb_master",QueryBuilders.termQuery("datastatus", false));
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("viewtimes").unmappedType("long").order(SortOrder.DESC)).withQuery(hasParentQueryBuilder);
	searchQueryBuilder.withPageable(pageable) ;
	Page<EkmKnowledgeTimes> knowledgeTimesList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeTimes.class)){
		knowledgeTimesList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeTimes.class ) ;
    }
	
	return knowledgeTimesList;
}
 
Example 7
Source Project: spring-data-cosmosdb   Source File: PageableAddressRepositoryIT.java    License: MIT License 5 votes vote down vote up
@Test
public void testFindWithPartitionKeyMultiPages() {
    final CosmosPageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_1, null);
    final Page<PageableAddress> page = repository.findByCity(TestConstants.CITY, pageRequest);

    assertThat(page.getContent().size()).isEqualTo(PAGE_SIZE_1);
    validateResultCityMatch(page, TestConstants.CITY);
    validateNonLastPage(page, PAGE_SIZE_1);

    final Page<PageableAddress> nextPage = repository.findByCity(TestConstants.CITY, page.getPageable());

    assertThat(nextPage.getContent().size()).isEqualTo(PAGE_SIZE_1);
    validateResultCityMatch(page, TestConstants.CITY);
    validateLastPage(nextPage, PAGE_SIZE_1);
}
 
Example 8
Source Project: e   Source File: CompanyServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping({ "/page" })
@ControllerLogExeTime(description = "分页查询公司", log = false)
@DataPermission(uniqueKey="CompanyServiceImpl.queryPage",findAll=true)
public Page<CompanyEntity> queryPage(CompanyQueryParam companyQueryParam, Pageable pageable) {
    if (companyQueryParam != null) {
        processSort(companyQueryParam);
        Date registerDateEnd = companyQueryParam.getRegisterDateEnd();
        if (registerDateEnd != null) {
            registerDateEnd = DateUtil.addOneDay(registerDateEnd);
            companyQueryParam.setRegisterDateEnd(registerDateEnd);
        }
    }
    Page<CompanyEntity> page = this.companyRepository.findCompanyPage((companyQueryParam), pageable);
    return page;
}
 
Example 9
Source Project: JavaQuarkBBS   Source File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping
public PageResult getAll(User user, String draw,
                         @RequestParam(required = false, defaultValue = "1") int start,
                         @RequestParam(required = false, defaultValue = "10") int length) {
    int pageNo = start / length;
    Page<User> page = userService.findByPage(user, pageNo, length);
    PageResult<List<User>> result = new PageResult<>(
            draw,
            page.getTotalElements(),
            page.getTotalElements(),
            page.getContent());
    return result;
}
 
Example 10
Source Project: logistics-back   Source File: CargoReceiptController.java    License: MIT License 5 votes vote down vote up
/**
 * 查询所有运单
 */
@RequestMapping(value = "/select", method = RequestMethod.GET)
public Result selectAll(@RequestParam("pageNum") int pageNum, @RequestParam("limit") int limit) {
	Pageable pageable = PageRequest.of(pageNum-1, limit);
	Page<CargoReceipt> page = cargoReceiptService.selectAll(pageable);
	Result result  = new Result(200, "SUCCESS", (int) page.getTotalElements(), page.getContent());
	return result;	
}
 
Example 11
Source Project: springBoot   Source File: PageInfo.java    License: MIT License 5 votes vote down vote up
/**
 * 获取JPA的分页对象
 */
public static Page readPage(Query query, Pageable pageable, Query countQuery) {
    if (pageable.isPaged()) {
        query.setFirstResult((int) pageable.getOffset());
        query.setMaxResults(pageable.getPageSize());
    }
    return PageableExecutionUtils.getPage(query.getResultList(), pageable, () -> executeCountQuery(countQuery));
}
 
Example 12
Source Project: logistics-back   Source File: GoodsBillController.java    License: MIT License 5 votes vote down vote up
/**
 * 查询所有运单
 */
@RequestMapping(value = "/selectByEvent", method = RequestMethod.GET)
public Result selectAllGoodsBills(@RequestParam("pageNum") int pageNum, @RequestParam("limit") int limit) {
	Pageable pageable = PageRequest.of(pageNum-1, limit);
	Page<GoodsBillEvent> page =  goodsBillService.selectAllGoogsBillByPage(pageable);
	Result result  = new Result(200, "SUCCESS", (int) page.getTotalElements(), page.getContent());
	return result;
}
 
Example 13
Source Project: sureness   Source File: RoleController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("/api/{roleId}/{currentPage}/{pageSize}")
public ResponseEntity<Message> getResourceOwnByRole(@PathVariable @NotBlank Long roleId, @PathVariable Integer currentPage, @PathVariable Integer pageSize) {
    if (currentPage == null){
        currentPage = 1;
    }
    if (pageSize == null) {
        pageSize = 10;
    }
    Page<AuthResourceDO> resourcePage = roleService.getPageResourceOwnRole(roleId, currentPage, pageSize);
    Message message = Message.builder().data(resourcePage).build();
    return ResponseEntity.ok().body(message);
}
 
Example 14
Source Project: ehcache3-samples   Source File: AuditResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * GET /audits : get a page of AuditEvents.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
 */
@GetMapping
public ResponseEntity<List<AuditEvent>> getAll(Pageable pageable) {
    Page<AuditEvent> page = auditEventService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 15
Source Project: logistics-back   Source File: CargoReceiptController.java    License: MIT License 5 votes vote down vote up
/**
 * 查询运单状态
 */
@RequestMapping(value = "/select/{backBillState}", method = RequestMethod.GET)
public Result selectByEvent(@PathVariable("backBillState") String backBillState, @RequestParam("pageNum") int pageNum, @RequestParam("limit") int limit) {
	Pageable pageable = PageRequest.of(pageNum-1, limit);
	Page<CargoReceipt> page = cargoReceiptService.selectByEvent(backBillState, pageable);
	Result result  = new Result(200, "SUCCESS", (int) page.getTotalElements(), page.getContent());
	return result;
}
 
Example 16
@Ignore
@Test
public void findAllUsers() {

    UserSearchForm searchForm = new UserSearchForm();
    searchForm.setSelectedLanguage(UserLanguage.ENGLISH);

    Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "firstName");
    Page<User> usersPage = userService.findAll(pageable, searchForm);
    log.debug("usersPage.getTotalElements(): {}", usersPage.getTotalElements());

    assertEquals(5, usersPage.getTotalElements());
}
 
Example 17
Source Project: tutorials   Source File: StudentDirectoryRestController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET, produces = "application/json")
public Page<Student> findPaginated(@RequestParam("page") int page, @RequestParam("size") int size) {

    Page<Student> resultPage = service.findPaginated(page, size);
    if (page > resultPage.getTotalPages()) {
        throw new MyResourceNotFoundException();
    }
    return resultPage;
}
 
Example 18
Source Project: spring-data-examples   Source File: IntermediateTest.java    License: MIT License 5 votes vote down vote up
public void shouldReturnPaginatedCompanies() {
  Page<Company> firstPage = companyRepository.findAll(new PageRequest(0, 2));
  assertNotNull(firstPage);
  assertEquals(firstPage.getSize(), 2);
  assertEquals(firstPage.getNumberOfElements(), 2);
  assertEquals(firstPage.getNumber(), 0);
  assertEquals(firstPage.getTotalElements(), 3);
  assertEquals(firstPage.getTotalPages(), 2);

  Page<Company> secondPage = companyRepository.findAll(new PageRequest(1, 2));
  assertEquals(secondPage.getSize(), 2);
  assertEquals(secondPage.getNumberOfElements(), 1);
  assertEquals(secondPage.getNumber(), 1);

}
 
Example 19
@Test
public void shouldReturnBooksForGivenBucketUsingTemplate() {

    template.deleteIndex(Book.class);
    template.createIndex(Book.class);
    template.putMapping(Book.class);
    template.refresh(Book.class);

    Book book1 = new Book(RandomUtil.randomString(5, 10), "test1", System.currentTimeMillis());
    Book book2 = new Book(RandomUtil.randomString(5, 10), "test2", System.currentTimeMillis());

    Map<Integer, Collection<String>> map1 = new HashMap<>();
    map1.put(1, Arrays.asList("test1", "test2"));

    Map<Integer, Collection<String>> map2 = new HashMap<>();
    map2.put(1, Arrays.asList("test3", "test4"));

    book1.setBuckets(map1);
    book2.setBuckets(map2);

    repository.saveAll(Arrays.asList(book1, book2));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.Total))
        .build();

    Page<Book> books = repository.search(searchQuery);

    Assertions.assertThat(books.getContent()).hasSize(1);
}
 
Example 20
Source Project: hawkbit   Source File: NoCountPagingRepository.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Page<T> readPage(final TypedQuery<T> query, final Pageable pageable, final Specification<T> spec) {
    query.setFirstResult((int) pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    final List<T> content = query.getResultList();

    return new PageImpl<>(content, pageable, content.size());
}
 
Example 21
Source Project: TeamDojo   Source File: BadgeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get all the badges.
 *
 * @param pageable the pagination information
 * @return the list of entities
 */
@Override
@Transactional(readOnly = true)
public Page<BadgeDTO> findAll(Pageable pageable) {
    log.debug("Request to get all Badges");
    return badgeRepository.findAll(pageable)
        .map(badgeMapper::toDto);
}
 
Example 22
/**
 * GET  /users : get all users.
 * 
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and with body all users
 * @throws URISyntaxException if the pagination headers couldnt be generated
 */
@RequestMapping(value = "/users",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(readOnly = true)
public ResponseEntity<List<ManagedUserDTO>> getAllUsers(Pageable pageable)
    throws URISyntaxException {
    Page<User> page = userRepository.findAll(pageable);
    List<ManagedUserDTO> managedUserDTOs = page.getContent().stream()
        .map(ManagedUserDTO::new)
        .collect(Collectors.toList());
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
    return new ResponseEntity<>(managedUserDTOs, headers, HttpStatus.OK);
}
 
Example 23
Source Project: spring-data-cosmosdb   Source File: PageableAddressRepositoryIT.java    License: MIT License 5 votes vote down vote up
@Test
public void testFindWithoutPartitionKeySinglePage() {
    final CosmosPageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_3, null);
    final Page<PageableAddress> page = repository.findByStreet(TestConstants.STREET, pageRequest);

    assertThat(page.getContent().size()).isEqualTo(2);
    validateResultStreetMatch(page, TestConstants.STREET);
    validateLastPage(page, page.getContent().size());
}
 
Example 24
Source Project: fullstop   Source File: ViolationRepositoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAllPage1() throws Exception {
    final Page<ViolationEntity> result = violationRepository
            .queryViolations(null, null, null, null, false, null, null, null, null, false, null, null, new PageRequest(0, 2, ASC, "id"));

    assertThat(result).isNotNull();
    assertThat(result.getTotalElements()).isEqualTo(2);
    assertThat(result.getTotalPages()).isEqualTo(1);
    assertThat(result.getNumberOfElements()).isEqualTo(2);
    assertThat(result.getContent()).extracting("id", Long.class)
            .isEqualTo(newArrayList(vio2.getId(), vio5.getId()));
    assertThat(result.getContent()).extracting("username", String.class)
            .isEqualTo(newArrayList(vio2.getUsername(), vio5.getUsername()));
}
 
Example 25
Source Project: cms   Source File: WxTagsServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Page<WxTags> getTags(Integer page, Integer size, WxTags query) {
    Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
    return tagsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
        List<Predicate> predicates = new ArrayList<>();
        if (query == null) {
            return null;
        }
        if (null != query.getName()) {
            predicates.add(criteriaBuilder.like(root.get("name").as(String.class), query.getName() + "%"));
        }

        return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
    }, pageable);
}
 
Example 26
Source Project: springBoot   Source File: PageInfo.java    License: MIT License 5 votes vote down vote up
/**
 * 获取统一分页对象
 */
public static <M> PageInfo<M> of(Page page, Class<M> entityModelClass) {
    int records = (int) page.getTotalElements();
    int pageSize = page.getSize();
    int total = records % pageSize == 0 ? records / pageSize : records / pageSize + 1;

    PageInfo<M> pageInfo = new PageInfo<>();
    pageInfo.setPage(page.getNumber() + 1);//页码
    pageInfo.setPageSize(pageSize);//页面大小
    pageInfo.setRows(CopyUtil.copyList(page.getContent(), entityModelClass));//分页结果
    pageInfo.setRecords(records);//总记录数
    pageInfo.setTotal(total);//总页数
    return pageInfo;
}
 
Example 27
Source Project: alchemy   Source File: UdfResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@code GET  /udfs} : get all the udfs.
 *
 * @param pageable the pagination information.
 * @param criteria the criteria which the requested entities should match.
 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of udfs in body.
 */
@GetMapping("/udfs")
public ResponseEntity<List<UdfDTO>> getAllUdfs(UdfCriteria criteria, Pageable pageable, @RequestParam MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder) {
    log.debug("REST request to get Udfs by criteria: {}", criteria);
    Page<UdfDTO> page = udfQueryService.findByCriteria(criteria, pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page);
    return ResponseEntity.ok().headers(headers).body(page.getContent());
}
 
Example 28
Source Project: hawkbit   Source File: JpaTargetTagManagement.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Page<TargetTag> findByRsql(final Pageable pageable, final String rsqlParam) {

    final Specification<JpaTargetTag> spec = RSQLUtility.parse(rsqlParam, TagFields.class, virtualPropertyReplacer,
            database);
    return convertTPage(targetTagRepository.findAll(spec, pageable), pageable);
}
 
Example 29
@Test
@DatabaseSetup("persistence/applications/init.xml")
void testGetApplicationsOrderBysDefault() {
    //Default to order by Updated
    final Page<Application> apps = this.service.findApplications(null, null, null, null, null, PAGEABLE);
    Assertions.assertThat(apps.getNumberOfElements()).isEqualTo(3);
    Assertions.assertThat(apps.getContent().get(0).getId()).isEqualTo(APP_3_ID);
    Assertions.assertThat(apps.getContent().get(1).getId()).isEqualTo(APP_2_ID);
    Assertions.assertThat(apps.getContent().get(2).getId()).isEqualTo(APP_1_ID);
}
 
Example 30
Source Project: youkefu   Source File: KbsTopicCommentRepositoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Page<KbsTopicComment> findByCon(
		NativeSearchQueryBuilder searchQueryBuilder, String q, int p, int ps) {
	searchQueryBuilder.withPageable(new PageRequest(p, ps)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC)) ;
	searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("content").fragmentSize(200)) ;
	if(!StringUtils.isBlank(q)){
	   	searchQueryBuilder.withQuery(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
	}
    return elasticsearchTemplate.queryForPage(searchQueryBuilder.build(), KbsTopicComment.class  , new UKResultMapper()) ;
}