Java Code Examples for org.springframework.data.domain.Page#hasNext()

The following examples show how to use org.springframework.data.domain.Page#hasNext() . 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: PageableMemoRepositoryIT.java    From spring-data-cosmosdb with MIT License 6 votes vote down vote up
private Set<PageableMemo> findAllWithPageSize(int pageSize) {
    final CosmosPageRequest pageRequest = new CosmosPageRequest(0, pageSize, null);
    Page<PageableMemo> page = repository.findAll(pageRequest);
    final Set<PageableMemo> outputSet = new HashSet<>(page.getContent());
    while (page.hasNext()) {
        final Pageable pageable = page.nextPageable();
        page = repository.findAll(pageable);
        outputSet.addAll((page.getContent()));
    }
    return outputSet;
}
 
Example 2
Source File: PageablePersonRepositoryIT.java    From spring-data-cosmosdb with MIT License 6 votes vote down vote up
private Set<PageablePerson> findAllWithPageSize(int pageSize, boolean checkContentLimit) {
    final CosmosPageRequest pageRequest = new CosmosPageRequest(0, pageSize, null);
    Page<PageablePerson> page = repository.findAll(pageRequest);
    final Set<PageablePerson> outputSet = new HashSet<>(page.getContent());
    if (checkContentLimit) {
        //  Make sure CosmosDB returns less number of documents than requested
        //  This will verify the functionality of new pagination implementation
        assertThat(page.getContent().size()).isLessThan(pageSize);
    }
    while (page.hasNext()) {
        final Pageable pageable = page.nextPageable();
        page = repository.findAll(pageable);
        outputSet.addAll((page.getContent()));
    }
    return outputSet;
}
 
Example 3
Source File: PageLinksAspect.java    From Showcase with Apache License 2.0 6 votes vote down vote up
@Around("@annotation(org.educama.common.api.resource.PageLinks) && execution(org.springframework.hateoas.ResourceSupport+ *(..)) && args(page, ..)")
public Object pageLinksAdvice(ProceedingJoinPoint joinPoint, Page<?> page) throws Throwable {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    PageLinks pageLinks = method.getAnnotation(PageLinks.class);
    Class<?> controller = pageLinks.value();
    UriComponentsBuilder original = originalUri(controller, request);
    ResourceSupport resourceSupport = (ResourceSupport) joinPoint.proceed();
    if (page.hasNext()) {
        UriComponentsBuilder nextBuilder = replacePageParams(original, page.nextPageable());
        resourceSupport.add(new Link(nextBuilder.toUriString()).withRel("next"));
    }
    if (page.hasPrevious()) {
        UriComponentsBuilder prevBuilder = replacePageParams(original, page.previousPageable());
        resourceSupport.add(new Link(prevBuilder.toUriString()).withRel("prev"));
    }
    return resourceSupport;
}
 
Example 4
Source File: SongResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Produces("application/json")
@Path("/all")
public String all() {
    Pageable wholePage = Pageable.unpaged();
    Page<Song> page = songRepository.findAll(wholePage);
    return page.hasPrevious() + " - " + page.hasNext() + " / " + page.getNumberOfElements();
}
 
Example 5
Source File: SongResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Produces("application/json")
@Path("/page/{num}/{size}")
public String songs(@PathParam("num") int pageNum, @PathParam("size") int pageSize) {
    PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
    Page<Song> page = songRepository.findAll(pageRequest);
    return page.hasPrevious() + " - " + page.hasNext() + " / " + page.getNumberOfElements();
}
 
Example 6
Source File: MovieResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/customFind/page/{size}/{num}")
public String customFind(@PathParam("size") int pageSize, @PathParam("num") int pageNum) {
    Page<Movie> page = movieRepository.customFind(
            PageRequest.of(pageNum, pageSize, Sort.Direction.ASC, "title"));
    return page.hasNext() + " / " + page.getNumberOfElements();
}
 
Example 7
Source File: SpiderSymptomService.java    From Doctor with Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
    Pageable pageable = new PageRequest(0,1000,Sort.Direction.ASC,"id");
    Page<NameHref> nameHrefs = nameHrefRepository.findAll(pageable);
    while (nameHrefs.hasNext()){
        for (NameHref nameHref : nameHrefs.getContent()){
            if (nameHref.getId()>398112){
                spider(nameHref.getHref(),nameHref.getName());
            }else{
                spider(nameHref.getName(),nameHref.getHref());
            }
        }
        nameHrefs = nameHrefRepository.findAll(pageable = pageable.next());
    }
}
 
