org.springframework.data.domain.Page Java Examples
The following examples show how to use
org.springframework.data.domain.Page.
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: PaginationUtilUnitTest.java From cubeai with Apache License 2.0 | 7 votes |
@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 File: EkmKnowledgeTimesRepositoryImpl.java From youkefu with Apache License 2.0 | 6 votes |
@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 #3
Source File: StorageControllerTest.java From market with MIT License | 6 votes |
@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 #4
Source File: NotificationManagementController.java From zhcet-web with Apache License 2.0 | 6 votes |
@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 File: PaginationUtilUnitTest.java From TeamDojo with Apache License 2.0 | 6 votes |
@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 #6
Source File: UserResource.java From spring-cloud-gray with Apache License 2.0 | 6 votes |
@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 #7
Source File: WxTagsServiceImpl.java From cms with Apache License 2.0 | 5 votes |
@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 #8
Source File: PageInfo.java From springBoot with MIT License | 5 votes |
/** * 获取统一分页对象 */ 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 #9
Source File: CargoReceiptController.java From logistics-back with MIT License | 5 votes |
/** * 查询所有运单 */ @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 #10
Source File: PageableAddressRepositoryIT.java From spring-data-cosmosdb with MIT License | 5 votes |
@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 #11
Source File: ViolationRepositoryTest.java From fullstop with Apache License 2.0 | 5 votes |
@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 #12
Source File: EsProductServiceImpl.java From macrozheng with Apache License 2.0 | 5 votes |
@Override public Page<EsProduct> recommend(Long id, Integer pageNum, Integer pageSize) { Pageable pageable = PageRequest.of(pageNum, pageSize); List<EsProduct> esProductList = productDao.getAllEsProductList(id); if (esProductList.size() > 0) { EsProduct esProduct = esProductList.get(0); String keyword = esProduct.getName(); Long brandId = esProduct.getBrandId(); Long productCategoryId = esProduct.getProductCategoryId(); //根据商品标题、品牌、分类进行搜索 List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>(); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword), ScoreFunctionBuilders.weightFactorFunction(8))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("brandId", brandId), ScoreFunctionBuilders.weightFactorFunction(10))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("productCategoryId", productCategoryId), ScoreFunctionBuilders.weightFactorFunction(6))); FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()]; filterFunctionBuilders.toArray(builders); FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders) .scoreMode(FunctionScoreQuery.ScoreMode.SUM) .setMinScore(2); NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); builder.withQuery(functionScoreQueryBuilder); builder.withPageable(pageable); NativeSearchQuery searchQuery = builder.build(); LOGGER.info("DSL:{}", searchQuery.getQuery().toString()); return productRepository.search(searchQuery); } return new PageImpl<>(null); }
Example #13
Source File: CompanyServiceImpl.java From e with Apache License 2.0 | 5 votes |
@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 #14
Source File: KbsTopicCommentRepositoryImpl.java From youkefu with Apache License 2.0 | 5 votes |
@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()) ; }
Example #15
Source File: UserController.java From JavaQuarkBBS with Apache License 2.0 | 5 votes |
@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 #16
Source File: GoodsBillController.java From logistics-back with MIT License | 5 votes |
/** * 查询所有运单 */ @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 #17
Source File: RoleController.java From sureness with Apache License 2.0 | 5 votes |
@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 #18
Source File: BookRepositoryTest.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
@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 #19
Source File: PageableAddressRepositoryIT.java From spring-data-cosmosdb with MIT License | 5 votes |
@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 #20
Source File: JpaPersistenceServiceImplApplicationsIntegrationTest.java From genie with Apache License 2.0 | 5 votes |
@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 #21
Source File: UserResource.java From jhipster-ribbon-hystrix with GNU General Public License v3.0 | 5 votes |
/** * 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 #22
Source File: BadgeServiceImpl.java From TeamDojo with Apache License 2.0 | 5 votes |
/** * 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 #23
Source File: IntermediateTest.java From spring-data-examples with MIT License | 5 votes |
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 #24
Source File: CargoReceiptController.java From logistics-back with MIT License | 5 votes |
/** * 查询运单状态 */ @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 #25
Source File: JpaTargetTagManagement.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@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 #26
Source File: NoCountPagingRepository.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@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 #27
Source File: UserServiceTest.java From abixen-platform with GNU Lesser General Public License v2.1 | 5 votes |
@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 #28
Source File: UdfResource.java From alchemy with Apache License 2.0 | 5 votes |
/** * {@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 #29
Source File: StudentDirectoryRestController.java From tutorials with MIT License | 5 votes |
@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 #30
Source File: AuditResource.java From ehcache3-samples with Apache License 2.0 | 5 votes |
/** * 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); }