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

org.sourcelab.github.client.request.PageOptions Maven / Gradle / Ivy

The newest version!
package org.sourcelab.github.client.request;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PageOptions {
    private final int page;
    private final int perPage;

    public PageOptions() {
        this(1, 30);
    }

    public PageOptions(final int page, final int perPage) {
        this.page = page;
        this.perPage = perPage;
    }

    public int getPage() {
        return page;
    }

    public int getPerPage() {
        return perPage;
    }

    /**
     * Parses the given url and creates a PageOptions instance from the parameters.
     *
     * @param url The url to parse for per_page and page parameters.
     * @return PageOptions instance populated from the supplied url.
     * @throws IllegalArgumentException if passed an invalid url.
     */
    public static PageOptions fromUrl(final String url) {
        Objects.requireNonNull(url);

        final Pattern perPagePattern = Pattern.compile(".*[?&]per_page=([0-9]+).*");
        final Pattern pagePattern = Pattern.compile(".*[?&]page=([0-9]+).*");

        Integer perPage = null;
        Integer page = null;

        final Matcher perPageMatcher = perPagePattern.matcher(url);
        if (perPageMatcher.matches() && perPageMatcher.groupCount() == 1) {
            perPage = Integer.parseInt(perPageMatcher.group(1));
        }

        final Matcher pageMatcher = pagePattern.matcher(url);
        if (pageMatcher.matches() && pageMatcher.groupCount() == 1) {
            page = Integer.parseInt(pageMatcher.group(1));
        }

        if (perPage == null || page == null) {
            throw new IllegalArgumentException("Unable to parse url " + url);
        }

        return new PageOptions(page, perPage);
    }

    @Override
    public String toString() {
        return "PageOptions{"
            + "\n\tpage=" + page
            + "\n\tperPage=" + perPage
            + "\n}";
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy