1 /*
2 * Copyright 2016-2020 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.springframework.data.repository.support;
17
18 import lombok.experimental.UtilityClass;
19
20 import java.util.List;
21 import java.util.function.LongSupplier;
22
23 import org.springframework.data.domain.Page;
24 import org.springframework.data.domain.PageImpl;
25 import org.springframework.data.domain.Pageable;
26 import org.springframework.util.Assert;
27
28 /**
29 * Support for query execution using {@link Pageable}. Using {@link PageableExecutionUtils} assumes that data queries
30 * are cheaper than {@code COUNT} queries and so some cases can take advantage of optimizations.
31 *
32 * @author Mark Paluch
33 * @author Oliver Gierke
34 * @author Christoph Strobl
35 * @since 1.13
36 */
37 @UtilityClass
38 public class PageableExecutionUtils {
39
40 /**
41 * Constructs a {@link Page} based on the given {@code content}, {@link Pageable} and {@link Supplier} applying
42 * optimizations. The construction of {@link Page} omits a count query if the total can be determined based on the
43 * result size and {@link Pageable}.
44 *
45 * @param content must not be {@literal null}.
46 * @param pageable must not be {@literal null}.
47 * @param totalSupplier must not be {@literal null}.
48 * @return the {@link Page}.
49 */
50 public static <T> Page<T> getPage(List<T> content, Pageable pageable, LongSupplier totalSupplier) {
51
52 Assert.notNull(content, "Content must not be null!");
53 Assert.notNull(pageable, "Pageable must not be null!");
54 Assert.notNull(totalSupplier, "TotalSupplier must not be null!");
55
56 if (pageable.isUnpaged() || pageable.getOffset() == 0) {
57
58 if (pageable.isUnpaged() || pageable.getPageSize() > content.size()) {
59 return new PageImpl<>(content, pageable, content.size());
60 }
61
62 return new PageImpl<>(content, pageable, totalSupplier.getAsLong());
63 }
64
65 if (content.size() != 0 && pageable.getPageSize() > content.size()) {
66 return new PageImpl<>(content, pageable, pageable.getOffset() + content.size());
67 }
68
69 return new PageImpl<>(content, pageable, totalSupplier.getAsLong());
70 }
71 }
72