All Downloads are FREE. Search and download functionalities are using the official Maven repository.

it.contactlab.hub.sdk.java.models.Paginated Maven / Gradle / Ivy

There is a newer version: 1.8.0
Show newest version
package it.contactlab.hub.sdk.java.models;

import it.contactlab.hub.sdk.java.exceptions.ApiException;
import it.contactlab.hub.sdk.java.exceptions.HttpException;
import it.contactlab.hub.sdk.java.exceptions.ServerException;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;

public class Paginated {

  private final Paged pagedElements;
  private final Function> requestFunction;

  public Paginated(Paged pagedElements,
                   Function> requestFunction) {
    this.pagedElements = pagedElements;
    this.requestFunction = requestFunction;
  }

  public List elements() {
    return pagedElements.elements();
  }

  public Page page() {
    return pagedElements.page();
  }

  /**
   * Retrieves the next page, if available.
   */
  public Optional> nextPage() throws HttpException,
      ServerException, ApiException {
    if (page().number().equals(page().totalPages())) {
      return Optional.empty();
    }

    return Optional.of(request(page().number() + 1));
  }

  /**
   * Retrieves the previous page, if available.
   */
  public Optional> previousPage() throws HttpException,
      ServerException, ApiException {
    if (page().number().equals(0)) {
      return Optional.empty();
    }

    return Optional.of(request(page().number() - 1));
  }

  private Paginated request(Integer pageNumber) throws HttpException,
      ServerException, ApiException {
    try {
      return requestFunction.apply(pageNumber);
    } catch (RuntimeException exception) {
      if (exception.getCause() instanceof HttpException) {
        throw (HttpException) exception.getCause();
      } else if (exception.getCause() instanceof ServerException) {
        throw (ServerException) exception.getCause();
      } else if (exception.getCause() instanceof ApiException) {
        throw (ApiException) exception.getCause();
      } else {
        throw exception;
      }
    }
  }

  @Override
  public String toString() {
    return "Paginated{"
      + "page=" + page()
      + ", elements=" + elements()
      + "}";
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy