Skip to content

Instantly share code, notes, and snippets.

@gronono
Created November 5, 2019 05:37
Show Gist options
  • Save gronono/302cc14e080c5d4021952723ddcf8cb7 to your computer and use it in GitHub Desktop.
Save gronono/302cc14e080c5d4021952723ddcf8cb7 to your computer and use it in GitHub Desktop.
package nc.unc.trec.progression.batch;
import java.util.Optional;
import java.util.function.Function;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Utility class for browsing Spring's {@link Page} and fetch the next one when is required.
*/
@Slf4j
@RequiredArgsConstructor
public class Paginator<T> {
private final Function<Pageable, Page<T>> nextPageFct;
private final int pageSize;
private int currentIndex;
private Page<T> currentPage;
public Optional<T> next() {
if (currentIndex % pageSize == 0) {
if (currentPage != null && currentPage.isLast()) {
// last page => don't fetch the next one
return Optional.empty();
}
currentPage = readNextPage();
currentIndex = 0;
}
if (currentIndex < currentPage.getNumberOfElements()) {
T next = currentPage.getContent().get(currentIndex);
log.debug("Next {} : {}", currentIndex, next);
currentIndex++;
return Optional.of(next);
} else {
log.debug("Finish");
return Optional.empty();
}
}
private Page<T> readNextPage() {
Pageable nextPageable = Optional.ofNullable(currentPage)
.map(last -> last.nextPageable())
.orElseGet(() -> PageRequest.of(0, pageSize));
log.info("Reading next page {}", nextPageable.getPageNumber() + 1);
Page<T> nextPage = nextPageFct.apply(nextPageable);
log.debug("Page {}/{}, last={}, items={}", nextPage.getNumber() + 1, nextPage.getTotalPages(), nextPage.isLast(), nextPage.getNumberOfElements());
return nextPage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment