-
Notifications
You must be signed in to change notification settings - Fork 472
/
Copy pathTraverson.java
537 lines (423 loc) · 15.4 KB
/
Traverson.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
/*
* Copyright 2013-2024 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.hateoas.client;
import static org.springframework.http.HttpMethod.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.UriTemplate;
import org.springframework.hateoas.client.Rels.Rel;
import org.springframework.hateoas.mediatype.hal.HalLinkDiscoverer;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.plugin.core.PluginRegistry;
import org.springframework.util.Assert;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import com.jayway.jsonpath.JsonPath;
/**
* Component to ease traversing hypermedia APIs by following links with relation types. Highly inspired by the equally
* named JavaScript library.
*
* @see https://github.com/basti1302/traverson
* @author Oliver Gierke
* @author Dietrich Schulten
* @author Greg Turnquist
* @author Tom Bunting
* @author Manish Misra
* @author Michael Wirth
* @since 0.11
*/
public class Traverson {
private static final TraversonDefaults DEFAULTS;
static {
List<TraversonDefaults> ALL_DEFAULTS = SpringFactoriesLoader.loadFactories(TraversonDefaults.class,
Traverson.class.getClassLoader());
Assert.isTrue(ALL_DEFAULTS.size() == 1,
() -> String.format("Expected to find only one TraversonDefaults instance, but found: %s", //
ALL_DEFAULTS.stream() //
.map(Object::getClass) //
.map(Class::getName) //
.collect(Collectors.joining(", "))));
DEFAULTS = ALL_DEFAULTS.get(0);
}
private final URI baseUri;
private final List<MediaType> mediaTypes;
private RestOperations operations;
private LinkDiscoverers discoverers;
/**
* Creates a new {@link Traverson} interacting with the given base URI and using the given {@link MediaType}s to
* interact with the service.
*
* @param baseUri must not be {@literal null}.
* @param mediaTypes must not be {@literal null} or empty.
*/
public Traverson(URI baseUri, MediaType... mediaTypes) {
this(baseUri, Arrays.asList(mediaTypes));
}
/**
* Creates a new {@link Traverson} interacting with the given base URI and using the given {@link MediaType}s to
* interact with the service.
*
* @param baseUri must not be {@literal null}.
* @param mediaTypes must not be {@literal null} or empty.
*/
public Traverson(URI baseUri, List<MediaType> mediaTypes) {
Assert.notNull(baseUri, "Base URI must not be null!");
Assert.notEmpty(mediaTypes, "At least one media type must be given!");
this.mediaTypes = mediaTypes;
this.baseUri = baseUri;
setLinkDiscoverers(DEFAULTS.getLinkDiscoverers(mediaTypes));
setRestOperations(createDefaultTemplate(this.mediaTypes));
}
/**
* Returns all {@link HttpMessageConverter}s that will be registered for the given {@link MediaType}s by default.
*
* @param mediaTypes must not be {@literal null}.
* @return
*/
public static List<HttpMessageConverter<?>> getDefaultMessageConverters(MediaType... mediaTypes) {
return DEFAULTS.getHttpMessageConverters(Arrays.asList(mediaTypes));
}
private static RestOperations createDefaultTemplate(List<MediaType> mediaTypes) {
RestTemplate template = new RestTemplate();
template.setMessageConverters(DEFAULTS.getHttpMessageConverters(mediaTypes));
return template;
}
/**
* Configures the {@link RestOperations} to use. If {@literal null} is provided a default {@link RestTemplate} will be
* used.
*
* @param operations
* @return
*/
public Traverson setRestOperations(@Nullable RestOperations operations) {
this.operations = operations == null //
? createDefaultTemplate(this.mediaTypes) //
: operations;
return this;
}
/**
* Sets the {@link LinkDiscoverers} to use. By default a single {@link HalLinkDiscoverer} is registered. If
* {@literal null} is provided the default is reapplied.
*
* @param discoverer can be {@literal null}.
* @return
*/
public Traverson setLinkDiscoverers(@Nullable List<? extends LinkDiscoverer> discoverer) {
List<? extends LinkDiscoverer> defaultedDiscoverers = discoverer == null //
? DEFAULTS.getLinkDiscoverers(mediaTypes) //
: discoverer;
this.discoverers = new LinkDiscoverers(PluginRegistry.of(defaultedDiscoverers));
return this;
}
/**
* Sets up a {@link TraversalBuilder} to follow the given rels.
*
* @param rels must not be {@literal null} or empty.
* @return
* @see TraversalBuilder
*/
public TraversalBuilder follow(String... rels) {
return new TraversalBuilder().follow(rels);
}
/**
* Sets up a {@link TraversalBuilder} for a single rel with customized details.
*
* @param hop must not be {@literal null}
* @return
*/
public TraversalBuilder follow(Hop hop) {
return new TraversalBuilder().follow(hop);
}
private HttpEntity<?> prepareRequest(HttpHeaders headers) {
HttpHeaders toSend = new HttpHeaders();
toSend.putAll(headers);
if (headers.getAccept().isEmpty()) {
toSend.setAccept(mediaTypes);
}
return new HttpEntity<Void>(toSend);
}
/**
* Builder API to customize traversals.
*
* @author Oliver Gierke
*/
public class TraversalBuilder {
private static final String MEDIA_TYPE_HEADER_NOT_FOUND = "Response for request to %s did not expose a content type! Unable to identify links!";
private static final String LINK_NOT_FOUND = "Expected to find link with rel '%s' in response %s!";
private final List<Hop> rels = new ArrayList<>();
private Map<String, Object> templateParameters = new HashMap<>();
private HttpHeaders headers = new HttpHeaders();
private TraversalBuilder() {}
/**
* Follows the given rels one by one, which means a request per rel to discover the next resource with the rel in
* line.
*
* @param rels must not be {@literal null}.
* @return
*/
public TraversalBuilder follow(String... rels) {
Assert.notNull(rels, "Rels must not be null!");
Arrays.stream(rels) //
.map(Hop::rel) //
.forEach(this.rels::add);
return this;
}
/**
* Follows the given rels one by one, which means a request per rel to discover the next resource with the rel in
* line.
*
* @param hop must not be {@literal null}.
* @return
* @see Hop#rel(String)
*/
public TraversalBuilder follow(Hop hop) {
Assert.notNull(hop, "Hop must not be null!");
this.rels.add(hop);
return this;
}
/**
* Adds the given operations parameters to the traversal. If a link discovered by the traversal is templated, the
* given parameters will be used to expand the operations into a resolvable URI.
*
* @param parameters can be {@literal null}.
* @return
*/
public TraversalBuilder withTemplateParameters(Map<String, Object> parameters) {
Assert.notNull(parameters, "Parameters must not be null!");
this.templateParameters = parameters;
return this;
}
/**
* The {@link HttpHeaders} that shall be used for the requests of the traversal.
*
* @param headers can be {@literal null}.
* @return
*/
public TraversalBuilder withHeaders(HttpHeaders headers) {
Assert.notNull(headers, "Headers must not be null!");
this.headers = headers;
return this;
}
/**
* Executes the traversal and marshals the final response into an object of the given type.
*
* @param type must not be {@literal null}.
* @return
*/
@Nullable
public <T> T toObject(Class<T> type) {
Assert.notNull(type, "Target type must not be null!");
URIAndHeaders uriAndHeaders = traverseToExpandedFinalUrl();
HttpEntity<?> requestEntity = prepareRequest(mergeHeaders(this.headers, uriAndHeaders.getHttpHeaders()));
return operations.exchange(uriAndHeaders.getUri(), GET, requestEntity, type).getBody();
}
/**
* Executes the traversal and marshals the final response into an object of the given
* {@link ParameterizedTypeReference}.
*
* @param type must not be {@literal null}.
* @return
*/
@Nullable
public <T> T toObject(ParameterizedTypeReference<T> type) {
Assert.notNull(type, "Target type must not be null!");
URIAndHeaders uriAndHeaders = traverseToExpandedFinalUrl();
HttpEntity<?> requestEntity = prepareRequest(mergeHeaders(this.headers, uriAndHeaders.getHttpHeaders()));
return operations.exchange(uriAndHeaders.getUri(), GET, requestEntity, type).getBody();
}
/**
* Executes the traversal and returns the result of the given JSON Path expression evaluated against the final
* representation.
*
* @param jsonPath must not be {@literal null} or empty.
* @return
*/
public <T> T toObject(String jsonPath) {
Assert.hasText(jsonPath, "JSON path must not be null or empty!");
URIAndHeaders uriAndHeaders = traverseToExpandedFinalUrl();
HttpEntity<?> requestEntity = prepareRequest(mergeHeaders(this.headers, uriAndHeaders.getHttpHeaders()));
String forObject = operations.exchange(uriAndHeaders.getUri(), GET, requestEntity, String.class).getBody();
return JsonPath.read(forObject, jsonPath);
}
/**
* Returns the raw {@link ResponseEntity} with the representation unmarshalled into an instance of the given type.
*
* @param type must not be {@literal null}.
* @return
*/
public <T> ResponseEntity<T> toEntity(Class<T> type) {
Assert.notNull(type, "Target type must not be null!");
URIAndHeaders uriAndHeaders = traverseToExpandedFinalUrl();
HttpEntity<?> requestEntity = prepareRequest(mergeHeaders(this.headers, uriAndHeaders.getHttpHeaders()));
return operations.exchange(uriAndHeaders.getUri(), GET, requestEntity, type);
}
/**
* Returns the {@link Link} found for the last rel in the rels configured to follow. Will expand the final
* {@link Link} using the
*
* @return
* @see #withTemplateParameters(Map)
* @since 0.15
*/
public Link asLink() {
return traverseToLink(true);
}
/**
* Returns the templated {@link Link} found for the last relation in the rels configured to follow.
*
* @return
* @since 0.17
*/
public Link asTemplatedLink() {
return traverseToLink(false);
}
private Link traverseToLink(boolean expandFinalUrl) {
Assert.isTrue(!rels.isEmpty(), "At least one rel needs to be provided!");
return Link.of(expandFinalUrl ? traverseToExpandedFinalUrl().getUri().toString() : traverseToFinalUrl().getUri(),
rels.get(rels.size() - 1).getRel());
}
private UriStringAndHeaders traverseToFinalUrl() {
UriStringAndHeaders uriAndHeaders = getAndFindLinkWithRel(baseUri.toString(), rels.iterator(), HttpHeaders.EMPTY);
return new UriStringAndHeaders(UriTemplate.of(uriAndHeaders.getUri()).toString(), uriAndHeaders.getHttpHeaders());
}
private URIAndHeaders traverseToExpandedFinalUrl() {
UriStringAndHeaders uriAndHeaders = getAndFindLinkWithRel(baseUri.toString(), rels.iterator(), HttpHeaders.EMPTY);
return new URIAndHeaders(UriTemplate.of(uriAndHeaders.getUri()).expand(templateParameters),
uriAndHeaders.getHttpHeaders());
}
private UriStringAndHeaders getAndFindLinkWithRel(String uri, Iterator<Hop> rels, HttpHeaders extraHeaders) {
if (!rels.hasNext()) {
return new UriStringAndHeaders(uri, extraHeaders);
}
HttpEntity<?> request = prepareRequest(mergeHeaders(this.headers, extraHeaders));
URI target = UriTemplate.of(uri).expand();
ResponseEntity<String> responseEntity = operations.exchange(target, GET, request, String.class);
MediaType contentType = responseEntity.getHeaders().getContentType();
if (contentType == null) {
throw new IllegalStateException(String.format(MEDIA_TYPE_HEADER_NOT_FOUND, target));
}
String responseBody = responseEntity.getBody();
Hop thisHop = rels.next();
Rel rel = Rels.getRelFor(thisHop.getRel(), discoverers);
Link link = rel.findInResponse(responseBody == null ? "" : responseBody, contentType) //
.orElseThrow(() -> new IllegalStateException(String.format(LINK_NOT_FOUND, rel, responseBody)));
String linkTarget = thisHop.hasParameters() //
? link.expand(thisHop.getMergedParameters(templateParameters)).getHref() //
: link.getHref();
return getAndFindLinkWithRel(linkTarget, rels, thisHop.getHeaders());
}
/**
* Combine two sets of {@link HttpHeaders} into one.
*
* @param headersA
* @param headersB
* @return
*/
private HttpHeaders mergeHeaders(HttpHeaders headersA, HttpHeaders headersB) {
HttpHeaders mergedHeaders = new HttpHeaders();
mergedHeaders.addAll(headersA);
mergedHeaders.addAll(headersB);
return mergedHeaders;
}
}
/**
* Temporary container for a string-base {@literal URI} and {@link HttpHeaders}.
*/
private static final class UriStringAndHeaders {
private final String uri;
private final HttpHeaders httpHeaders;
UriStringAndHeaders(String uri, HttpHeaders httpHeaders) {
this.uri = uri;
this.httpHeaders = httpHeaders;
}
String getUri() {
return this.uri;
}
HttpHeaders getHttpHeaders() {
return this.httpHeaders;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UriStringAndHeaders that = (UriStringAndHeaders) o;
return Objects.equals(this.uri, that.uri) && Objects.equals(this.httpHeaders, that.httpHeaders);
}
@Override
public int hashCode() {
return Objects.hash(this.uri, this.httpHeaders);
}
@Override
public String toString() {
return "Traverson.UriStringAndHeaders(uri=" + this.uri + ", httpHeaders=" + this.httpHeaders + ")";
}
}
/**
* Temporary container for a {@link URI}-based {@literal URI} and {@link HttpHeaders}.
*/
private static final class URIAndHeaders {
private final URI uri;
private final HttpHeaders httpHeaders;
URIAndHeaders(URI uri, HttpHeaders httpHeaders) {
this.uri = uri;
this.httpHeaders = httpHeaders;
}
URI getUri() {
return this.uri;
}
HttpHeaders getHttpHeaders() {
return this.httpHeaders;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
URIAndHeaders that = (URIAndHeaders) o;
return Objects.equals(this.uri, that.uri) && Objects.equals(this.httpHeaders, that.httpHeaders);
}
@Override
public int hashCode() {
return Objects.hash(this.uri, this.httpHeaders);
}
@Override
public String toString() {
return "Traverson.URIAndHeaders(uri=" + this.uri + ", httpHeaders=" + this.httpHeaders + ")";
}
}
}