PaginationUtils.java

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.httpv2.util;

import org.apache.doris.common.Pair;
import org.apache.doris.httpv2.exception.BadRequestException;

import com.google.common.base.Strings;
import jakarta.servlet.http.HttpServletRequest;

public final class PaginationUtils {
    private static final String PARAM_LIMIT = "limit";
    private static final String PARAM_OFFSET = "offset";

    private PaginationUtils() {
    }

    /**
     * Return the half-open range to use when paging a list with limit and offset query parameters.
     */
    public static Pair<Integer, Integer> getPageRange(HttpServletRequest request, int itemCount) {
        String limitString = request.getParameter(PARAM_LIMIT);
        String offsetString = request.getParameter(PARAM_OFFSET);

        if (Strings.isNullOrEmpty(limitString)) {
            if (!Strings.isNullOrEmpty(offsetString)) {
                throw new BadRequestException("Param offset should be set with param limit");
            }
            return Pair.of(0, Math.max(itemCount, 0));
        }

        long limit = parseNonNegativeLong(limitString, PARAM_LIMIT);
        long offset = Strings.isNullOrEmpty(offsetString)
                ? 0 : parseNonNegativeLong(offsetString, PARAM_OFFSET);
        int size = Math.max(itemCount, 0);
        if (offset >= size) {
            return Pair.of(size, size);
        }

        int fromIndex = (int) offset;
        int pageSize = (int) Math.min(limit, (long) size - fromIndex);
        return Pair.of(fromIndex, fromIndex + pageSize);
    }

    private static long parseNonNegativeLong(String value, String parameterName) {
        try {
            long parsedValue = Long.parseLong(value);
            if (parsedValue >= 0) {
                return parsedValue;
            }
        } catch (NumberFormatException ignored) {
            // Converted to a stable bad-request response below.
        }
        throw new BadRequestException("Param " + parameterName + " should be a non-negative integer");
    }
}