Example 8
Source File: MedicalRepositoryTest.java    From Doctor with Apache License 2.0 5 votes vote down vote up
@Test
public void test2() throws IOException {
    int page = 0;
    Sort sort = new Sort(Sort.Direction.ASC, "id");
    Page<Msymptom> msymptomPage = msymptomRepository.findAll(new PageRequest(page++, 1000, sort));
    //写入txt文件
    write(msymptomPage.getContent(),path2);
    while (msymptomPage.hasNext()) {
        //再读取一页
        msymptomPage = msymptomRepository.findAll(new PageRequest(page++, 1000, sort));
        //写入Tet文件
        write(msymptomPage.getContent(),path2);
    }
}
 
Example 9
Source File: BotNodeUpdata.java    From Doctor with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    int size = 1000;//每页1000条
    Sort sort = new Sort(Sort.Direction.ASC, "id");
    Pageable pageable = new PageRequest(0, size, sort);
    Page<Medical> medicalPage = getMedicals(pageable);
    //如果还有下一页
    while (medicalPage.hasNext()) {
        medicalPage = getMedicals(pageable = pageable.next());
    }
    logger.info("操作完成");
}
 
Example 10
Source File: PageResponseBodyAdvisor.java    From spring-boot-jpa with Apache License 2.0 5 votes vote down vote up
private Optional<String> getHttpHeaderLinksString(ServerHttpRequest request, Page<?> page) {
	List<String> headerLinks = new ArrayList<>();

	if (!page.isFirst()) {
		headerLinks.add(String.format(LINK_STANDARD_FMT, UriComponentsBuilder.fromHttpRequest(request)
				.replaceQueryParam(QUERY_PARAM_PAGE, 0)
				.build(), LINK_HEADER_FIRST));
	}

	if (page.hasPrevious()) {
		headerLinks.add(String.format(LINK_STANDARD_FMT, UriComponentsBuilder.fromHttpRequest(request)
				.replaceQueryParam(QUERY_PARAM_PAGE, page.previousPageable().getPageNumber())
				.build(), LINK_HEADER_PREVIOUS));
	}

	if (page.hasNext()) {
		headerLinks.add(String.format(LINK_STANDARD_FMT, UriComponentsBuilder.fromHttpRequest(request)
				.replaceQueryParam(QUERY_PARAM_PAGE, page.nextPageable().getPageNumber())
				.build(), LINK_HEADER_NEXT));
	}

	if (!page.isLast()) {
		headerLinks.add(String.format(LINK_STANDARD_FMT, UriComponentsBuilder.fromHttpRequest(request)
				.replaceQueryParam(QUERY_PARAM_PAGE, page.getTotalPages() - 1)
				.build(), LINK_HEADER_LAST));
	}

	return Optional.of(StringUtils.join(headerLinks, ", "));
}
 
Example 11
Source File: FullPaginationDecorator.java    From thymeleaf-spring-data-dialect with Apache License 2.0 5 votes vote down vote up
private String getNextPageLink(Page<?> page, final ITemplateContext context) {
    String msgKey = page.hasNext() ? "next.page.link" : "next.page";
    Locale locale = context.getLocale();
    int nextPage = page.getNumber() + 1;
    String link = PageUtils.createPageUrl(context, nextPage);

    return Messages.getMessage(BUNDLE_NAME, msgKey, locale, link);
}
 
Example 12
Source File: SimpleHazelcastRepositoryIT.java    From spring-data-hazelcast with Apache License 2.0 5 votes vote down vote up
@Test
public void findAll_Pageable() {
    Set<String> yearsExpected = new TreeSet<>();
    for (Object[] datum : TestData.bestMakeUp) {
        yearsExpected.add(datum[0].toString());
    }

    Pageable pageRequest = PageRequest.of(PAGE_0, SIZE_10);

    Page<Makeup> pageResponse = this.theRepository.findAll(pageRequest);
    int page = 0;
    while (pageResponse != null) {
        assertThat("Page " + page + ", has content", pageResponse.hasContent(), equalTo(true));

        List<Makeup> makeups = pageResponse.getContent();
        assertThat("Page " + page + ", has makeups", makeups.size(), greaterThan(0));

        for (Makeup makeup : makeups) {
            assertThat(makeup.toString(), yearsExpected.contains(makeup.getId()), equalTo(true));
            yearsExpected.remove(makeup.getId());
        }

        if (pageResponse.hasNext()) {
            pageRequest = pageResponse.nextPageable();
            pageResponse = this.theRepository.findAll(pageRequest);
        } else {
            pageResponse = null;
        }
        page++;
    }

    assertThat("All years matched", yearsExpected, hasSize(0));
}
 
Example 13
Source File: SpringDataWithSecurityIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenAppUser_whenLoginSuccessful_shouldReadMyPagedTweets() {
    AppUser appUser = userRepository.findByUsername("[email protected]");
    Authentication auth = new UsernamePasswordAuthenticationToken(new AppUserPrincipal(appUser), null, DummyContentUtil.getAuthorities());
    SecurityContextHolder.getContext()
        .setAuthentication(auth);
    Page<Tweet> page = null;
    do {
        page = tweetRepository.getMyTweetsAndTheOnesILiked(PageRequest.of(page != null ? page.getNumber() + 1 : 0, 5));
        for (Tweet twt : page.getContent()) {
            isTrue((twt.getOwner() == appUser.getUsername()) || (twt.getLikes()
                .contains(appUser.getUsername())), "I do not have any Tweets");
        }
    } while (page.hasNext());
}
 
Example 14
Source File: SpringDataWithSecurityIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = InvalidDataAccessApiUsageException.class)
public void givenNoAppUser_whenPaginatedResultsRetrievalAttempted_shouldFail() {
    Page<Tweet> page = null;
    do {
        page = tweetRepository.getMyTweetsAndTheOnesILiked(PageRequest.of(page != null ? page.getNumber() + 1 : 0, 5));
    } while (page != null && page.hasNext());
}
 
Example 15
Source File: PersonResource.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@GET
@Path("/name/joinedOrder/{name}/page/{size}/{num}")
public String byNamePage(@PathParam("name") String name, @PathParam("size") int pageSize, @PathParam("num") int pageNum) {
    Page<Person> page = personRepository.findByNameOrderByJoined(name, PageRequest.of(pageNum, pageSize));
    return page.hasPrevious() + " - " + page.hasNext() + " / " + page.getNumberOfElements();
}
 
Example 16
Source File: SimpleTaskExplorerTests.java    From spring-cloud-task with Apache License 2.0 4 votes vote down vote up
private void verifyPageResults(Pageable pageable, int totalNumberOfExecs) {
	Map<Long, TaskExecution> expectedResults = createSampleDataSet(
			totalNumberOfExecs);
	List<Long> sortedExecIds = getSortedOfTaskExecIds(expectedResults);
	Iterator<Long> expectedTaskExecutionIter = sortedExecIds.iterator();
	// Verify pageable totals
	Page<TaskExecution> taskPage = this.taskExplorer.findAll(pageable);
	int pagesExpected = (int) Math
			.ceil(totalNumberOfExecs / ((double) pageable.getPageSize()));
	assertThat(taskPage.getTotalPages())
			.as("actual page count return was not the expected total")
			.isEqualTo(pagesExpected);
	assertThat(taskPage.getTotalElements())
			.as("actual element count was not the expected count")
			.isEqualTo(totalNumberOfExecs);

	// Verify pagination
	Pageable actualPageable = PageRequest.of(0, pageable.getPageSize());
	boolean hasMorePages = taskPage.hasContent();
	int pageNumber = 0;
	int elementCount = 0;
	while (hasMorePages) {
		taskPage = this.taskExplorer.findAll(actualPageable);
		hasMorePages = taskPage.hasNext();
		List<TaskExecution> actualTaskExecutions = taskPage.getContent();
		int expectedPageSize = pageable.getPageSize();
		if (!hasMorePages && pageable.getPageSize() != actualTaskExecutions.size()) {
			expectedPageSize = totalNumberOfExecs % pageable.getPageSize();
		}
		assertThat(actualTaskExecutions.size()).as(String.format(
				"Element count on page did not match on the %n page", pageNumber))
				.isEqualTo(expectedPageSize);
		for (TaskExecution actualExecution : actualTaskExecutions) {
			assertThat(actualExecution.getExecutionId())
					.as(String.format("Element on page %n did not match expected",
							pageNumber))
					.isEqualTo((long) expectedTaskExecutionIter.next());
			TestVerifierUtils.verifyTaskExecution(
					expectedResults.get(actualExecution.getExecutionId()),
					actualExecution);
			elementCount++;
		}
		actualPageable = taskPage.nextPageable();
		pageNumber++;
	}
	// Verify actual totals
	assertThat(pageNumber).as("Pages processed did not equal expected")
			.isEqualTo(pagesExpected);
	assertThat(elementCount).as("Elements processed did not equal expected,")
			.isEqualTo(totalNumberOfExecs);
}