-
Notifications
You must be signed in to change notification settings - Fork 684
/
Copy pathPagedResourcesAssembler.java
309 lines (255 loc) · 11.2 KB
/
PagedResourcesAssembler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.data.web;
import static org.springframework.web.util.UriComponentsBuilder.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkRelation;
import org.springframework.hateoas.PagedModel;
import org.springframework.hateoas.PagedModel.PageMetadata;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.UriTemplate;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.hateoas.server.core.EmbeddedWrapper;
import org.springframework.hateoas.server.core.EmbeddedWrappers;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
/**
* {@link RepresentationModelAssembler} to easily convert {@link Page} instances into {@link PagedModel}.
*
* @since 1.6
* @author Oliver Gierke
* @author Nick Williams
* @author Marcel Overdijk
*/
public class PagedResourcesAssembler<T> implements RepresentationModelAssembler<Page<T>, PagedModel<EntityModel<T>>> {
private final HateoasPageableHandlerMethodArgumentResolver pageableResolver;
private final Optional<UriComponents> baseUri;
private final EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
private boolean forceFirstAndLastRels = false;
/**
* Creates a new {@link PagedResourcesAssembler} using the given {@link PageableHandlerMethodArgumentResolver} and
* base URI. If the former is {@literal null}, a default one will be created. If the latter is {@literal null}, calls
* to {@link #toModel(Page)} will use the current request's URI to build the relevant previous and next links.
*
* @param resolver can be {@literal null}.
* @param baseUri can be {@literal null}.
*/
public PagedResourcesAssembler(@Nullable HateoasPageableHandlerMethodArgumentResolver resolver,
@Nullable UriComponents baseUri) {
this.pageableResolver = resolver == null ? new HateoasPageableHandlerMethodArgumentResolver() : resolver;
this.baseUri = Optional.ofNullable(baseUri);
}
/**
* Configures whether to always add {@code first} and {@code last} links to the {@link PagedModel} created. Defaults
* to {@literal false} which means that {@code first} and {@code last} links only appear in conjunction with
* {@code prev} and {@code next} links.
*
* @param forceFirstAndLastRels whether to always add {@code first} and {@code last} links to the {@link PagedModel}
* created.
* @since 1.11
*/
public void setForceFirstAndLastRels(boolean forceFirstAndLastRels) {
this.forceFirstAndLastRels = forceFirstAndLastRels;
}
@Override
public PagedModel<EntityModel<T>> toModel(Page<T> entity) {
return toModel(entity, EntityModel::of);
}
/**
* Creates a new {@link PagedModel} by converting the given {@link Page} into a {@link PageMetadata} instance and
* wrapping the contained elements into {@link PagedModel} instances. Will add pagination links based on the given the
* self link.
*
* @param page must not be {@literal null}.
* @param selfLink must not be {@literal null}.
* @return
*/
public PagedModel<EntityModel<T>> toModel(Page<T> page, Link selfLink) {
return toModel(page, EntityModel::of, selfLink);
}
/**
* Creates a new {@link PagedModel} by converting the given {@link Page} into a {@link PageMetadata} instance and
* using the given {@link PagedModel} to turn elements of the {@link Page} into resources.
*
* @param page must not be {@literal null}.
* @param assembler must not be {@literal null}.
* @return
*/
public <R extends RepresentationModel<?>> PagedModel<R> toModel(Page<T> page,
RepresentationModelAssembler<T, R> assembler) {
return createModel(page, assembler, Optional.empty());
}
/**
* Creates a new {@link PagedModel} by converting the given {@link Page} into a {@link PageMetadata} instance and
* using the given {@link PagedModel} to turn elements of the {@link Page} into resources. Will add pagination links
* based on the given the self link.
*
* @param page must not be {@literal null}.
* @param assembler must not be {@literal null}.
* @param link must not be {@literal null}.
* @return
*/
public <R extends RepresentationModel<?>> PagedModel<R> toModel(Page<T> page,
RepresentationModelAssembler<T, R> assembler, Link link) {
Assert.notNull(link, "Link must not be null");
return createModel(page, assembler, Optional.of(link));
}
/**
* Creates a {@link PagedModel} with an empt collection {@link EmbeddedWrapper} for the given domain type.
*
* @param page must not be {@literal null}, content must be empty.
* @param type must not be {@literal null}.
* @return
* @since 2.0
*/
public PagedModel<?> toEmptyModel(Page<?> page, Class<?> type) {
return toEmptyModel(page, type, Optional.empty());
}
/**
* Creates a {@link PagedModel} with an empt collection {@link EmbeddedWrapper} for the given domain type.
*
* @param page must not be {@literal null}, content must be empty.
* @param type must not be {@literal null}.
* @param link must not be {@literal null}.
* @return
* @since 1.11
*/
public PagedModel<?> toEmptyModel(Page<?> page, Class<?> type, Link link) {
return toEmptyModel(page, type, Optional.of(link));
}
private PagedModel<?> toEmptyModel(Page<?> page, Class<?> type, Optional<Link> link) {
Assert.notNull(page, "Page must not be null");
Assert.isTrue(!page.hasContent(), "Page must not have any content");
Assert.notNull(type, "Type must not be null");
Assert.notNull(link, "Link must not be null");
PageMetadata metadata = asPageMetadata(page);
EmbeddedWrapper wrapper = wrappers.emptyCollectionOf(type);
List<EmbeddedWrapper> embedded = Collections.singletonList(wrapper);
return addPaginationLinks(PagedModel.of(embedded, metadata), page, link);
}
/**
* Creates the {@link PagedModel} to be equipped with pagination links downstream.
*
* @param resources the original page's elements mapped into {@link RepresentationModel} instances.
* @param metadata the calculated {@link PageMetadata}, must not be {@literal null}.
* @param page the original page handed to the assembler, must not be {@literal null}.
* @return must not be {@literal null}.
*/
protected <R extends RepresentationModel<?>, S> PagedModel<R> createPagedModel(List<R> resources,
PageMetadata metadata, Page<S> page) {
Assert.notNull(resources, "Content resources must not be null");
Assert.notNull(metadata, "PageMetadata must not be null");
Assert.notNull(page, "Page must not be null");
return PagedModel.of(resources, metadata);
}
private <S, R extends RepresentationModel<?>> PagedModel<R> createModel(Page<S> page,
RepresentationModelAssembler<S, R> assembler, Optional<Link> link) {
Assert.notNull(page, "Page must not be null");
Assert.notNull(assembler, "ResourceAssembler must not be null");
List<R> resources = new ArrayList<>(page.getNumberOfElements());
for (S element : page) {
resources.add(assembler.toModel(element));
}
PagedModel<R> resource = createPagedModel(resources, asPageMetadata(page), page);
return addPaginationLinks(resource, page, link);
}
private <R> PagedModel<R> addPaginationLinks(PagedModel<R> resources, Page<?> page, Optional<Link> link) {
UriTemplate base = getUriTemplate(link);
boolean isNavigable = page.hasPrevious() || page.hasNext();
if (isNavigable || forceFirstAndLastRels) {
resources.add(createLink(base, PageRequest.of(0, page.getSize(), page.getSort()), IanaLinkRelations.FIRST));
}
if (page.hasPrevious()) {
resources.add(createLink(base, page.previousPageable(), IanaLinkRelations.PREV));
}
Link selfLink = link.map(Link::withSelfRel)//
.orElseGet(() -> createLink(base, page.getPageable(), IanaLinkRelations.SELF));
resources.add(selfLink);
if (page.hasNext()) {
resources.add(createLink(base, page.nextPageable(), IanaLinkRelations.NEXT));
}
if (isNavigable || forceFirstAndLastRels) {
int lastIndex = page.getTotalPages() == 0 ? 0 : page.getTotalPages() - 1;
resources
.add(createLink(base, PageRequest.of(lastIndex, page.getSize(), page.getSort()), IanaLinkRelations.LAST));
}
return resources;
}
/**
* Returns a default URI string either from the one configured on assembler creatino or by looking it up from the
* current request.
*
* @return
*/
private UriTemplate getUriTemplate(Optional<Link> baseLink) {
return UriTemplate.of(baseLink.map(Link::getHref).orElseGet(this::baseUriOrCurrentRequest));
}
/**
* Creates a {@link Link} with the given {@link LinkRelation} that will be based on the given {@link UriTemplate} but
* enriched with the values of the given {@link Pageable} (if not {@literal null}).
*
* @param base must not be {@literal null}.
* @param pageable can be {@literal null}
* @param relation must not be {@literal null}.
* @return
*/
private Link createLink(UriTemplate base, Pageable pageable, LinkRelation relation) {
UriComponentsBuilder builder = fromUri(base.expand());
pageableResolver.enhance(builder, getMethodParameter(), pageable);
return Link.of(UriTemplate.of(builder.build().toString()), relation);
}
/**
* Return the {@link MethodParameter} to be used to potentially qualify the paging and sorting request parameters to.
* Default implementations returns {@literal null}, which means the parameters will not be qualified.
*
* @return
* @since 1.7
*/
@Nullable
protected MethodParameter getMethodParameter() {
return null;
}
/**
* Creates a new {@link PageMetadata} instance from the given {@link Page}.
*
* @param page must not be {@literal null}.
* @return
*/
private PageMetadata asPageMetadata(Page<?> page) {
Assert.notNull(page, "Page must not be null");
int number = pageableResolver.isOneIndexedParameters() ? page.getNumber() + 1 : page.getNumber();
return new PageMetadata(page.getSize(), number, page.getTotalElements(), page.getTotalPages());
}
private String baseUriOrCurrentRequest() {
return baseUri.map(Object::toString).orElseGet(PagedResourcesAssembler::currentRequest);
}
private static String currentRequest() {
return ServletUriComponentsBuilder.fromCurrentRequest().build().toString();
}
}