RestResponsePage.java

  1. package no.nav.data.common.rest;

  2. import com.fasterxml.jackson.annotation.JsonPropertyOrder;
  3. import io.swagger.v3.oas.annotations.Parameter;
  4. import lombok.AllArgsConstructor;
  5. import lombok.Getter;
  6. import no.nav.data.common.utils.StreamUtils;
  7. import org.springframework.data.domain.Page;

  8. import java.util.List;
  9. import java.util.function.Function;

  10. @Getter
  11. @AllArgsConstructor
  12. @JsonPropertyOrder({"pageNumber", "pageSize", "pages", "numberOfElements", "totalElements", "paged", "content"})
  13. public class RestResponsePage<T> {

  14.     private final long pageNumber;
  15.     private final long pageSize;
  16.     private final long pages;
  17.     private final long numberOfElements;
  18.     private final long totalElements;
  19.     @Parameter(description = "False if operation always returns all elements")
  20.     private final boolean paged;
  21.     private final List<T> content;

  22.     public RestResponsePage(Page<T> page) {
  23.         this.content = page.getContent();
  24.         this.pageNumber = page.getNumber();
  25.         this.pageSize = page.getSize();
  26.         this.pages = page.getTotalPages();
  27.         this.numberOfElements = page.getNumberOfElements();
  28.         this.totalElements = page.getTotalElements();
  29.         this.paged = true;
  30.     }

  31.     public RestResponsePage() {
  32.         this(List.of());
  33.     }

  34.     public RestResponsePage(List<T> content) {
  35.         this(content, content.size());
  36.     }

  37.     public RestResponsePage(List<T> content, long totalResults) {
  38.         this.content = content;
  39.         this.pageNumber = 0L;
  40.         this.pages = 1L;
  41.         this.pageSize = content.size();
  42.         this.numberOfElements = content.size();
  43.         this.totalElements = totalResults;
  44.         this.paged = false;
  45.     }

  46.     public <R> RestResponsePage<R> convert(Function<T, R> converter) {
  47.         return new RestResponsePage<>(pageNumber, pageSize, pages, numberOfElements, totalElements, paged, StreamUtils.convert(content, converter));
  48.     }
  49. }