#1116 - Revisit factory methods of RepresentationModel.

This commit introduces ….of(…) factory methods on all RepresentationModel types as well as Link. RepresentationModel.of(…) transparently creates a EntityModel or CollectionModel depending on the value handed into the method.
This commit is contained in:
Oliver Drotbohm
2019-11-18 20:15:41 +01:00
parent 37896bc244
commit 60cf2a828e
78 changed files with 966 additions and 594 deletions

View File

@@ -65,7 +65,7 @@ public class EmployeeController {
return IntStream.range(0, EMPLOYEES.size()) //
.mapToObj(this::findOne) //
.collect(Collectors.collectingAndThen(Collectors.toList(), //
it -> new CollectionModel<>(it, selfLink)));
it -> CollectionModel.of(it, selfLink)));
}
@GetMapping("/employees/search")
@@ -100,7 +100,7 @@ public class EmployeeController {
.andAffordance(afford(methodOn(EmployeeController.class).search(null, null)));
// Return the collection of employee resources along with the composite affordance
return new CollectionModel<>(employees, selfLink);
return CollectionModel.of(employees, selfLink);
}
// tag::get[]
@@ -113,7 +113,7 @@ public class EmployeeController {
Link findOneLink = linkTo(methodOn(controllerClass).findOne(id)).withSelfRel(); // <1>
// Return the affordance + a link back to the entire collection resource.
return new EntityModel<>(EMPLOYEES.get(id), //
return EntityModel.of(EMPLOYEES.get(id), //
findOneLink //
.andAffordance(afford(methodOn(controllerClass).updateEmployee(null, id))) // <2>
.andAffordance(afford(methodOn(controllerClass).partiallyUpdateEmployee(null, id)))); // <3>

View File

@@ -31,11 +31,11 @@ public class FundamentalsTest {
public void links() {
// tag::links[]
Link link = new Link("/something");
Link link = Link.of("/something");
assertThat(link.getHref()).isEqualTo("/something");
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
link = new Link("/something", "my-rel");
link = Link.of("/something", "my-rel");
assertThat(link.getHref()).isEqualTo("/something");
assertThat(link.getRel()).isEqualTo(LinkRelation.of("my-rel"));
// end::links[]
@@ -45,7 +45,7 @@ public class FundamentalsTest {
public void templatedLinks() {
// tag::templatedLinks[]
Link link = new Link("/{segment}/something{?parameter}");
Link link = Link.of("/{segment}/something{?parameter}");
assertThat(link.isTemplated()).isTrue(); // <1>
assertThat(link.getVariableNames()).contains("segment", "parameter"); // <2>

View File

@@ -28,7 +28,7 @@ public class PaymentProcessor implements RepresentationModelProcessor<EntityMode
public EntityModel<Order> process(EntityModel<Order> model) {
model.add( // <2>
new Link("/payments/{orderId}").withRel(LinkRelation.of("payments")) //
Link.of("/payments/{orderId}").withRel(LinkRelation.of("payments")) //
.expand(model.getContent().getOrderId()));
return model; // <3>

View File

@@ -68,7 +68,7 @@ URI templates can be constructed manually and template variables added later on.
====
[source, java]
----
UriTemplate template = new UriTemplate("/{segment}/something")
UriTemplate template = UriTemplate.of("/{segment}/something")
.with(new TemplateVariable("parameter", VariableType.REQUEST_PARAM);
assertThat(template.toString()).isEqualTo("/{segment}/something{?parameter}");
@@ -92,7 +92,7 @@ They can be referred to via `IanaLinkRelations`.
====
[source, java]
----
Link link = new Link("/some-resource"), IanaLinkRelations.NEXT);
Link link = Link.of("/some-resource"), IanaLinkRelations.NEXT);
assertThat(link.getRel()).isEqualTo(LinkRelation.of("next"));
assertThat(IanaLinkRelation.isIanaRel(link.getRel())).isTrue();
@@ -145,7 +145,7 @@ The model type can now be used like this:
PersonModel model = new PersonModel();
model.firstname = "Dave";
model.lastname = "Matthews";
model.add(new Link("https://myhost/people/42"));
model.add(Link.of("https://myhost/people/42"));
----
====
@@ -178,7 +178,7 @@ Instead of creating a custom model type for each concept, you can just reuse an
[source, java]
----
Person person = new Person("Dave", "Matthews");
EntityModel<Person> model = new EntityModel<>(person);
EntityModel<Person> model = EntityModel.of(person);
----
====
@@ -192,6 +192,6 @@ Its elements can either be simple objects or `RepresentationModel` instances in
[source, java]
----
Collection<Person> people = Collections.singleton(new Person("Dave", "Matthews"));
CollectionModel<Person> model = new CollectionModel<>(people);
CollectionModel<Person> model = CollectionModel.of(people);
----
====

View File

@@ -48,7 +48,9 @@ public class CollectionModel<T> extends RepresentationModel<CollectionModel<T>>
*
* @param content must not be {@literal null}.
* @param links the links to be added to the {@link CollectionModel}.
* @deprecated since 1.1, use {@link #of(Iterable, Link...)} instead.
*/
@Deprecated
public CollectionModel(Iterable<T> content, Link... links) {
this(content, Arrays.asList(links));
}
@@ -58,7 +60,9 @@ public class CollectionModel<T> extends RepresentationModel<CollectionModel<T>>
*
* @param content must not be {@literal null}.
* @param links the links to be added to the {@link CollectionModel}.
* @deprecated since 1.1, use {@link #of(Iterable, Iterable)} instead.
*/
@Deprecated
public CollectionModel(Iterable<T> content, Iterable<Link> links) {
Assert.notNull(content, "Content must not be null!");
@@ -68,9 +72,56 @@ public class CollectionModel<T> extends RepresentationModel<CollectionModel<T>>
for (T element : content) {
this.content.add(element);
}
this.add(links);
}
/**
* Creates a new empty collection model.
*
* @param <T>
* @return
*/
public static <T> CollectionModel<T> empty() {
return of(Collections.emptyList());
}
/**
* Creates a {@link CollectionModel} instance with the given content.
*
* @param content must not be {@literal null}.
* @param links the links to be added to the {@link CollectionModel}.
* @return
* @since 1.1
*/
public static <T> CollectionModel<T> of(Iterable<T> content) {
return of(content, Collections.emptyList());
}
/**
* Creates a {@link CollectionModel} instance with the given content and {@link Link}s (optional).
*
* @param content must not be {@literal null}.
* @param links the links to be added to the {@link CollectionModel}.
* @return
* @since 1.1
*/
public static <T> CollectionModel<T> of(Iterable<T> content, Link... links) {
return of(content, Arrays.asList(links));
}
/**
* s Creates a {@link CollectionModel} instance with the given content and {@link Link}s.
*
* @param content must not be {@literal null}.
* @param links the links to be added to the {@link CollectionModel}.
* @return
* @since 1.1
*/
public static <T> CollectionModel<T> of(Iterable<T> content, Iterable<Link> links) {
return new CollectionModel<>(content, links);
}
/**
* Creates a new {@link CollectionModel} instance by wrapping the given domain class instances into a
* {@link EntityModel}.
@@ -86,10 +137,10 @@ public class CollectionModel<T> extends RepresentationModel<CollectionModel<T>>
ArrayList<T> resources = new ArrayList<>();
for (S element : content) {
resources.add((T) new EntityModel<>(element));
resources.add((T) EntityModel.of(element));
}
return new CollectionModel<>(resources);
return CollectionModel.of(resources);
}
/**

View File

@@ -17,6 +17,7 @@ package org.springframework.hateoas;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -49,7 +50,9 @@ public class EntityModel<T> extends RepresentationModel<EntityModel<T>> {
*
* @param content must not be {@literal null}.
* @param links the links to add to the {@link EntityModel}.
* @deprecated since 1.1, use {@link #of(Object, Link...)} instead.
*/
@Deprecated
public EntityModel(T content, Link... links) {
this(content, Arrays.asList(links));
}
@@ -59,15 +62,54 @@ public class EntityModel<T> extends RepresentationModel<EntityModel<T>> {
*
* @param content must not be {@literal null}.
* @param links the links to add to the {@link EntityModel}.
* @deprecated since 1.1, use {@link #of(Object, Iterable)} instead.
*/
public EntityModel(@Nullable T content, Iterable<Link> links) {
@Deprecated
public EntityModel(T content, Iterable<Link> links) {
Assert.notNull(content, "Content must not be null!");
Assert.isTrue(!(content instanceof Collection), "Content must not be a collection! Use Resources instead!");
Assert.isTrue(!(content instanceof Collection), "Content must not be a collection! Use CollectionModel instead!");
this.content = content;
this.add(links);
}
/**
* Creates a new {@link EntityModel} with the given content.
*
* @param content must not be {@literal null}.
* @param links the links to add to the {@link EntityModel}.
* @return
* @since 1.1
*/
public static <T> EntityModel<T> of(T content) {
return of(content, Collections.emptyList());
}
/**
* Creates a new {@link EntityModel} with the given content and {@link Link}s (optional).
*
* @param content must not be {@literal null}.
* @param links the links to add to the {@link EntityModel}.
* @return
* @since 1.1
*/
public static <T> EntityModel<T> of(T content, Link... links) {
return of(content, Arrays.asList(links));
}
/**
* Creates a new {@link EntityModel} with the given content and {@link Link}s.
*
* @param content must not be {@literal null}.
* @param links the links to add to the {@link EntityModel}.
* @return
* @since 1.1
*/
public static <T> EntityModel<T> of(T content, Iterable<Link> links) {
return new EntityModel<>(content, links);
}
/**
* Returns the underlying entity.
*
@@ -81,7 +123,9 @@ public class EntityModel<T> extends RepresentationModel<EntityModel<T>> {
// Hacks to allow deserialization into an EntityModel<Map<String, Object>>
@Nullable
@JsonAnyGetter
@SuppressWarnings("unchecked")
private Map<String, Object> getMapContent() {
return Map.class.isInstance(content) ? (Map<String, Object>) content : null;
}

View File

@@ -105,7 +105,9 @@ public class Link implements Serializable {
*
* @see IanaLinkRelations#SELF
* @param href must not be {@literal null} or empty.
* @deprecated since 1.1, use {@link #of(String)}
*/
@Deprecated
public Link(String href) {
this(href, IanaLinkRelations.SELF);
}
@@ -115,7 +117,9 @@ public class Link implements Serializable {
*
* @param href must not be {@literal null} or empty.
* @param rel must not be {@literal null} or empty.
* @deprecated since 1.1, use {@link #of(String, String)}.
*/
@Deprecated
public Link(String href, String rel) {
this(UriTemplate.of(href), LinkRelation.of(rel));
}
@@ -125,7 +129,9 @@ public class Link implements Serializable {
*
* @param href must not be {@literal null} or empty.
* @param rel must not be {@literal null} or empty.
* @deprecated since 1.1, use {@link #of(String, LinkRelation)}.
*/
@Deprecated
public Link(String href, LinkRelation rel) {
this(UriTemplate.of(href), rel);
}
@@ -135,7 +141,9 @@ public class Link implements Serializable {
*
* @param template must not be {@literal null}.
* @param rel must not be {@literal null} or empty.
* @deprecated since 1.1, use {@link #of(UriTemplate, String)}.
*/
@Deprecated
public Link(UriTemplate template, String rel) {
this(template, LinkRelation.of(rel));
}
@@ -145,7 +153,9 @@ public class Link implements Serializable {
*
* @param template must not be {@literal null}.
* @param rel must not be {@literal null} or empty.
* @deprecated since 1.1, use {@link #of(UriTemplate, LinkRelation)}.
*/
@Deprecated
public Link(UriTemplate template, LinkRelation rel) {
this(template, rel, Collections.emptyList());
}
@@ -168,6 +178,67 @@ public class Link implements Serializable {
this.affordances = affordances;
}
/**
* Creates a new link to the given URI with the self relation.
*
* @see IanaLinkRelations#SELF
* @param href must not be {@literal null} or empty.
* @return
* @since 1.1
*/
public static Link of(String href) {
return new Link(href);
}
/**
* Creates a new {@link Link} to the given href with the given relation.
*
* @param href must not be {@literal null} or empty.
* @param relation must not be {@literal null} or empty.
* @return
* @since 1.1
*/
@Deprecated
public static Link of(String href, String relation) {
return new Link(href, relation);
}
/**
* Creates a new {@link Link} to the given href and {@link LinkRelation}.
*
* @param href must not be {@literal null} or empty.
* @param relation must not be {@literal null}.
* @return
* @since 1.1
*/
public static Link of(String href, LinkRelation relation) {
return new Link(href, relation);
}
/**
* Creates a new {@link Link} to the given {@link UriTemplate} and link relation.
*
* @param template must not be {@literal null}.
* @param relation must not be {@literal null} or empty.
* @return
* @since 1.1
*/
public static Link of(UriTemplate template, String relation) {
return new Link(template, relation);
}
/**
* Creates a new {@link Link} to the given {@link UriTemplate} and {@link LinkRelation}.
*
* @param template must not be {@literal null}.
* @param relation must not be {@literal null}.
* @return
* @since 1.1
*/
public static Link of(UriTemplate template, LinkRelation relation) {
return new Link(template, relation);
}
/**
* Empty constructor required by the marshaling framework.
*/
@@ -272,7 +343,7 @@ public class Link implements Serializable {
* @return
*/
public Link expand(Object... arguments) {
return new Link(template.expand(arguments).toString(), getRel());
return of(template.expand(arguments).toString(), getRel());
}
/**
@@ -282,7 +353,7 @@ public class Link implements Serializable {
* @return
*/
public Link expand(Map<String, ?> arguments) {
return new Link(template.expand(arguments).toString(), getRel());
return of(template.expand(arguments).toString(), getRel());
}
/**
@@ -416,7 +487,7 @@ public class Link implements Serializable {
throw new IllegalArgumentException("Link does not provide a rel attribute!");
}
Link link = new Link(matcher.group(1), attributes.get("rel"));
Link link = of(matcher.group(1), attributes.get("rel"));
if (attributes.containsKey("hreflang")) {
link = link.withHreflang(attributes.get("hreflang"));

View File

@@ -18,6 +18,7 @@ package org.springframework.hateoas;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import org.springframework.lang.Nullable;
@@ -51,7 +52,9 @@ public class PagedModel<T> extends CollectionModel<T> {
* @param content must not be {@literal null}.
* @param metadata
* @param links
* @deprectated since 1.1, use {@link #of(Collection, PageMetadata, Link...)} instead.
*/
@Deprecated
public PagedModel(Collection<T> content, @Nullable PageMetadata metadata, Link... links) {
this(content, metadata, Arrays.asList(links));
}
@@ -62,7 +65,9 @@ public class PagedModel<T> extends CollectionModel<T> {
* @param content must not be {@literal null}.
* @param metadata
* @param links
* @deprectated since 1.1, use {@link #of(Collection, PageMetadata, Iterable)} instead.
*/
@Deprecated
public PagedModel(Collection<T> content, @Nullable PageMetadata metadata, Iterable<Link> links) {
super(content, links);
@@ -70,6 +75,62 @@ public class PagedModel<T> extends CollectionModel<T> {
this.metadata = metadata;
}
/**
* Creates an empty {@link PagedModel}.
*
* @param <T>
* @return
* @since 1.1
*/
public static <T> PagedModel<T> empty() {
return empty(null);
}
/**
* Creates an empty {@link PagedModel} with the given {@link PageMetadata}.
*
* @param <T>
* @param metadata can be {@literal null}.
* @return
* @since 1.1
*/
public static <T> PagedModel<T> empty(@Nullable PageMetadata metadata) {
return of(Collections.emptyList(), metadata);
}
/**
* Creates a new {@link PagedModel} from the given content, {@link PageMetadata} and {@link Link}s (optional).
*
* @param content must not be {@literal null}.
* @param metadata can be {@literal null}.
* @param links
*/
public static <T> PagedModel<T> of(Collection<T> content, @Nullable PageMetadata metadata) {
return new PagedModel<>(content, metadata);
}
/**
* Creates a new {@link PagedModel} from the given content, {@link PageMetadata} and {@link Link}s (optional).
*
* @param content must not be {@literal null}.
* @param metadata can be {@literal null}.
* @param links
*/
public static <T> PagedModel<T> of(Collection<T> content, @Nullable PageMetadata metadata, Link... links) {
return new PagedModel<>(content, metadata, Arrays.asList(links));
}
/**
* Creates a new {@link PagedModel} from the given content {@link PageMetadata} and {@link Link}s.
*
* @param content must not be {@literal null}.
* @param metadata can be {@literal null}.
* @param links
*/
public static <T> PagedModel<T> of(Collection<T> content, @Nullable PageMetadata metadata, Iterable<Link> links) {
return new PagedModel<>(content, metadata, links);
}
/**
* Returns the pagination metadata.
*
@@ -95,10 +156,10 @@ public class PagedModel<T> extends CollectionModel<T> {
ArrayList<T> resources = new ArrayList<>();
for (S element : content) {
resources.add((T) new EntityModel<>(element));
resources.add((T) EntityModel.of(element));
}
return new PagedModel<>(resources, metadata);
return PagedModel.of(resources, metadata);
}
/**

View File

@@ -17,6 +17,8 @@ package org.springframework.hateoas;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
@@ -50,12 +52,48 @@ public class RepresentationModel<T extends RepresentationModel<? extends T>> {
this.links.add(initialLink);
}
public RepresentationModel(List<Link> initialLinks) {
public RepresentationModel(Iterable<Link> initialLinks) {
Assert.notNull(initialLinks, "initialLinks must not be null!");
this.links = new ArrayList<>();
this.links.addAll(initialLinks);
for (Link link : initialLinks) {
this.links.add(link);
}
}
/**
* Creates a new {@link RepresentationModel} for the given content object and no links.
*
* @param object can be {@literal null}.
* @return
* @see #of(Object, Iterable)
*/
public static <T> RepresentationModel<?> of(@Nullable T object) {
return of(object, Collections.emptyList());
}
/**
* Creates a new {@link RepresentationModel} for the given content object and links. Will return a simple
* {@link RepresentationModel} if the content is {@literal null}, a {@link CollectionModel} in case the given content
* object is a {@link Collection} or an {@link EntityModel} otherwise.
*
* @param object can be {@literal null}.
* @param links must not be {@literal null}.
* @return
*/
public static <T> RepresentationModel<?> of(@Nullable T object, Iterable<Link> links) {
if (object == null) {
return new RepresentationModel<>(links);
}
if (Collection.class.isInstance(object)) {
return CollectionModel.of((Collection<?>) object, links);
}
return EntityModel.of(object, links);
}
/**

View File

@@ -140,7 +140,7 @@ public class JsonPathLinkDiscoverer implements LinkDiscoverer {
* @return link
*/
protected Link extractLink(Object element, LinkRelation rel) {
return new Link(element.toString(), rel);
return Link.of(element.toString(), rel);
}
/**
@@ -174,7 +174,7 @@ public class JsonPathLinkDiscoverer implements LinkDiscoverer {
return Links.of(Map.class.isInstance(parseResult) //
? extractLink(parseResult, rel) //
: new Link(parseResult.toString(), rel));
: Link.of(parseResult.toString(), rel));
}
private static <T> Optional<T> firstOrEmpty(Iterable<T> source) {

View File

@@ -143,7 +143,7 @@ class Rels {
*/
@Override
public Optional<Link> findInResponse(@Nullable String representation, @Nullable MediaType mediaType) {
return Optional.of(new Link(JsonPath.read(representation, jsonPath).toString(), rel));
return Optional.of(Link.of(JsonPath.read(representation, jsonPath).toString(), rel));
}
}
}

View File

@@ -377,7 +377,7 @@ public class Traverson {
Assert.isTrue(rels.size() > 0, "At least one rel needs to be provided!");
return new Link(expandFinalUrl ? traverseToExpandedFinalUrl().getUri().toString() : traverseToFinalUrl().getUri(),
return Link.of(expandFinalUrl ? traverseToExpandedFinalUrl().getUri().toString() : traverseToFinalUrl().getUri(),
rels.get(rels.size() - 1).getRel());
}

View File

@@ -100,7 +100,7 @@ class CollectionJson<T> {
return this;
}
return withLinks(Links.of(new Link(href)).merge(MergeMode.SKIP_BY_REL, links));
return withLinks(Links.of(Link.of(href)).merge(MergeMode.SKIP_BY_REL, links));
}
boolean hasItems() {

View File

@@ -53,7 +53,7 @@ class CollectionJsonItem<T> {
private @Nullable String href;
private List<CollectionJsonData> data;
private @JsonInclude(Include.NON_EMPTY) Links links;
private @Nullable @Getter(onMethod = @__({ @JsonIgnore }), value = AccessLevel.PRIVATE) T rawData;
private @Nullable @Getter(onMethod = @__(@JsonIgnore)) T rawData;
@JsonCreator
CollectionJsonItem(@JsonProperty("href") @Nullable String href, //
@@ -91,6 +91,10 @@ class CollectionJsonItem<T> {
return Collections.singletonList(new CollectionJsonData().withValue(this.rawData));
}
if (rawData == null) {
return Collections.emptyList();
}
return PropertyUtils.extractPropertyValues(this.rawData).entrySet().stream() //
.map(entry -> new CollectionJsonData() //
.withName(entry.getKey()) //
@@ -135,6 +139,6 @@ class CollectionJsonItem<T> {
return this;
}
return withLinks(Links.of(new Link(href)).merge(MergeMode.SKIP_BY_REL, links));
return withLinks(Links.of(Link.of(href)).merge(MergeMode.SKIP_BY_REL, links));
}
}

View File

@@ -762,7 +762,7 @@ public class Jackson2CollectionJsonModule extends SimpleModule {
Object obj = PropertyUtils.createObjectFromProperties(rootType.getRawClass(), properties);
return new EntityModel<>(obj, links);
return EntityModel.of(obj, links);
} else {
@@ -774,7 +774,7 @@ public class Jackson2CollectionJsonModule extends SimpleModule {
CollectionJsonItem<?> firstItem = items.get(0).withOwnSelfLink();
return new EntityModel<>(firstItem.toRawData(rootType),
return EntityModel.of(firstItem.toRawData(rootType),
merged.merge(MergeMode.REPLACE_BY_REL, firstItem.getLinks()));
}
}
@@ -877,7 +877,7 @@ public class Jackson2CollectionJsonModule extends SimpleModule {
return collection.getItems().stream() //
.map(CollectionJsonItem::withOwnSelfLink) //
.map(it -> isResource //
? new EntityModel<>(it.toRawData(rootType), it.getLinks()) //
? RepresentationModel.of(it.toRawData(rootType), it.getLinks()) //
: it.toRawData(rootType)) //
.collect(Collectors.collectingAndThen(Collectors.toList(), it -> finalizer.apply(it, links)));
}
@@ -902,7 +902,7 @@ public class Jackson2CollectionJsonModule extends SimpleModule {
private static final long serialVersionUID = -7465448422501330790L;
private static final BiFunction<List<Object>, Links, PagedModel<?>> FINISHER = (content,
links) -> new PagedModel<>(content, null, links);
links) -> PagedModel.of(content, null, links);
private static final Function<JavaType, CollectionJsonDeserializerBase<PagedModel<?>>> CONTEXTUAL_CREATOR = CollectionJsonPagedResourcesDeserializer::new;
CollectionJsonPagedResourcesDeserializer() {

View File

@@ -155,6 +155,7 @@ public class DefaultCurieProvider implements CurieProvider {
private final @Getter String name;
@SuppressWarnings("deprecation")
public Curie(String name, String href) {
super(href, "curies");

View File

@@ -57,7 +57,7 @@ public class HalLinkDiscoverer extends JsonPathLinkDiscoverer {
Map<String, String> json = (Map<String, String>) element;
return new Link(json.get("href"), rel) //
return Link.of(json.get("href"), rel) //
.withHreflang(json.get("hreflang")) //
.withMedia(json.get("media")) //
.withTitle(json.get("title")) //

View File

@@ -82,7 +82,7 @@ import com.fasterxml.jackson.databind.type.TypeFactory;
public class Jackson2HalModule extends SimpleModule {
private static final long serialVersionUID = 7806951456457932384L;
private static final Link CURIES_REQUIRED_DUE_TO_EMBEDS = new Link("__rel__", "¯\\_(ツ)_/¯");
private static final Link CURIES_REQUIRED_DUE_TO_EMBEDS = Link.of("__rel__", "¯\\_(ツ)_/¯");
public Jackson2HalModule() {
@@ -606,12 +606,12 @@ public class Jackson2HalModule extends SimpleModule {
if (JsonToken.START_ARRAY.equals(jp.nextToken())) {
while (!JsonToken.END_ARRAY.equals(jp.nextToken())) {
link = jp.readValueAs(Link.class);
result.add(new Link(link.getHref(), relation).withHreflang(link.getHreflang()).withTitle(link.getTitle())
result.add(Link.of(link.getHref(), relation).withHreflang(link.getHreflang()).withTitle(link.getTitle())
.withType(link.getType()).withDeprecation(link.getDeprecation()));
}
} else {
link = jp.readValueAs(Link.class);
result.add(new Link(link.getHref(), relation).withHreflang(link.getHreflang()).withTitle(link.getTitle())
result.add(Link.of(link.getHref(), relation).withHreflang(link.getHreflang()).withTitle(link.getTitle())
.withType(link.getType()).withDeprecation(link.getDeprecation()));
}
}

View File

@@ -576,7 +576,7 @@ public class Jackson2UberModule extends SimpleModule {
/**
* Custom {@link StdDeserializer} to deserialize {@link EntityModel}.
*/
static class UberEntityModelDeserializer extends ContainerDeserializerBase<EntityModel<?>>
static class UberEntityModelDeserializer extends ContainerDeserializerBase<RepresentationModel<?>>
implements ContextualDeserializer {
private static final long serialVersionUID = 1776321413269082414L;
@@ -599,7 +599,7 @@ public class Jackson2UberModule extends SimpleModule {
*/
@Override
@SuppressWarnings("null")
public EntityModel<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
public RepresentationModel<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
UberDocument doc = p.getCodec().readValue(p, UberDocument.class);
Links links = doc.getUber().getLinks();
@@ -612,8 +612,7 @@ public class Jackson2UberModule extends SimpleModule {
() -> new IllegalStateException("No data entry containing a 'value' was found in this document!"));
}
@NotNull
private EntityModel<Object> convertToResource(UberData uberData, Links links) {
private RepresentationModel<?> convertToResource(UberData uberData, Links links) {
// Primitive type
List<UberData> data = uberData.getData();
@@ -625,9 +624,9 @@ public class Jackson2UberModule extends SimpleModule {
if (isPrimitiveType(data)) {
UberData firstItem = data.get(0);
Object scalarValue = firstItem.getValue();
return new EntityModel<>(scalarValue, links);
return RepresentationModel.of(scalarValue, links);
}
Map<String, Object> properties = data == null //
@@ -637,7 +636,7 @@ public class Jackson2UberModule extends SimpleModule {
JavaType rootType = JacksonHelper.findRootType(this.contentType);
Object value = PropertyUtils.createObjectFromProperties(rootType.getRawClass(), properties);
return new EntityModel<>(value, links);
return EntityModel.of(value, links);
}
/*
@@ -774,7 +773,7 @@ public class Jackson2UberModule extends SimpleModule {
CollectionModel<?> resources = extractResources(doc, rootType, this.contentType);
PageMetadata pageMetadata = extractPagingMetadata(doc);
return new PagedModel<>(resources.getContent(), pageMetadata, resources.getLinks());
return PagedModel.of(resources.getContent(), pageMetadata, resources.getLinks());
}
/**
@@ -834,7 +833,7 @@ public class Jackson2UberModule extends SimpleModule {
}
List<Link> resourceLinks = new ArrayList<>();
EntityModel<?> resource = null;
RepresentationModel<?> resource = null;
List<UberData> data = uberData.getData();
@@ -861,7 +860,8 @@ public class Jackson2UberModule extends SimpleModule {
UberData firstItem = itemData.get(0);
Object scalarValue = firstItem.getValue();
resource = new EntityModel<>(scalarValue, uberData.getLinks());
resource = RepresentationModel.of(scalarValue, uberData.getLinks());
} else {
@@ -871,7 +871,7 @@ public class Jackson2UberModule extends SimpleModule {
.collect(Collectors.toMap(UberData::getName, UberData::getValue));
Object obj = PropertyUtils.createObjectFromProperties(rootType.getRawClass(), properties);
resource = new EntityModel<>(obj, uberData.getLinks());
resource = EntityModel.of(obj, uberData.getLinks());
}
}
}
@@ -889,7 +889,7 @@ public class Jackson2UberModule extends SimpleModule {
/*
* Either return a Resources<Resource<T>>...
*/
return new CollectionModel<>(content, doc.getUber().getLinks());
return CollectionModel.of(content, doc.getUber().getLinks());
} else {
/*
* ...or return a Resources<T>
@@ -898,7 +898,7 @@ public class Jackson2UberModule extends SimpleModule {
List<Object> resourceLessContent = content.stream().map(item -> (EntityModel<?>) item)
.map(EntityModel::getContent).collect(Collectors.toList());
return new CollectionModel<>(resourceLessContent, doc.getUber().getLinks());
return CollectionModel.of(resourceLessContent, doc.getUber().getLinks());
}
}

View File

@@ -148,7 +148,7 @@ class UberData {
return Optional.ofNullable(this.rel) //
.map(rels -> rels.stream() //
.map(rel -> new Link(url, rel)) //
.map(rel -> Link.of(url, rel)) //
.collect(Collectors.toList())) //
.orElse(Collections.emptyList());
}
@@ -296,7 +296,7 @@ class UberData {
return extractLinksAndContent((RepresentationModel<?>) item);
}
return extractLinksAndContent(new EntityModel<>(item));
return extractLinksAndContent(EntityModel.of(item));
}
/**
@@ -374,11 +374,11 @@ class UberData {
return affordanceBasedLinks.stream() //
.flatMap(affordance -> links.stream() //
.filter(data -> data.hasUrl(affordance.getUrl())) //
.map(link -> {
.map(data -> {
if (link.getAction() == affordance.getAction()) {
if (data.getAction() == affordance.getAction()) {
List<LinkRelation> rels = new ArrayList<>(link.getRel());
List<LinkRelation> rels = new ArrayList<>(data.getRel());
rels.addAll(affordance.getRel());
return affordance.withName(rels.get(0).value()) //

View File

@@ -30,6 +30,7 @@ import org.springframework.hateoas.Link;
import org.springframework.hateoas.Links;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.server.core.Relation;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -45,11 +46,12 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
* @see https://github.com/blongden/vnd.error
* @author Oliver Gierke
* @author Greg Turnquist
* @deprecated Use {@link org.springframework.hateoas.mediatype.problem.Problem} to form vendor neutral error messages.
* @deprecated since 1.1, use {@link org.springframework.hateoas.mediatype.problem.Problem} to form vendor neutral error
* messages.
*/
@JsonPropertyOrder({ "message", "logref", "total", "_links", "_embedded" })
@JsonIgnoreProperties(ignoreUnknown = true)
@EqualsAndHashCode
@EqualsAndHashCode(callSuper = true)
@Deprecated
public class VndErrors extends CollectionModel<VndErrors.VndError> {
@@ -177,8 +179,16 @@ public class VndErrors extends CollectionModel<VndErrors.VndError> {
/**
* Virtual attribute to generate JSON field of {@literal total}. Only generated when there are multiple errors.
*/
@Nullable
@JsonInclude(JsonInclude.Include.NON_NULL)
public Integer getTotal() {
List<VndError> errors = this.errors;
if (errors == null) {
return null;
}
return this.errors.size() > 1 //
? this.errors.size() //
: null; //
@@ -214,12 +224,12 @@ public class VndErrors extends CollectionModel<VndErrors.VndError> {
*
* @author Oliver Gierke
* @author Greg Turnquist
*
* @deprecated Use {@link org.springframework.hateoas.mediatype.problem.Problem} to form vendor neutral error messages.
* @deprecated Use {@link org.springframework.hateoas.mediatype.problem.Problem} to form vendor neutral error
* messages.
*/
@JsonPropertyOrder({ "message", "path", "logref" })
@Relation(collectionRelation = "errors")
@EqualsAndHashCode
@EqualsAndHashCode(callSuper = true)
@Deprecated
public static class VndError extends RepresentationModel<VndError> {

View File

@@ -29,8 +29,7 @@ import org.springframework.util.Assert;
* @author Greg Turnquist
* @since 1.0
*/
public interface SimpleRepresentationModelAssembler<T>
extends RepresentationModelAssembler<T, EntityModel<T>> {
public interface SimpleRepresentationModelAssembler<T> extends RepresentationModelAssembler<T, EntityModel<T>> {
/**
* Converts the given entity into a {@link EntityModel}.
@@ -40,7 +39,7 @@ public interface SimpleRepresentationModelAssembler<T>
*/
default EntityModel<T> toModel(T entity) {
EntityModel<T> resource = new EntityModel<>(entity);
EntityModel<T> resource = EntityModel.of(entity);
addLinks(resource);
return resource;
}
@@ -60,8 +59,7 @@ public interface SimpleRepresentationModelAssembler<T>
* @return {@link CollectionModel} containing {@link EntityModel} of {@code T}.
*/
@Override
default CollectionModel<EntityModel<T>> toCollectionModel(
Iterable<? extends T> entities) {
default CollectionModel<EntityModel<T>> toCollectionModel(Iterable<? extends T> entities) {
Assert.notNull(entities, "entities must not be null!");
List<EntityModel<T>> resourceList = new ArrayList<>();
@@ -70,8 +68,7 @@ public interface SimpleRepresentationModelAssembler<T>
resourceList.add(toModel(entity));
}
CollectionModel<EntityModel<T>> resources = new CollectionModel<>(
resourceList);
CollectionModel<EntityModel<T>> resources = CollectionModel.of(resourceList);
addLinks(resources);
return resources;
}

View File

@@ -139,7 +139,7 @@ public abstract class LinkBuilderSupport<T extends LinkBuilder> implements LinkB
*/
public Link withRel(LinkRelation rel) {
return new Link(toString(), rel) //
return Link.of(toString(), rel) //
.withAffordances(affordances);
}

View File

@@ -50,7 +50,7 @@ public class SpringAffordanceBuilder {
public static List<Affordance> create(Class<?> type, Method method, String href, MappingDiscoverer discoverer) {
String methodName = method.getName();
Link affordanceLink = new Link(href, LinkRelation.of(methodName));
Link affordanceLink = Link.of(href, LinkRelation.of(methodName));
MethodParameters parameters = MethodParameters.of(method);

View File

@@ -161,7 +161,7 @@ public abstract class RepresentationModelAssemblerSupport<T, D extends Represent
* @return
*/
public CollectionModel<D> toResources() {
return new CollectionModel<>(toListOfResources());
return CollectionModel.of(toListOfResources());
}
}
}

View File

@@ -1,5 +1,5 @@
/**
* Spring MVC helper classes to build {@link org.springframework.hateoas.Link}s and assemble
* Spring MVC helper classes to build {@link org.springframework.hateoas.Link}s and assemble
* {@link org.springframework.hateoas.RepresentationModel} types.
*/
@NonNullApi

View File

@@ -42,7 +42,7 @@ public interface SimpleReactiveRepresentationModelAssembler<T>
@Override
default Mono<EntityModel<T>> toModel(T entity, ServerWebExchange exchange) {
EntityModel<T> resource = new EntityModel<>(entity);
EntityModel<T> resource = EntityModel.of(entity);
return Mono.just(addLinks(resource, exchange));
}

View File

@@ -29,21 +29,21 @@ import org.junit.jupiter.api.Test;
*/
class CollectionModelUnitTest {
Set<EntityModel<String>> foo = Collections.singleton(new EntityModel<>("foo"));
Set<EntityModel<String>> bar = Collections.singleton(new EntityModel<>("bar"));
Set<EntityModel<String>> foo = Collections.singleton(EntityModel.of("foo"));
Set<EntityModel<String>> bar = Collections.singleton(EntityModel.of("bar"));
@Test
void equalsForSelfReference() {
CollectionModel<EntityModel<String>> resource = new CollectionModel<>(foo);
CollectionModel<EntityModel<String>> resource = CollectionModel.of(foo);
assertThat(resource).isEqualTo(resource);
}
@Test
void equalsWithEqualContent() {
CollectionModel<EntityModel<String>> left = new CollectionModel<>(foo);
CollectionModel<EntityModel<String>> right = new CollectionModel<>(foo);
CollectionModel<EntityModel<String>> left = CollectionModel.of(foo);
CollectionModel<EntityModel<String>> right = CollectionModel.of(foo);
assertThat(left).isEqualTo(right);
assertThat(right).isEqualTo(left);
@@ -52,8 +52,8 @@ class CollectionModelUnitTest {
@Test
void notEqualForDifferentContent() {
CollectionModel<EntityModel<String>> left = new CollectionModel<>(foo);
CollectionModel<EntityModel<String>> right = new CollectionModel<>(bar);
CollectionModel<EntityModel<String>> left = CollectionModel.of(foo);
CollectionModel<EntityModel<String>> right = CollectionModel.of(bar);
assertThat(left).isNotEqualTo(right);
assertThat(right).isNotEqualTo(left);
@@ -62,9 +62,9 @@ class CollectionModelUnitTest {
@Test
void notEqualForDifferentLinks() {
CollectionModel<EntityModel<String>> left = new CollectionModel<>(foo);
CollectionModel<EntityModel<String>> right = new CollectionModel<>(bar);
right.add(new Link("localhost"));
CollectionModel<EntityModel<String>> left = CollectionModel.of(foo);
CollectionModel<EntityModel<String>> right = CollectionModel.of(bar);
right.add(Link.of("localhost"));
assertThat(left).isNotEqualTo(right);
assertThat(right).isNotEqualTo(left);

View File

@@ -39,8 +39,8 @@ class EntityModelIntegrationTest extends AbstractJackson2MarshallingIntegrationT
person.firstname = "Dave";
person.lastname = "Matthews";
EntityModel<Person> resource = new EntityModel<>(person);
resource.add(new Link("localhost"));
EntityModel<Person> resource = EntityModel.of(person);
resource.add(Link.of("localhost"));
assertThat(write(resource)).isEqualTo(REFERENCE);
}
@@ -54,7 +54,7 @@ class EntityModelIntegrationTest extends AbstractJackson2MarshallingIntegrationT
PersonModel result = read(REFERENCE, PersonModel.class);
assertThat(result.getLinks()).hasSize(1);
assertThat(result.getLinks()).contains(new Link("localhost"));
assertThat(result.getLinks()).contains(Link.of("localhost"));
assertThat(result.getContent().firstname).isEqualTo("Dave");
assertThat(result.getContent().lastname).isEqualTo("Matthews");
}

View File

@@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link EntityModel}.
*
*
* @author Oliver Gierke
*/
class EntityModelUnitTest {
@@ -31,15 +31,15 @@ class EntityModelUnitTest {
@Test
void equalsForSelfReference() {
EntityModel<String> resource = new EntityModel<>("foo");
EntityModel<String> resource = EntityModel.of("foo");
assertThat(resource).isEqualTo(resource);
}
@Test
void equalsWithEqualContent() {
EntityModel<String> left = new EntityModel<>("foo");
EntityModel<String> right = new EntityModel<>("foo");
EntityModel<String> left = EntityModel.of("foo");
EntityModel<String> right = EntityModel.of("foo");
assertThat(left).isEqualTo(right);
assertThat(right).isEqualTo(left);
@@ -48,8 +48,8 @@ class EntityModelUnitTest {
@Test
void notEqualForDifferentContent() {
EntityModel<String> left = new EntityModel<>("foo");
EntityModel<String> right = new EntityModel<>("bar");
EntityModel<String> left = EntityModel.of("foo");
EntityModel<String> right = EntityModel.of("bar");
assertThat(left).isNotEqualTo(right);
assertThat(right).isNotEqualTo(left);
@@ -58,9 +58,9 @@ class EntityModelUnitTest {
@Test
void notEqualForDifferentLinks() {
EntityModel<String> left = new EntityModel<>("foo");
EntityModel<String> right = new EntityModel<>("foo");
right.add(new Link("localhost"));
EntityModel<String> left = EntityModel.of("foo");
EntityModel<String> right = EntityModel.of("foo");
right.add(Link.of("localhost"));
assertThat(left).isNotEqualTo(right);
assertThat(right).isNotEqualTo(left);
@@ -70,7 +70,7 @@ class EntityModelUnitTest {
void rejectsCollectionContent() {
assertThatIllegalArgumentException().isThrownBy(() -> {
new EntityModel<Object>(Collections.emptyList());
EntityModel.of(Collections.emptyList());
});
}
}

View File

@@ -34,7 +34,7 @@ class Jackson2LinkIntegrationTest extends AbstractJackson2MarshallingIntegration
*/
@Test
void writesLinkCorrectly() throws Exception {
assertThat(write(new Link("location", "something"))).isEqualTo(REFERENCE);
assertThat(write(Link.of("location", "something"))).isEqualTo(REFERENCE);
}
/**

View File

@@ -65,7 +65,7 @@ class Jackson2PagedResourcesIntegrationTest {
user.lastname = "Matthews";
PageMetadata metadata = new PagedModel.PageMetadata(1, 0, 2);
PagedModel<User> resources = new PagedModel<>(Collections.singleton(user), metadata);
PagedModel<User> resources = PagedModel.of(Collections.singleton(user), metadata);
Method method = Sample.class.getMethod("someMethod");
StringWriter writer = new StringWriter();

View File

@@ -27,8 +27,8 @@ class Jackson2ResourceIntegrationTest extends AbstractJackson2MarshallingIntegra
person.firstname = "Dave";
person.lastname = "Matthews";
EntityModel<Person> resource = new EntityModel<>(person);
resource.add(new Link("localhost"));
EntityModel<Person> resource = EntityModel.of(person);
resource.add(Link.of("localhost"));
assertThat(write(resource)).isEqualTo(REFERENCE);
}
@@ -42,7 +42,7 @@ class Jackson2ResourceIntegrationTest extends AbstractJackson2MarshallingIntegra
PersonResource result = read(REFERENCE, PersonResource.class);
assertThat(result.getLinks()).hasSize(1);
assertThat(result.getLinks()).contains(new Link("localhost"));
assertThat(result.getLinks()).contains(Link.of("localhost"));
assertThat(result.getContent().firstname).isEqualTo("Dave");
assertThat(result.getContent().lastname).isEqualTo("Matthews");
}

View File

@@ -35,7 +35,7 @@ class Jackson2ResourceSupportIntegrationTest extends AbstractJackson2Marshalling
void doesNotRenderId() throws Exception {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost"));
resourceSupport.add(Link.of("localhost"));
assertThat(write(resourceSupport)).isEqualTo(REFERENCE);
}
@@ -49,6 +49,6 @@ class Jackson2ResourceSupportIntegrationTest extends AbstractJackson2Marshalling
RepresentationModel<?> result = read(REFERENCE, RepresentationModel.class);
assertThat(result.getLinks()).hasSize(1);
assertThat(result.getLinks()).contains(new Link("localhost"));
assertThat(result.getLinks()).contains(Link.of("localhost"));
}
}

View File

@@ -33,7 +33,7 @@ class LinkIntegrationTest extends AbstractJackson2MarshallingIntegrationTest {
*/
@Test
void writesLinkCorrectly() throws Exception {
assertThat(write(new Link("location", "something"))).isEqualTo(REFERENCE);
assertThat(write(Link.of("location", "something"))).isEqualTo(REFERENCE);
}
/**

View File

@@ -38,13 +38,13 @@ class LinkUnitTest {
@Test
void linkWithHrefOnlyBecomesSelfLink() {
assertThat(new Link("foo").hasRel(IanaLinkRelations.SELF)).isTrue();
assertThat(Link.of("foo").hasRel(IanaLinkRelations.SELF)).isTrue();
}
@Test
void createsLinkFromRelAndHref() {
Link link = new Link("foo", IanaLinkRelations.SELF);
Link link = Link.of("foo", IanaLinkRelations.SELF);
assertSoftly(softly -> {
@@ -58,7 +58,7 @@ class LinkUnitTest {
void rejectsNullHref() {
assertThatIllegalArgumentException().isThrownBy(() -> {
new Link(null);
Link.of(null);
});
}
@@ -67,7 +67,7 @@ class LinkUnitTest {
void rejectsNullRel() {
assertThatIllegalArgumentException().isThrownBy(() -> {
new Link("foo", (String) null);
Link.of("foo", (String) null);
});
}
@@ -75,7 +75,7 @@ class LinkUnitTest {
void rejectsEmptyHref() {
assertThatIllegalArgumentException().isThrownBy(() -> {
new Link("");
Link.of("");
});
}
@@ -83,15 +83,15 @@ class LinkUnitTest {
void rejectsEmptyRel() {
assertThatIllegalArgumentException().isThrownBy(() -> {
new Link("foo", "");
Link.of("foo", "");
});
}
@Test
void sameRelAndHrefMakeSameLink() {
Link left = new Link("foo", IanaLinkRelations.SELF);
Link right = new Link("foo", IanaLinkRelations.SELF);
Link left = Link.of("foo", IanaLinkRelations.SELF);
Link right = Link.of("foo", IanaLinkRelations.SELF);
TestUtils.assertEqualAndSameHashCode(left, right);
}
@@ -99,8 +99,8 @@ class LinkUnitTest {
@Test
void differentRelMakesDifferentLink() {
Link left = new Link("foo", IanaLinkRelations.PREV);
Link right = new Link("foo", IanaLinkRelations.NEXT);
Link left = Link.of("foo", IanaLinkRelations.PREV);
Link right = Link.of("foo", IanaLinkRelations.NEXT);
TestUtils.assertNotEqualAndDifferentHashCode(left, right);
}
@@ -108,15 +108,15 @@ class LinkUnitTest {
@Test
void differentHrefMakesDifferentLink() {
Link left = new Link("foo", IanaLinkRelations.SELF);
Link right = new Link("bar", IanaLinkRelations.SELF);
Link left = Link.of("foo", IanaLinkRelations.SELF);
Link right = Link.of("bar", IanaLinkRelations.SELF);
TestUtils.assertNotEqualAndDifferentHashCode(left, right);
}
@Test
void differentTypeDoesNotEqual() {
assertThat(new Link("foo")).isNotEqualTo(new RepresentationModel<>());
assertThat(Link.of("foo")).isNotEqualTo(new RepresentationModel<>());
}
/**
@@ -129,9 +129,9 @@ class LinkUnitTest {
assertSoftly(softly -> {
softly.assertThat(Link.valueOf("</something>;rel=\"foo\"")).isEqualTo(new Link("/something", "foo"));
softly.assertThat(Link.valueOf("</something>;rel=\"foo\"")).isEqualTo(Link.of("/something", "foo"));
softly.assertThat(Link.valueOf("</something>;rel=\"foo\";title=\"Some title\""))
.isEqualTo(new Link("/something", "foo"));
.isEqualTo(Link.of("/something", "foo"));
softly.assertThat(Link.valueOf("</customer/1>;" //
+ "rel=\"self\";" //
+ "hreflang=\"en\";" //
@@ -141,7 +141,7 @@ class LinkUnitTest {
+ "deprecation=\"https://example.com/customers/deprecated\";" //
+ "profile=\"my-profile\";" //
+ "name=\"my-name\";")) //
.isEqualTo(new Link("/customer/1") //
.isEqualTo(Link.of("/customer/1") //
.withHreflang("en") //
.withMedia("pdf") //
.withTitle("pdf customer copy") //
@@ -197,14 +197,14 @@ class LinkUnitTest {
@Test
void isTemplatedIfSourceContainsTemplateVariables() {
Link link = new Link("/foo{?page}");
Link link = Link.of("/foo{?page}");
assertSoftly(softly -> {
softly.assertThat(link.isTemplated()).isTrue();
softly.assertThat(link.getVariableNames()).hasSize(1);
softly.assertThat(link.getVariableNames()).contains("page");
softly.assertThat(link.expand("2")).isEqualTo(new Link("/foo?page=2"));
softly.assertThat(link.expand("2")).isEqualTo(Link.of("/foo?page=2"));
});
}
@@ -214,7 +214,7 @@ class LinkUnitTest {
@Test
void isntTemplatedIfSourceDoesNotContainTemplateVariables() {
Link link = new Link("/foo");
Link link = Link.of("/foo");
assertSoftly(softly -> {
@@ -229,7 +229,7 @@ class LinkUnitTest {
@Test
void serializesCorrectly() throws IOException {
Link link = new Link("https://foobar{?foo,bar}");
Link link = Link.of("https://foobar{?foo,bar}");
ObjectOutputStream stream = new ObjectOutputStream(new ByteArrayOutputStream());
stream.writeObject(link);
@@ -242,7 +242,7 @@ class LinkUnitTest {
@Test
void keepsCompleteBaseUri() {
Link link = new Link("/customer/{customerId}/programs", "programs");
Link link = Link.of("/customer/{customerId}/programs", "programs");
assertThat(link.getHref()).isEqualTo("/customer/{customerId}/programs");
}
@@ -272,7 +272,7 @@ class LinkUnitTest {
@Test
void linkWithAffordancesShouldWorkProperly() {
Link originalLink = new Link("/foo");
Link originalLink = Link.of("/foo");
Link linkWithAffordance = Affordances.of(originalLink).afford(HttpMethod.GET).toLink();
Link linkWithTwoAffordances = Affordances.of(linkWithAffordance).afford(HttpMethod.GET).toLink();
@@ -297,7 +297,7 @@ class LinkUnitTest {
@Test
void exposesLinkRelation() {
Link link = new Link("/", "foo");
Link link = Link.of("/", "foo");
assertThat(link.hasRel("foo")).isTrue();
assertThat(link.hasRel("bar")).isFalse();
@@ -309,7 +309,7 @@ class LinkUnitTest {
@Test
void rejectsInvalidRelationsOnHasRel() {
Link link = new Link("/");
Link link = Link.of("/");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> link.hasRel((String) null));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> link.hasRel(""));
@@ -317,16 +317,16 @@ class LinkUnitTest {
@Test
void createsUriForSimpleLink() {
assertThat(new Link("/something").toUri()).isEqualTo(URI.create("/something"));
assertThat(Link.of("/something").toUri()).isEqualTo(URI.create("/something"));
}
@Test
void createsUriForTemplateWithOptionalParameters() {
assertThat(new Link("/something{?parameter}").toUri()).isEqualTo(URI.create("/something"));
assertThat(Link.of("/something{?parameter}").toUri()).isEqualTo(URI.create("/something"));
}
@Test
void uriCreationRejectsLinkWithUnresolvedMandatoryParameters() {
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> new Link("/{segment}/path").toUri());
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> Link.of("/{segment}/path").toUri());
}
}

View File

@@ -43,9 +43,9 @@ class LinksUnitTest {
static final String LINKS2 = StringUtils.collectionToCommaDelimitedString(Arrays.asList(THIRD, FOURTH));
static final Links reference = Links.of(new Link("/something", "foo"), new Link("/somethingElse", "bar"));
static final Links reference2 = Links.of(new Link("/something", "foo").withHreflang("en"),
new Link("/somethingElse", "bar").withHreflang("de"));
static final Links reference = Links.of(Link.of("/something", "foo"), Link.of("/somethingElse", "bar"));
static final Links reference2 = Links.of(Link.of("/something", "foo").withHreflang("en"),
Link.of("/somethingElse", "bar").withHreflang("de"));
@Test
void parsesLinkHeaderLinks() {
@@ -75,8 +75,8 @@ class LinksUnitTest {
*/
@Test
void getSingleLinkByRel() {
assertThat(reference.getLink("bar")).hasValue(new Link("/somethingElse", "bar"));
assertThat(reference2.getLink("bar")).hasValue(new Link("/somethingElse", "bar").withHreflang("de"));
assertThat(reference.getLink("bar")).hasValue(Link.of("/somethingElse", "bar"));
assertThat(reference2.getLink("bar")).hasValue(Link.of("/somethingElse", "bar").withHreflang("de"));
}
/**
@@ -85,14 +85,14 @@ class LinksUnitTest {
@Test
void parsesLinkWithComma() {
Link withComma = new Link("http://localhost:8080/test?page=0&filter=foo,bar", "foo");
Link withComma = Link.of("http://localhost:8080/test?page=0&filter=foo,bar", "foo");
assertThat(Links.parse(WITH_COMMA).getLink("foo")).isEqualTo(Optional.of(withComma));
Links twoWithCommaInFirst = Links.parse(WITH_COMMA.concat(",").concat(SECOND));
assertThat(twoWithCommaInFirst.getLink("foo")).hasValue(withComma);
assertThat(twoWithCommaInFirst.getLink("bar")).hasValue(new Link("/somethingElse", "bar"));
assertThat(twoWithCommaInFirst.getLink("bar")).hasValue(Link.of("/somethingElse", "bar"));
}
/**
@@ -106,7 +106,7 @@ class LinksUnitTest {
@Test // #805
void returnsRequiredLink() {
Link reference = new Link("http://localhost", "someRel");
Link reference = Link.of("http://localhost", "someRel");
Links links = Links.of(reference);
assertThat(links.getRequiredLink("someRel")).isEqualTo(reference);
@@ -125,8 +125,8 @@ class LinksUnitTest {
@Test
void detectsContainedLinks() {
Link first = new Link("http://localhost", "someRel");
Link second = new Link("http://localhost", "someOtherRel");
Link first = Link.of("http://localhost", "someRel");
Link second = Link.of("http://localhost", "someOtherRel");
assertThat(Links.of(first).contains(first)).isTrue();
assertThat(Links.of(first).contains(second)).isFalse();

View File

@@ -15,9 +15,21 @@
*/
package org.springframework.hateoas;
import lombok.RequiredArgsConstructor;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.function.Consumer;
import org.springframework.core.io.ClassPathResource;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
/**
* @author Oliver Drotbohm
@@ -38,4 +50,93 @@ public class MappingTestUtils {
return mapper;
}
public static ContextualMapper createMapper(Class<?> context, Consumer<ObjectMapper> configurer) {
ObjectMapper mapper = defaultObjectMapper();
configurer.accept(mapper);
return ContextualMapper.of(context, mapper);
}
@RequiredArgsConstructor(staticName = "of")
public static class ContextualMapper {
private final Class<?> context;
private final ObjectMapper mapper;
public JavaType getGenericType(Class<?> type, Class<?>... elements) {
return mapper.getTypeFactory().constructParametricType(type, elements);
}
public JavaType getGenericType(Class<?> type, JavaType element) {
return mapper.getTypeFactory().constructParametricType(type, element);
}
public String writeObject(Object source) {
try {
return mapper.writeValueAsString(source);
} catch (JsonProcessingException o_O) {
throw new RuntimeException(o_O);
}
}
public RepresentationModel<?> readObject(String filename) {
return readObject(filename, RepresentationModel.class);
}
public <T> T readObject(String filename, Class<T> type) {
TypeFactory factory = mapper.getTypeFactory();
JavaType javaType = factory.constructType(type);
return readObject(filename, javaType);
}
public <S> S readObject(String filename, Class<?> type, Class<?> elementType) {
TypeFactory factory = mapper.getTypeFactory();
JavaType javaType = factory.constructParametricType(type, elementType);
return readObject(filename, javaType);
}
public <S> S readObject(String filename, JavaType type) {
ClassPathResource resource = new ClassPathResource(filename, context);
try (InputStream stream = resource.getInputStream()) {
return mapper.readValue(stream, type);
} catch (IOException o_O) {
throw new RuntimeException(o_O);
}
}
public String readFile(String filename) {
ClassPathResource resource = new ClassPathResource(filename, context);
try (Scanner scanner = new Scanner(resource.getInputStream())) {
StringBuilder builder = new StringBuilder();
while (scanner.hasNextLine()) {
builder.append(scanner.nextLine());
if (scanner.hasNextLine()) {
builder.append(System.lineSeparator());
}
}
return builder.toString();
} catch (IOException o_O) {
throw new RuntimeException(o_O);
}
}
}
}

View File

@@ -36,13 +36,13 @@ class PagedModelUnitTest {
@BeforeEach
void setUp() {
resources = new PagedModel<>(Collections.emptyList(), metadata);
resources = PagedModel.of(Collections.emptyList(), metadata);
}
@Test
void discoversNextLink() {
resources.add(new Link("foo", IanaLinkRelations.NEXT.value()));
resources.add(Link.of("foo", IanaLinkRelations.NEXT.value()));
assertThat(resources.getNextLink()).isNotNull();
}
@@ -50,7 +50,7 @@ class PagedModelUnitTest {
@Test
void discoversPreviousLink() {
resources.add(new Link("custom", IanaLinkRelations.PREV.value()));
resources.add(Link.of("custom", IanaLinkRelations.PREV.value()));
assertThat(resources.getPreviousLink()).isNotNull();
}

View File

@@ -32,7 +32,7 @@ class RepresentationModelIntegrationTest extends AbstractJackson2MarshallingInte
void doesNotRenderId() throws Exception {
RepresentationModel<?> model = new RepresentationModel<>();
model.add(new Link("localhost"));
model.add(Link.of("localhost"));
assertThat(write(model)).isEqualTo(REFERENCE);
}
@@ -43,6 +43,6 @@ class RepresentationModelIntegrationTest extends AbstractJackson2MarshallingInte
RepresentationModel<?> model = read(REFERENCE, RepresentationModel.class);
assertThat(model.getLinks()).hasSize(1);
assertThat(model.getLinks()).contains(new Link("localhost"));
assertThat(model.getLinks()).contains(Link.of("localhost"));
}
}

View File

@@ -42,7 +42,7 @@ class RepresentationModelUnitTest {
@Test
void addsLinkCorrectly() {
Link link = new Link("foo", IanaLinkRelations.NEXT.value());
Link link = Link.of("foo", IanaLinkRelations.NEXT.value());
RepresentationModel<?> support = new RepresentationModel<>();
support.add(link);
@@ -55,8 +55,8 @@ class RepresentationModelUnitTest {
@Test
void addsMultipleLinkRelationsCorrectly() {
Link link = new Link("/customers/1", "customers");
Link link2 = new Link("/orders/1/customer", "customers");
Link link = Link.of("/customers/1", "customers");
Link link2 = Link.of("/orders/1/customer", "customers");
RepresentationModel<?> support = new RepresentationModel<>();
support.add(link, link2);
@@ -69,8 +69,8 @@ class RepresentationModelUnitTest {
@Test
void addsLinksCorrectly() {
Link first = new Link("foo", IanaLinkRelations.PREV.value());
Link second = new Link("bar", IanaLinkRelations.NEXT.value());
Link first = Link.of("foo", IanaLinkRelations.PREV.value());
Link second = Link.of("bar", IanaLinkRelations.NEXT.value());
RepresentationModel<?> support = new RepresentationModel<>();
support.add(Arrays.asList(first, second));
@@ -110,7 +110,7 @@ class RepresentationModelUnitTest {
TestUtils.assertEqualAndSameHashCode(first, second);
Link link = new Link("foo");
Link link = Link.of("foo");
first.add(link);
second.add(link);
@@ -122,7 +122,7 @@ class RepresentationModelUnitTest {
RepresentationModel<?> first = new RepresentationModel<>();
RepresentationModel<?> second = new RepresentationModel<>();
second.add(new Link("foo"));
second.add(Link.of("foo"));
TestUtils.assertNotEqualAndDifferentHashCode(first, second);
}
@@ -165,7 +165,7 @@ class RepresentationModelUnitTest {
void addsLinksViaVarargs() {
RepresentationModel<?> support = new RepresentationModel<>();
support.add(new Link("/self", "self"), new Link("/another", "another"));
support.add(Link.of("/self", "self"), Link.of("/another", "another"));
assertThat(support.hasLink("self")).isTrue();
assertThat(support.hasLink("another")).isTrue();
@@ -176,10 +176,10 @@ class RepresentationModelUnitTest {
RepresentationModel<?> model = new RepresentationModel<>();
model.addIf(true, () -> new Link("added", "foo"));
model.addIf(true, () -> Link.of("added", "foo"));
assertThat(model.hasLink("foo")).isTrue();
model.addIf(false, () -> new Link("not-added", "bar"));
model.addIf(false, () -> Link.of("not-added", "bar"));
assertThat(model.hasLink("bar")).isFalse();
}
@@ -188,10 +188,10 @@ class RepresentationModelUnitTest {
RepresentationModel<?> model = new RepresentationModel<>();
model.addAllIf(true, () -> Links.of(new Link("added", "foo")));
model.addAllIf(true, () -> Links.of(Link.of("added", "foo")));
assertThat(model.hasLink("foo")).isTrue();
model.addAllIf(false, () -> Links.of(new Link("not-added", "bar")));
model.addAllIf(false, () -> Links.of(Link.of("not-added", "bar")));
assertThat(model.hasLink("bar")).isFalse();
}
}

View File

@@ -53,7 +53,7 @@ class SimpleRepresentationModelAssemblerTest {
CollectionModel<EntityModel<Employee>> resources = assembler
.toCollectionModel(Collections.singletonList(new Employee("Frodo")));
assertThat(resources.getContent()).containsExactly(new EntityModel<>(new Employee("Frodo")));
assertThat(resources.getContent()).containsExactly(EntityModel.of(new Employee("Frodo")));
assertThat(resources.getLinks()).isEmpty();
}
@@ -67,7 +67,7 @@ class SimpleRepresentationModelAssemblerTest {
EntityModel<Employee> resource = assembler.toModel(new Employee("Frodo"));
assertThat(resource.getContent().getName()).isEqualTo("Frodo");
assertThat(resource.getLinks()).containsExactly(new Link("/employees").withRel("employees"));
assertThat(resource.getLinks()).containsExactly(Link.of("/employees").withRel("employees"));
}
/**
@@ -81,7 +81,7 @@ class SimpleRepresentationModelAssemblerTest {
.toCollectionModel(Collections.singletonList(new Employee("Frodo")));
assertThat(resources.getContent()).containsExactly(
new EntityModel<>(new Employee("Frodo"), new Link("/employees").withRel("employees")));
EntityModel.of(new Employee("Frodo"), Link.of("/employees").withRel("employees")));
assertThat(resources.getLinks()).isEmpty();
}
@@ -98,7 +98,7 @@ class SimpleRepresentationModelAssemblerTest {
@Override
public void addLinks(EntityModel<Employee> resource) {
resource.add(new Link("/employees").withRel("employees"));
resource.add(Link.of("/employees").withRel("employees"));
}
@Override

View File

@@ -38,19 +38,19 @@ public abstract class LinkDiscovererUnitTest {
void findsSingleLink() {
assertThat(getDiscoverer().findLinkWithRel("self", getInputString())) //
.hasValue(new Link("selfHref"));
.hasValue(Link.of("selfHref"));
Links links = getDiscoverer().findLinksWithRel("self", getInputString());
assertThat(links).hasSize(1);
assertThat(links).contains(new Link("selfHref"));
assertThat(links).contains(Link.of("selfHref"));
}
@Test
void findsFirstLink() {
assertThat(getDiscoverer().findLinkWithRel("relation", getInputString()))
.hasValue(new Link("firstHref", "relation"));
.hasValue(Link.of("firstHref", "relation"));
}
@Test
@@ -59,7 +59,7 @@ public abstract class LinkDiscovererUnitTest {
Links links = getDiscoverer().findLinksWithRel("relation", getInputString());
assertThat(links).hasSize(2);
assertThat(links).contains(new Link("firstHref", "relation"), new Link("secondHref", "relation"));
assertThat(links).contains(Link.of("firstHref", "relation"), Link.of("secondHref", "relation"));
}
@Test

View File

@@ -189,7 +189,7 @@ public class Server implements Closeable {
String baseResourceUri = String.format("%s/%s", rootResource(), collectionRel.value());
String resourceUri = String.format("%s/%s", baseResourceUri, UUID.randomUUID().toString());
baseResources.add(new Link(baseResourceUri, collectionRel), new Link(resourceUri, singleRel));
baseResources.add(Link.of(baseResourceUri, collectionRel), Link.of(resourceUri, singleRel));
register(resourceUri, resource);
@@ -198,13 +198,13 @@ public class Server implements Closeable {
public void finishMocking() {
CollectionModel<String> resources = new CollectionModel<>(Collections.emptyList());
CollectionModel<String> resources = CollectionModel.of(Collections.emptyList());
for (Link link : baseResources.keySet()) {
resources.add(link);
CollectionModel<String> nested = new CollectionModel<>(Collections.emptyList());
CollectionModel<String> nested = CollectionModel.of(Collections.emptyList());
nested.add(baseResources.get(link));
register(link.getHref(), nested);

View File

@@ -442,12 +442,12 @@ class TraversonTest {
private static void setUpActors() {
EntityModel<Actor> actor = new EntityModel<>(new Actor("Keanu Reaves"));
EntityModel<Actor> actor = EntityModel.of(new Actor("Keanu Reaves"));
String actorUri = server.mockResourceFor(actor);
Movie movie = new Movie("The Matrix");
EntityModel<Movie> resource = new EntityModel<>(movie);
resource.add(new Link(actorUri, "actor"));
EntityModel<Movie> resource = EntityModel.of(movie);
resource.add(Link.of(actorUri, "actor"));
server.mockResourceFor(resource);
server.finishMocking();

View File

@@ -96,7 +96,7 @@ class CustomHypermediaWebFluxTest {
return linkTo(methodOn(EmployeeController.class).findOne()).withSelfRel() //
.toMono() //
.map(link -> new EntityModel<>(new Employee("Frodo Baggins", "ring bearer"), link)); //
.map(link -> EntityModel.of(new Employee("Frodo Baggins", "ring bearer"), link)); //
}
}
}

View File

@@ -95,7 +95,7 @@ class CustomHypermediaWebMvcTest {
@GetMapping("/employees/1")
public EntityModel<Employee> findOne() {
return new EntityModel<>(new Employee("Frodo Baggins", "ring bearer"),
return EntityModel.of(new Employee("Frodo Baggins", "ring bearer"),
linkTo(methodOn(EmployeeController.class).findOne()).withSelfRel());
}
}

View File

@@ -498,7 +498,7 @@ class EnableHypermediaSupportIntegrationTest {
assertThat(mapper).hasValueSatisfying(it -> {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost").withSelfRel());
resourceSupport.add(Link.of("localhost").withSelfRel());
assertThatCode(() -> {
assertThat(it.writeValueAsString(resourceSupport)) //
@@ -518,7 +518,7 @@ class EnableHypermediaSupportIntegrationTest {
MediaTypes.HAL_JSON, //
mapper -> { //
RepresentationModel<?> resourceSupport = new RepresentationModel<>(); //
resourceSupport.add(new Link("localhost").withSelfRel()); //
resourceSupport.add(Link.of("localhost").withSelfRel()); //
assertThat(mapper.writeValueAsString(resourceSupport)) //
.isEqualTo("{\"_links\":{\"self\":[{\"href\":\"localhost\"}]}}"); //
} //

View File

@@ -53,12 +53,12 @@ class HypermediaWebClientBeanPostProcessorTest {
this.server = new Server();
EntityModel<Actor> actor = new EntityModel<>(new Actor("Keanu Reaves"));
EntityModel<Actor> actor = EntityModel.of(new Actor("Keanu Reaves"));
String actorUri = this.server.mockResourceFor(actor);
Movie movie = new Movie("The Matrix");
EntityModel<Movie> resource = new EntityModel<>(movie);
resource.add(new Link(actorUri, "actor"));
EntityModel<Movie> resource = EntityModel.of(movie);
resource.add(Link.of(actorUri, "actor"));
this.server.mockResourceFor(resource);
this.server.finishMocking();
@@ -125,7 +125,7 @@ class HypermediaWebClientBeanPostProcessorTest {
.retrieve() //
.bodyToMono(typeReference)) //
.as(StepVerifier::create) //
.expectNext(new EntityModel<>(new Actor("Keanu Reaves"))) //
.expectNext(EntityModel.of(new Actor("Keanu Reaves"))) //
.verifyComplete();
});
}

View File

@@ -287,8 +287,8 @@ class HypermediaWebFluxConfigurerTest {
.returnResult(RepresentationModel.class).getResponseBody().as(StepVerifier::create)
.expectNextMatches(resourceSupport -> {
assertThat(resourceSupport.getLinks()).containsExactlyInAnyOrder(new Link("/", IanaLinkRelations.SELF),
new Link("/employees", "employees"));
assertThat(resourceSupport.getLinks()).containsExactlyInAnyOrder(Link.of("/", IanaLinkRelations.SELF),
Link.of("/employees", "employees"));
return true;
}).verifyComplete();
@@ -298,14 +298,14 @@ class HypermediaWebFluxConfigurerTest {
.returnResult(this.resourcesEmployeeType).getResponseBody() //
.as(StepVerifier::create).expectNextMatches(resources -> {
assertThat(resources.getLinks()).containsExactlyInAnyOrder(new Link("/employees", IanaLinkRelations.SELF));
assertThat(resources.getLinks()).containsExactlyInAnyOrder(Link.of("/employees", IanaLinkRelations.SELF));
EntityModel<Employee> content = resources.getContent().iterator().next();
assertThat(content.getContent()).isEqualTo(new Employee("Frodo Baggins", "ring bearer"));
assertThat(content.getLinks()) //
.containsExactlyInAnyOrder(new Link("/employees/1", IanaLinkRelations.SELF),
new Link("/employees", "employees"));
.containsExactlyInAnyOrder(Link.of("/employees/1", IanaLinkRelations.SELF),
Link.of("/employees", "employees"));
return true;
}).verifyComplete();
@@ -317,8 +317,8 @@ class HypermediaWebFluxConfigurerTest {
assertThat(employee.getContent()).isEqualTo(new Employee("Frodo Baggins", "ring bearer"));
assertThat(employee.getLinks()) //
.containsExactlyInAnyOrder(new Link("/employees/1", IanaLinkRelations.SELF),
new Link("/employees", "employees"));
.containsExactlyInAnyOrder(Link.of("/employees/1", IanaLinkRelations.SELF),
Link.of("/employees", "employees"));
return true;
}).verifyComplete();
}
@@ -336,7 +336,7 @@ class HypermediaWebFluxConfigurerTest {
.expectNextMatches(resourceSupport -> {
assertThat(resourceSupport.getLinks()) //
.containsExactlyInAnyOrder(new Link("/", IanaLinkRelations.SELF), new Link("/employees", "employees"));
.containsExactlyInAnyOrder(Link.of("/", IanaLinkRelations.SELF), Link.of("/employees", "employees"));
return true;
}).verifyComplete();
@@ -352,7 +352,7 @@ class HypermediaWebFluxConfigurerTest {
.contentType(responseType).returnResult(this.resourcesEmployeeType).getResponseBody().as(StepVerifier::create)
.expectNextMatches(resources -> {
assertThat(resources.getLinks()).containsExactlyInAnyOrder(new Link("/employees", IanaLinkRelations.SELF));
assertThat(resources.getLinks()).containsExactlyInAnyOrder(Link.of("/employees", IanaLinkRelations.SELF));
Collection<EntityModel<Employee>> content = resources.getContent();
assertThat(content).hasSize(1);
@@ -361,8 +361,8 @@ class HypermediaWebFluxConfigurerTest {
assertThat(resource.getContent()).isEqualTo(new Employee("Frodo Baggins", "ring bearer"));
assertThat(resource.getLinks()) //
.containsExactlyInAnyOrder(new Link("/employees/1", IanaLinkRelations.SELF),
new Link("/employees", "employees"));
.containsExactlyInAnyOrder(Link.of("/employees/1", IanaLinkRelations.SELF),
Link.of("/employees", "employees"));
return true;
}).verifyComplete();
@@ -383,7 +383,7 @@ class HypermediaWebFluxConfigurerTest {
assertThat(employeeResource.getContent()).isEqualTo(new Employee("Frodo Baggins", "ring bearer"));
assertThat(employeeResource.getLinks()).containsExactlyInAnyOrder(
new Link("/employees/1", IanaLinkRelations.SELF), new Link("/employees", "employees"));
Link.of("/employees/1", IanaLinkRelations.SELF), Link.of("/employees", "employees"));
return true;
}).verifyComplete();
@@ -417,8 +417,8 @@ class HypermediaWebFluxConfigurerTest {
assertThat(resource.getContent()).isEqualTo(new Employee("Samwise Gamgee", "gardener"));
assertThat(resource.getLinks()) //
.containsExactlyInAnyOrder(new Link("/employees/1", IanaLinkRelations.SELF),
new Link("/employees", "employees"));
.containsExactlyInAnyOrder(Link.of("/employees/1", IanaLinkRelations.SELF),
Link.of("/employees", "employees"));
return true;
}).verifyComplete();
@@ -472,8 +472,8 @@ class HypermediaWebFluxConfigurerTest {
RepresentationModel<?> root = new RepresentationModel<>();
root.add(new Link("/").withSelfRel());
root.add(new Link("/employees").withRel("employees"));
root.add(Link.of("/").withSelfRel());
root.add(Link.of("/employees").withRel("employees"));
return root;
}
@@ -546,13 +546,13 @@ class HypermediaWebFluxConfigurerTest {
@Override
public void addLinks(EntityModel<Employee> resource) {
resource.add(new Link("/employees/1").withSelfRel());
resource.add(new Link("/employees").withRel("employees"));
resource.add(Link.of("/employees/1").withSelfRel());
resource.add(Link.of("/employees").withRel("employees"));
}
@Override
public void addLinks(CollectionModel<EntityModel<Employee>> resources) {
resources.add(new Link("/employees").withSelfRel());
resources.add(Link.of("/employees").withSelfRel());
}
}

View File

@@ -273,7 +273,7 @@ class HypermediaWebMvcConfigurerTest {
RepresentationModel<?> model = mapper.readValue(json, RepresentationModel.class);
assertThat(model.getLinks()) //
.containsExactlyInAnyOrder(new Link("/", IanaLinkRelations.SELF), new Link("/employees", "employees"));
.containsExactlyInAnyOrder(Link.of("/", IanaLinkRelations.SELF), Link.of("/employees", "employees"));
}
private void verifyAggregateRootServesHypermedia(MediaType mediaType) throws Exception {
@@ -295,7 +295,7 @@ class HypermediaWebMvcConfigurerTest {
CollectionModel<EntityModel<Employee>> resources = mapper.readValue(json, collectionModelType);
assertThat(resources.getLinks()).containsExactlyInAnyOrder(new Link("/employees", IanaLinkRelations.SELF));
assertThat(resources.getLinks()).containsExactlyInAnyOrder(Link.of("/employees", IanaLinkRelations.SELF));
Collection<EntityModel<Employee>> content = resources.getContent();
assertThat(content).hasSize(1);
@@ -304,8 +304,8 @@ class HypermediaWebMvcConfigurerTest {
assertThat(resource.getContent()).isEqualTo(new Employee("Frodo Baggins", "ring bearer"));
assertThat(resource.getLinks()) //
.containsExactlyInAnyOrder(new Link("/employees/1", IanaLinkRelations.SELF),
new Link("/employees", "employees"));
.containsExactlyInAnyOrder(Link.of("/employees/1", IanaLinkRelations.SELF),
Link.of("/employees", "employees"));
}
private void verifySingleItemResourceServesHypermedia(MediaType mediaType) throws Exception {
@@ -327,8 +327,8 @@ class HypermediaWebMvcConfigurerTest {
EntityModel<Employee> employeeResource = mapper.readValue(json, entityModelType);
assertThat(employeeResource.getContent()).isEqualTo(new Employee("Frodo Baggins", "ring bearer"));
assertThat(employeeResource.getLinks()).containsExactlyInAnyOrder(new Link("/employees/1", IanaLinkRelations.SELF),
new Link("/employees", "employees"));
assertThat(employeeResource.getLinks()).containsExactlyInAnyOrder(Link.of("/employees/1", IanaLinkRelations.SELF),
Link.of("/employees", "employees"));
}
private void verifyCreatingNewEntityWorks(MediaType mediaType) throws Exception {
@@ -358,8 +358,8 @@ class HypermediaWebMvcConfigurerTest {
assertThat(resource.getContent()).isEqualTo(new Employee("Samwise Gamgee", "gardener"));
assertThat(resource.getLinks()) //
.containsExactlyInAnyOrder(new Link("/employees/1", IanaLinkRelations.SELF),
new Link("/employees", "employees"));
.containsExactlyInAnyOrder(Link.of("/employees/1", IanaLinkRelations.SELF),
Link.of("/employees", "employees"));
}
private static ObjectMapper getMapper(MediaType mediaType) {
@@ -430,8 +430,8 @@ class HypermediaWebMvcConfigurerTest {
RepresentationModel<?> root = new RepresentationModel<>();
root.add(new Link("/").withSelfRel());
root.add(new Link("/employees").withRel("employees"));
root.add(Link.of("/").withSelfRel());
root.add(Link.of("/employees").withRel("employees"));
return root;
}
@@ -468,13 +468,13 @@ class HypermediaWebMvcConfigurerTest {
@Override
public void addLinks(EntityModel<Employee> resource) {
resource.add(new Link("/employees/1").withSelfRel());
resource.add(new Link("/employees").withRel("employees"));
resource.add(Link.of("/employees/1").withSelfRel());
resource.add(Link.of("/employees").withRel("employees"));
}
@Override
public void addLinks(CollectionModel<EntityModel<Employee>> resources) {
resources.add(new Link("/employees").withSelfRel());
resources.add(Link.of("/employees").withSelfRel());
}
}

View File

@@ -41,7 +41,7 @@ public class AffordancesUnitTests {
@Test
void affordanceConvenienceMethodChainsExistingLink() {
Link link = Affordances.of(new Link("/")) //
Link link = Affordances.of(Link.of("/")) //
.afford(HttpMethod.POST) //
.withInputAndOutput(Employee.class) //
.withName("name") //
@@ -63,7 +63,7 @@ public class AffordancesUnitTests {
@Test
void affordanceConvenienceMethodDefaultsNameBasedOnHttpVerb() {
Link link = Affordances.of(new Link("/")) //
Link link = Affordances.of(Link.of("/")) //
.afford(HttpMethod.POST) //
.withInputAndOutput(Employee.class) //
.toLink();

View File

@@ -68,7 +68,7 @@ class PropertyUtilsTest {
void simpleObjectWrappedAsResource() {
Employee employee = new Employee("Frodo Baggins", "ring bearer");
EntityModel<Employee> employeeResource = new EntityModel<>(employee);
EntityModel<Employee> employeeResource = EntityModel.of(employee);
Map<String, Object> properties = PropertyUtils.extractPropertyValues(employeeResource);

View File

@@ -70,7 +70,7 @@ class CollectionJsonSpecTest {
RepresentationModel<?> resource = mapper.readValue(specBasedJson, RepresentationModel.class);
assertThat(resource.getLinks()).hasSize(1);
assertThat(resource.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(new Link("https://example.org/friends/"));
assertThat(resource.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(Link.of("https://example.org/friends/"));
}
/**
@@ -87,8 +87,8 @@ class CollectionJsonSpecTest {
mapper.getTypeFactory().constructParametricType(EntityModel.class, Friend.class)));
assertThat(resources.getLinks()).hasSize(2);
assertThat(resources.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(new Link("https://example.org/friends/"));
assertThat(resources.getRequiredLink("feed")).isEqualTo(new Link("https://example.org/friends/rss", "feed"));
assertThat(resources.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(Link.of("https://example.org/friends/"));
assertThat(resources.getRequiredLink("feed")).isEqualTo(Link.of("https://example.org/friends/rss", "feed"));
assertThat(resources.getContent()).hasSize(3);
List<EntityModel<Friend>> friends = new ArrayList<>(resources.getContent());
@@ -96,27 +96,27 @@ class CollectionJsonSpecTest {
assertThat(friends.get(0).getContent().getEmail()).isEqualTo("jdoe@example.org");
assertThat(friends.get(0).getContent().getFullname()).isEqualTo("J. Doe");
assertThat(friends.get(0).getRequiredLink(IanaLinkRelations.SELF))
.isEqualTo(new Link("https://example.org/friends/jdoe"));
assertThat(friends.get(0).getRequiredLink("blog")).isEqualTo(new Link("https://examples.org/blogs/jdoe", "blog"));
.isEqualTo(Link.of("https://example.org/friends/jdoe"));
assertThat(friends.get(0).getRequiredLink("blog")).isEqualTo(Link.of("https://examples.org/blogs/jdoe", "blog"));
assertThat(friends.get(0).getRequiredLink("avatar"))
.isEqualTo(new Link("https://examples.org/images/jdoe", "avatar"));
.isEqualTo(Link.of("https://examples.org/images/jdoe", "avatar"));
assertThat(friends.get(1).getContent().getEmail()).isEqualTo("msmith@example.org");
assertThat(friends.get(1).getContent().getFullname()).isEqualTo("M. Smith");
assertThat(friends.get(1).getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("https://example.org/friends/msmith"));
assertThat(friends.get(1).getRequiredLink("blog")).isEqualTo(new Link("https://examples.org/blogs/msmith", "blog"));
.isEqualTo(Link.of("https://example.org/friends/msmith"));
assertThat(friends.get(1).getRequiredLink("blog")).isEqualTo(Link.of("https://examples.org/blogs/msmith", "blog"));
assertThat(friends.get(1).getRequiredLink("avatar"))
.isEqualTo(new Link("https://examples.org/images/msmith", "avatar"));
.isEqualTo(Link.of("https://examples.org/images/msmith", "avatar"));
assertThat(friends.get(2).getContent().getEmail()).isEqualTo("rwilliams@example.org");
assertThat(friends.get(2).getContent().getFullname()).isEqualTo("R. Williams");
assertThat(friends.get(2).getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("https://example.org/friends/rwilliams"));
.isEqualTo(Link.of("https://example.org/friends/rwilliams"));
assertThat(friends.get(2).getRequiredLink("blog"))
.isEqualTo(new Link("https://examples.org/blogs/rwilliams", "blog"));
.isEqualTo(Link.of("https://examples.org/blogs/rwilliams", "blog"));
assertThat(friends.get(2).getRequiredLink("avatar"))
.isEqualTo(new Link("https://examples.org/images/rwilliams", "avatar"));
.isEqualTo(Link.of("https://examples.org/images/rwilliams", "avatar"));
}
/**
@@ -132,14 +132,14 @@ class CollectionJsonSpecTest {
mapper.getTypeFactory().constructParametricType(EntityModel.class, Friend.class));
assertThat(resource.getLinks()).hasSize(6);
assertThat(resource.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(new Link("https://example.org/friends/jdoe"));
assertThat(resource.getRequiredLink("feed")).isEqualTo(new Link("https://example.org/friends/rss", "feed"));
assertThat(resource.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(Link.of("https://example.org/friends/jdoe"));
assertThat(resource.getRequiredLink("feed")).isEqualTo(Link.of("https://example.org/friends/rss", "feed"));
assertThat(resource.getRequiredLink("queries"))
.isEqualTo(new Link("https://example.org/friends/?queries", "queries"));
.isEqualTo(Link.of("https://example.org/friends/?queries", "queries"));
assertThat(resource.getRequiredLink("template"))
.isEqualTo(new Link("https://example.org/friends/?template", "template"));
assertThat(resource.getRequiredLink("blog")).isEqualTo(new Link("https://examples.org/blogs/jdoe", "blog"));
assertThat(resource.getRequiredLink("avatar")).isEqualTo(new Link("https://examples.org/images/jdoe", "avatar"));
.isEqualTo(Link.of("https://example.org/friends/?template", "template"));
assertThat(resource.getRequiredLink("blog")).isEqualTo(Link.of("https://examples.org/blogs/jdoe", "blog"));
assertThat(resource.getRequiredLink("avatar")).isEqualTo(Link.of("https://examples.org/images/jdoe", "avatar"));
assertThat(resource.getContent().getEmail()).isEqualTo("jdoe@example.org");
assertThat(resource.getContent().getFullname()).isEqualTo("J. Doe");
@@ -160,7 +160,7 @@ class CollectionJsonSpecTest {
assertThat(resources.getContent()).hasSize(0);
assertThat(resources.getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("https://example.org/friends/"));
.isEqualTo(Link.of("https://example.org/friends/"));
}
/**
@@ -178,7 +178,7 @@ class CollectionJsonSpecTest {
assertThat(resources.getContent()).hasSize(0);
assertThat(resources.getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("https://example.org/friends/"));
.isEqualTo(Link.of("https://example.org/friends/"));
}
/**
@@ -196,7 +196,7 @@ class CollectionJsonSpecTest {
assertThat(resources.getContent()).hasSize(0);
assertThat(resources.getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("https://example.org/friends/"));
.isEqualTo(Link.of("https://example.org/friends/"));
}
/**

View File

@@ -208,7 +208,7 @@ class CollectionJsonWebMvcIntegrationTest {
.andAffordance(afford(methodOn(EmployeeController.class).search(null, null)));
// Return the collection of employee resources along with the composite affordance
return new CollectionModel<>(employees, selfLink);
return CollectionModel.of(employees, selfLink);
}
@GetMapping("/employees/search")
@@ -239,7 +239,7 @@ class CollectionJsonWebMvcIntegrationTest {
.andAffordance(afford(methodOn(EmployeeController.class).search(null, null)));
// Return the collection of employee resources along with the composite affordance
return new CollectionModel<>(employees, selfLink);
return CollectionModel.of(employees, selfLink);
}
@GetMapping("/employees/{id}")
@@ -252,7 +252,7 @@ class CollectionJsonWebMvcIntegrationTest {
Link employeesLink = linkTo(methodOn(EmployeeController.class).all()).withRel("employees");
// Return the affordance + a link back to the entire collection resource.
return new EntityModel<>(EMPLOYEES.get(id),
return EntityModel.of(EMPLOYEES.get(id),
findOneLink.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, id))) //
.andAffordance(afford(methodOn(EmployeeController.class).partiallyUpdateEmployee(null, id))),
employeesLink);

View File

@@ -27,18 +27,17 @@ import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.AbstractJackson2MarshallingIntegrationTest;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Links;
import org.springframework.hateoas.MappingTestUtils;
import org.springframework.hateoas.PagedModel;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.mediatype.hal.SimplePojo;
import org.springframework.hateoas.support.MappingUtils;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
@@ -47,96 +46,92 @@ import com.fasterxml.jackson.databind.SerializationFeature;
* @author Greg Turnquist
* @author Oliver Drotbohm
*/
class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2MarshallingIntegrationTest {
class Jackson2CollectionJsonIntegrationTest {
static final Links PAGINATION_LINKS = Links.of( //
new Link("localhost", IanaLinkRelations.SELF), //
new Link("foo", IanaLinkRelations.NEXT), //
new Link("bar", IanaLinkRelations.PREV));
Link.of("localhost", IanaLinkRelations.SELF), //
Link.of("foo", IanaLinkRelations.NEXT), //
Link.of("bar", IanaLinkRelations.PREV));
MappingTestUtils.ContextualMapper mapper;
@BeforeEach
void setUpModule() {
mapper.registerModule(new Jackson2CollectionJsonModule());
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
this.mapper = MappingTestUtils.createMapper(getClass(), mapper -> {
mapper.registerModule(new Jackson2CollectionJsonModule());
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
});
}
@Test
void rendersSingleLinkAsObject() throws Exception {
void rendersSingleLinkAsObject() {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost").withSelfRel());
resourceSupport.add(Link.of("localhost").withSelfRel());
assertThat(write(resourceSupport))
.isEqualTo(MappingUtils.read(new ClassPathResource("resource-support.json", getClass())));
assertThat(mapper.writeObject(resourceSupport)).isEqualTo(mapper.readFile("resource-support.json"));
}
@Test
void deserializeSingleLink() throws Exception {
void deserializeSingleLink() {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost"));
expected.add(Link.of("localhost"));
assertThat(
read(MappingUtils.read(new ClassPathResource("resource-support.json", getClass())), RepresentationModel.class))
.isEqualTo(expected);
assertThat(mapper.readObject("resource-support.json")).isEqualTo(expected);
}
@Test
void rendersMultipleLinkAsArray() throws Exception {
void rendersMultipleLinkAsArray() {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost"));
resourceSupport.add(new Link("localhost2").withRel("orders"));
resourceSupport.add(Link.of("localhost"));
resourceSupport.add(Link.of("localhost2").withRel("orders"));
assertThat(write(resourceSupport))
.isEqualTo(MappingUtils.read(new ClassPathResource("resource-support-2.json", getClass())));
assertThat(mapper.writeObject(resourceSupport)).isEqualTo(mapper.readFile("resource-support-2.json"));
}
@Test
void rendersResourceSupportBasedObject() throws Exception {
void rendersResourceSupportBasedObject() {
ResourceWithAttributes resource = new ResourceWithAttributes("test value");
resource.add(new Link("localhost").withSelfRel());
resource.add(Link.of("localhost").withSelfRel());
assertThat(write(resource))
.isEqualTo(MappingUtils.read(new ClassPathResource("resource-support-3.json", getClass())));
assertThat(mapper.writeObject(resource)).isEqualTo(mapper.readFile("resource-support-3.json"));
}
@Test
void deserializeResourceSupportBasedObject() throws Exception {
void deserializeResourceSupportBasedObject() {
ResourceWithAttributes expected = new ResourceWithAttributes("test value");
expected.add(new Link("localhost").withSelfRel());
expected.add(Link.of("localhost").withSelfRel());
assertThat(read(MappingUtils.read(new ClassPathResource("resource-support-3.json", getClass())),
ResourceWithAttributes.class)).isEqualTo(expected);
assertThat(mapper.readObject("resource-support-3.json", ResourceWithAttributes.class)).isEqualTo(expected);
}
@Test
void deserializeMultipleLinks() throws Exception {
void deserializeMultipleLinks() {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost"));
expected.add(new Link("localhost2").withRel("orders"));
expected.add(Link.of("localhost"));
expected.add(Link.of("localhost2").withRel("orders"));
String read = MappingUtils.read(new ClassPathResource("resource-support-2.json", getClass()));
RepresentationModel<?> readResourceSupport = read(read, RepresentationModel.class);
assertThat(readResourceSupport.getLinks()).containsAll(expected.getLinks());
assertThat(mapper.readObject("resource-support-2.json").getLinks()).containsAll(expected.getLinks());
}
@Test
void rendersSimpleResourcesAsEmbedded() throws Exception {
void rendersSimpleResourcesAsEmbedded() {
List<String> content = new ArrayList<>();
content.add("first");
content.add("second");
CollectionModel<String> resources = new CollectionModel<>(content);
resources.add(new Link("localhost"));
CollectionModel<String> resources = CollectionModel.of(content);
resources.add(Link.of("localhost"));
assertThat(write(resources)).isEqualTo(MappingUtils.read(new ClassPathResource("resources.json", getClass())));
assertThat(mapper.writeObject(resources)).isEqualTo(mapper.readFile("resources.json"));
}
@Test
@@ -146,103 +141,92 @@ class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2MarshallingI
content.add("first");
content.add("second");
CollectionModel<String> expected = new CollectionModel<>(content);
expected.add(new Link("localhost"));
CollectionModel<String> expected = CollectionModel.of(content);
expected.add(Link.of("localhost"));
CollectionModel<String> result = mapper.readValue(
MappingUtils.read(new ClassPathResource("resources.json", getClass())),
mapper.getTypeFactory().constructParametricType(CollectionModel.class, String.class));
CollectionModel<String> result = mapper.readObject("resources.json", CollectionModel.class, String.class);
assertThat(result).isEqualTo(expected);
}
@Test
void renderResource() throws Exception {
void renderResource() {
EntityModel<String> data = new EntityModel<>("first", new Link("localhost"));
assertThat(write(data)).isEqualTo(MappingUtils.read(new ClassPathResource("resource.json", getClass())));
assertThat(mapper.writeObject(EntityModel.of("first", Link.of("localhost")))) //
.isEqualTo(mapper.readFile("resource.json"));
}
@Test
void deserializeResource() throws Exception {
void deserializeResource() {
EntityModel<?> expected = new EntityModel<>("first", new Link("localhost"));
EntityModel<String> actual = mapper.readObject("resource.json", EntityModel.class, String.class);
String source = MappingUtils.read(new ClassPathResource("resource.json", getClass()));
EntityModel<String> actual = mapper.readValue(source,
mapper.getTypeFactory().constructParametricType(EntityModel.class, String.class));
assertThat(actual).isEqualTo(expected);
assertThat(actual).isEqualTo(EntityModel.of("first", Link.of("localhost")));
}
@Test
void renderComplexStructure() throws Exception {
List<EntityModel<String>> data = new ArrayList<>();
data.add(new EntityModel<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new EntityModel<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
data.add(EntityModel.of("first", Link.of("localhost"), Link.of("orders").withRel("orders")));
data.add(EntityModel.of("second", Link.of("remotehost"), Link.of("order").withRel("orders")));
CollectionModel<EntityModel<String>> resources = new CollectionModel<>(
data);
resources.add(new Link("localhost"));
resources.add(new Link("/page/2").withRel("next"));
CollectionModel<EntityModel<String>> resources = CollectionModel.of(data);
resources.add(Link.of("localhost"));
resources.add(Link.of("/page/2").withRel("next"));
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())));
assertThat(mapper.writeObject(resources)).isEqualTo(mapper.readFile("resources-with-resource-objects.json"));
}
@Test
void deserializeResources() throws Exception {
void deserializeResources() {
List<EntityModel<String>> data = new ArrayList<>();
data.add(new EntityModel<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new EntityModel<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
data.add(EntityModel.of("first", Link.of("localhost"), Link.of("orders").withRel("orders")));
data.add(EntityModel.of("second", Link.of("remotehost"), Link.of("order").withRel("orders")));
CollectionModel<?> expected = new CollectionModel<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
CollectionModel<?> expected = CollectionModel.of(data);
expected.add(Link.of("localhost"));
expected.add(Link.of("/page/2").withRel("next"));
CollectionModel<EntityModel<String>> actual = mapper.readValue(
MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())),
mapper.getTypeFactory().constructParametricType(CollectionModel.class,
mapper.getTypeFactory().constructParametricType(EntityModel.class, String.class)));
JavaType entityModel = mapper.getGenericType(EntityModel.class, String.class);
JavaType collectionModel = mapper.getGenericType(CollectionModel.class, entityModel);
CollectionModel<?> actual = mapper.readObject("resources-with-resource-objects.json", collectionModel);
assertThat(actual).isEqualTo(expected);
}
@Test
void renderSimplePojos() throws Exception {
List<EntityModel<SimplePojo>> data = new ArrayList<>();
data.add(new EntityModel<>(new SimplePojo("text", 1), new Link("localhost"),
new Link("orders").withRel("orders")));
data.add(new EntityModel<>(new SimplePojo("text2", 2), new Link("localhost")));
data.add(EntityModel.of(new SimplePojo("text", 1), Link.of("localhost"), Link.of("orders").withRel("orders")));
data.add(EntityModel.of(new SimplePojo("text2", 2), Link.of("localhost")));
CollectionModel<EntityModel<SimplePojo>> resources = new CollectionModel<>(
data);
resources.add(new Link("localhost"));
resources.add(new Link("/page/2").withRel("next"));
CollectionModel<EntityModel<SimplePojo>> resources = CollectionModel.of(data);
resources.add(Link.of("localhost"));
resources.add(Link.of("/page/2").withRel("next"));
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("resources-simple-pojos.json", getClass())));
assertThat(mapper.writeObject(resources)).isEqualTo(mapper.readFile("resources-simple-pojos.json"));
}
@Test
void serializesPagedResource() throws Exception {
String actual = write(setupAnnotatedPagedResources());
assertThat(actual).isEqualTo(MappingUtils.read(new ClassPathResource("paged-resources.json", getClass())));
assertThat(mapper.writeObject(setupAnnotatedPagedResources())) //
.isEqualTo(mapper.readFile("paged-resources.json"));
}
@Test
void deserializesPagedResource() throws Exception {
PagedModel<EntityModel<SimplePojo>> result = mapper.readValue(
MappingUtils.read(new ClassPathResource("paged-resources.json", getClass())),
mapper.getTypeFactory().constructParametricType(PagedModel.class,
mapper.getTypeFactory().constructParametricType(EntityModel.class, SimplePojo.class)));
JavaType entityModel = mapper.getGenericType(EntityModel.class, SimplePojo.class);
JavaType pagedModel = mapper.getGenericType(PagedModel.class, entityModel);
mapper.readObject("paged-resources.json", pagedModel);
PagedModel<?> result = mapper.readObject("paged-resources.json", pagedModel);
assertThat(result).isEqualTo(setupAnnotatedPagedResources());
}
@@ -250,10 +234,10 @@ class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2MarshallingI
private static CollectionModel<EntityModel<SimplePojo>> setupAnnotatedPagedResources() {
List<EntityModel<SimplePojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost")));
content.add(new EntityModel<>(new SimplePojo("test2", 2), new Link("localhost")));
content.add(EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost")));
content.add(EntityModel.of(new SimplePojo("test2", 2), Link.of("localhost")));
return new PagedModel<>(content, null, PAGINATION_LINKS);
return PagedModel.of(content, null, PAGINATION_LINKS);
}
@Data

View File

@@ -48,15 +48,15 @@ class JacksonSerializationTest {
void createSimpleCollection() throws IOException {
CollectionJson<?> collection = new CollectionJson<>().withVersion("1.0").withHref("localhost")
.withLinks(Links.of(new Link("foo").withSelfRel())) //
.withLinks(Links.of(Link.of("foo").withSelfRel())) //
.withItems(new CollectionJsonItem<>() //
.withHref("localhost") //
.withRawData("Greetings programs") //
.withLinks(new Link("localhost").withSelfRel()), //
.withLinks(Link.of("localhost").withSelfRel()), //
new CollectionJsonItem<>() //
.withHref("localhost") //
.withRawData("Yo") //
.withLinks(new Link("localhost/orders").withRel("orders")));
.withLinks(Link.of("localhost/orders").withRel("orders")));
String actual = mapper.writeValueAsString(collection);

View File

@@ -89,21 +89,21 @@ class DefaultCurieProviderUnitTest {
@Test
void doesNotPrefixIanaRels() {
assertThat(provider.getNamespacedRelFrom(new Link("https://amazon.com"))) //
assertThat(provider.getNamespacedRelFrom(Link.of("https://amazon.com"))) //
.isEqualTo(HalLinkRelation.of(IanaLinkRelations.SELF));
}
@Test
void prefixesNormalRels() {
assertThat(provider.getNamespacedRelFrom(new Link("https://amazon.com", "book"))) //
assertThat(provider.getNamespacedRelFrom(Link.of("https://amazon.com", "book"))) //
.isEqualTo(HalLinkRelation.curied("acme", "book"));
}
@Test
void doesNotPrefixQualifiedRels() {
assertThat(provider.getNamespacedRelFrom(new Link("https://amazon.com", "custom:rel")))
assertThat(provider.getNamespacedRelFrom(Link.of("https://amazon.com", "custom:rel")))
.isEqualTo(HalLinkRelation.curied("custom", "rel"));
}
@@ -113,7 +113,7 @@ class DefaultCurieProviderUnitTest {
@Test
void prefixesNormalRelsThatHaveExtraRFC5988Attributes() {
Link link = new Link("https://amazon.com", "custom:rel") //
Link link = Link.of("https://amazon.com", "custom:rel") //
.withHreflang("en") //
.withTitle("the title") //
.withMedia("the media") //
@@ -191,7 +191,7 @@ class DefaultCurieProviderUnitTest {
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
Links links = Links.of(new Link("http://localhost", "name:foo"));
Links links = Links.of(Link.of("http://localhost", "name:foo"));
Collection<? extends Object> curies = provider.getCurieInformation(links);
assertThat(curies).hasSize(1);

View File

@@ -84,8 +84,8 @@ class Jackson2HalIntegrationTest {
static final String ANNOTATED_PAGED_RESOURCES = "{\"_embedded\":{\"pojos\":[{\"text\":\"test1\",\"number\":1,\"_links\":{\"self\":{\"href\":\"localhost\"}}},{\"text\":\"test2\",\"number\":2,\"_links\":{\"self\":{\"href\":\"localhost\"}}}]},\"_links\":{\"next\":{\"href\":\"foo\"},\"prev\":{\"href\":\"bar\"}},\"page\":{\"size\":2,\"totalElements\":4,\"totalPages\":2,\"number\":0}}";
static final Links PAGINATION_LINKS = Links.of(new Link("foo", IanaLinkRelations.NEXT.value()),
new Link("bar", IanaLinkRelations.PREV.value()));
static final Links PAGINATION_LINKS = Links.of(Link.of("foo", IanaLinkRelations.NEXT.value()),
Link.of("bar", IanaLinkRelations.PREV.value()));
static final String CURIED_DOCUMENT = "{\"_links\":{\"self\":{\"href\":\"foo\"},\"foo:myrel\":{\"href\":\"bar\"},\"curies\":[{\"href\":\"http://localhost:8080/rels/{rel}\",\"name\":\"foo\",\"templated\":true}]}}";
static final String MULTIPLE_CURIES_DOCUMENT = "{\"_links\":{\"default:myrel\":{\"href\":\"foo\"},\"curies\":[{\"href\":\"bar\",\"name\":\"foo\"},{\"href\":\"foo\",\"name\":\"bar\"}]}}";
@@ -113,7 +113,7 @@ class Jackson2HalIntegrationTest {
void rendersSingleLinkAsObject() throws Exception {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost"));
resourceSupport.add(Link.of("localhost"));
assertThat(mapper.writeValueAsString(resourceSupport)).isEqualTo(SINGLE_LINK_REFERENCE);
}
@@ -125,7 +125,7 @@ class Jackson2HalIntegrationTest {
void rendersAllExtraRFC5988Attributes() throws Exception {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost", "self") //
resourceSupport.add(Link.of("localhost", "self") //
.withHreflang("en") //
.withTitle("the title") //
.withType("the type") //
@@ -144,7 +144,7 @@ class Jackson2HalIntegrationTest {
void deserializeAllExtraRFC5988Attributes() throws Exception {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost", "self") //
expected.add(Link.of("localhost", "self") //
.withHreflang("en") //
.withTitle("the title") //
.withType("the type") //
@@ -157,7 +157,7 @@ class Jackson2HalIntegrationTest {
void rendersWithOneExtraRFC5988Attribute() throws Exception {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost", "self").withTitle("the title"));
resourceSupport.add(Link.of("localhost", "self").withTitle("the title"));
assertThat(mapper.writeValueAsString(resourceSupport)).isEqualTo(SINGLE_WITH_ONE_EXTRA_ATTRIBUTES);
}
@@ -169,7 +169,7 @@ class Jackson2HalIntegrationTest {
void deserializeOneExtraRFC5988Attribute() throws Exception {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost", "self").withTitle("the title"));
expected.add(Link.of("localhost", "self").withTitle("the title"));
assertThat(mapper.readValue(SINGLE_WITH_ONE_EXTRA_ATTRIBUTES, RepresentationModel.class)).isEqualTo(expected);
}
@@ -177,7 +177,7 @@ class Jackson2HalIntegrationTest {
@Test
void deserializeSingleLink() throws Exception {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost"));
expected.add(Link.of("localhost"));
assertThat(mapper.readValue(SINGLE_LINK_REFERENCE, RepresentationModel.class)).isEqualTo(expected);
}
@@ -188,8 +188,8 @@ class Jackson2HalIntegrationTest {
void rendersMultipleLinkAsArray() throws Exception {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost"));
resourceSupport.add(new Link("localhost2"));
resourceSupport.add(Link.of("localhost"));
resourceSupport.add(Link.of("localhost2"));
assertThat(mapper.writeValueAsString(resourceSupport)).isEqualTo(LIST_LINK_REFERENCE);
}
@@ -198,8 +198,8 @@ class Jackson2HalIntegrationTest {
void deserializeMultipleLinks() throws Exception {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost"));
expected.add(new Link("localhost2"));
expected.add(Link.of("localhost"));
expected.add(Link.of("localhost2"));
assertThat(mapper.readValue(LIST_LINK_REFERENCE, RepresentationModel.class)).isEqualTo(expected);
}
@@ -211,8 +211,8 @@ class Jackson2HalIntegrationTest {
content.add("first");
content.add("second");
CollectionModel<String> resources = new CollectionModel<>(content);
resources.add(new Link("localhost"));
CollectionModel<String> resources = CollectionModel.of(content);
resources.add(Link.of("localhost"));
assertThat(mapper.writeValueAsString(resources)).isEqualTo(SIMPLE_EMBEDDED_RESOURCE_REFERENCE);
}
@@ -224,8 +224,8 @@ class Jackson2HalIntegrationTest {
content.add("first");
content.add("second");
CollectionModel<String> expected = new CollectionModel<>(content);
expected.add(new Link("localhost"));
CollectionModel<String> expected = CollectionModel.of(content);
expected.add(Link.of("localhost"));
CollectionModel<String> result = mapper.readValue(SIMPLE_EMBEDDED_RESOURCE_REFERENCE,
mapper.getTypeFactory().constructParametricType(CollectionModel.class, String.class));
@@ -238,10 +238,10 @@ class Jackson2HalIntegrationTest {
void rendersSingleResourceResourcesAsEmbedded() throws Exception {
List<EntityModel<SimplePojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost")));
content.add(EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost")));
CollectionModel<EntityModel<SimplePojo>> resources = new CollectionModel<>(content);
resources.add(new Link("localhost"));
CollectionModel<EntityModel<SimplePojo>> resources = CollectionModel.of(content);
resources.add(Link.of("localhost"));
assertThat(mapper.writeValueAsString(resources)).isEqualTo(SINGLE_EMBEDDED_RESOURCE_REFERENCE);
}
@@ -250,10 +250,10 @@ class Jackson2HalIntegrationTest {
void deserializesSingleResourceResourcesAsEmbedded() throws Exception {
List<EntityModel<SimplePojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost")));
content.add(EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost")));
CollectionModel<EntityModel<SimplePojo>> expected = new CollectionModel<>(content);
expected.add(new Link("localhost"));
CollectionModel<EntityModel<SimplePojo>> expected = CollectionModel.of(content);
expected.add(Link.of("localhost"));
TypeFactory typeFactory = mapper.getTypeFactory();
CollectionModel<EntityModel<SimplePojo>> result = mapper.readValue(SINGLE_EMBEDDED_RESOURCE_REFERENCE,
@@ -268,7 +268,7 @@ class Jackson2HalIntegrationTest {
void rendersMultipleResourceResourcesAsEmbedded() throws Exception {
CollectionModel<EntityModel<SimplePojo>> resources = setupResources();
resources.add(new Link("localhost"));
resources.add(Link.of("localhost"));
assertThat(mapper.writeValueAsString(resources)).isEqualTo(LIST_EMBEDDED_RESOURCE_REFERENCE);
}
@@ -277,7 +277,7 @@ class Jackson2HalIntegrationTest {
void deserializesMultipleResourceResourcesAsEmbedded() throws Exception {
CollectionModel<EntityModel<SimplePojo>> expected = setupResources();
expected.add(new Link("localhost"));
expected.add(Link.of("localhost"));
CollectionModel<EntityModel<SimplePojo>> result = mapper.readValue(LIST_EMBEDDED_RESOURCE_REFERENCE,
mapper.getTypeFactory().constructParametricType(CollectionModel.class,
@@ -293,10 +293,10 @@ class Jackson2HalIntegrationTest {
void serializesAnnotatedResourceResourcesAsEmbedded() throws Exception {
List<EntityModel<SimpleAnnotatedPojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test1", 1), new Link("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test1", 1), Link.of("localhost")));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> resources = new CollectionModel<>(content);
resources.add(new Link("localhost"));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> resources = CollectionModel.of(content);
resources.add(Link.of("localhost"));
assertThat(mapper.writeValueAsString(resources)).isEqualTo(ANNOTATED_EMBEDDED_RESOURCE_REFERENCE);
}
@@ -308,10 +308,10 @@ class Jackson2HalIntegrationTest {
void deserializesAnnotatedResourceResourcesAsEmbedded() throws Exception {
List<EntityModel<SimpleAnnotatedPojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test1", 1), new Link("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test1", 1), Link.of("localhost")));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> expected = new CollectionModel<>(content);
expected.add(new Link("localhost"));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> expected = CollectionModel.of(content);
expected.add(Link.of("localhost"));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> result = mapper.readValue(ANNOTATED_EMBEDDED_RESOURCE_REFERENCE,
mapper.getTypeFactory().constructParametricType(CollectionModel.class,
@@ -367,8 +367,8 @@ class Jackson2HalIntegrationTest {
@Test
void rendersCuriesCorrectly() throws Exception {
CollectionModel<Object> resources = new CollectionModel<>(Collections.emptySet(), new Link("foo"),
new Link("bar", "myrel"));
CollectionModel<Object> resources = CollectionModel.of(Collections.emptySet(), Link.of("foo"),
Link.of("bar", "myrel"));
assertThat(getCuriedObjectMapper().writeValueAsString(resources)).isEqualTo(CURIED_DOCUMENT);
}
@@ -379,7 +379,7 @@ class Jackson2HalIntegrationTest {
@Test
void doesNotRenderCuriesIfNoLinkIsPresent() throws Exception {
CollectionModel<Object> resources = new CollectionModel<>(Collections.emptySet());
CollectionModel<Object> resources = CollectionModel.of(Collections.emptySet());
assertThat(getCuriedObjectMapper().writeValueAsString(resources)).isEqualTo(EMPTY_DOCUMENT);
}
@@ -389,8 +389,8 @@ class Jackson2HalIntegrationTest {
@Test
void doesNotRenderCuriesIfNoCurieLinkIsPresent() throws Exception {
CollectionModel<Object> resources = new CollectionModel<>(Collections.emptySet());
resources.add(new Link("foo"));
CollectionModel<Object> resources = CollectionModel.of(Collections.emptySet());
resources.add(Link.of("foo"));
assertThat(getCuriedObjectMapper().writeValueAsString(resources)).isEqualTo(SINGLE_NON_CURIE_LINK);
}
@@ -402,7 +402,7 @@ class Jackson2HalIntegrationTest {
void rendersTemplate() throws Exception {
RepresentationModel<?> support = new RepresentationModel<>();
support.add(new Link("/foo{?bar}", "search"));
support.add(Link.of("/foo{?bar}", "search"));
assertThat(mapper.writeValueAsString(support)).isEqualTo(LINK_TEMPLATE);
}
@@ -413,8 +413,8 @@ class Jackson2HalIntegrationTest {
@Test
void rendersMultipleCuries() throws Exception {
CollectionModel<Object> resources = new CollectionModel<>(Collections.emptySet());
resources.add(new Link("foo", "myrel"));
CollectionModel<Object> resources = CollectionModel.of(Collections.emptySet());
resources.add(Link.of("foo", "myrel"));
CurieProvider provider = new DefaultCurieProvider("default", UriTemplate.of("/doc{?rel}")) {
@Override
@@ -437,7 +437,7 @@ class Jackson2HalIntegrationTest {
List<Object> values = new ArrayList<>();
values.add(wrappers.emptyCollectionOf(SimpleAnnotatedPojo.class));
CollectionModel<Object> resources = new CollectionModel<>(values);
CollectionModel<Object> resources = CollectionModel.of(values);
assertThat(mapper.writeValueAsString(resources)).isEqualTo("{\"_embedded\":{\"pojos\":[]}}");
}
@@ -465,7 +465,7 @@ class Jackson2HalIntegrationTest {
.halObjectMapper(new HalConfiguration().withRenderSingleLinks(RenderSingleLinks.AS_ARRAY));
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost").withSelfRel());
resourceSupport.add(Link.of("localhost").withSelfRel());
assertThat(mapper.writeValueAsString(resourceSupport))
.isEqualTo("{\"_links\":{\"self\":[{\"href\":\"localhost\"}]}}");
@@ -478,7 +478,7 @@ class Jackson2HalIntegrationTest {
void handleTemplatedLinksOnDeserialization() throws IOException {
RepresentationModel<?> original = new RepresentationModel<>();
original.add(new Link("/orders{?id}", "order"));
original.add(Link.of("/orders{?id}", "order"));
String serialized = mapper.writeValueAsString(original);
@@ -496,7 +496,7 @@ class Jackson2HalIntegrationTest {
.halObjectMapper(new HalConfiguration().withRenderSingleLinksFor("foo", RenderSingleLinks.AS_ARRAY));
RepresentationModel<?> resource = new RepresentationModel<>();
resource.add(new Link("/some-href", "foo"));
resource.add(Link.of("/some-href", "foo"));
assertThat(mapper.writeValueAsString(resource)) //
.isEqualTo("{\"_links\":{\"foo\":[{\"href\":\"/some-href\"}]}}");
@@ -505,7 +505,7 @@ class Jackson2HalIntegrationTest {
@Test // #1019
void doesNotRenderTitleForEmptyString() throws Exception {
Link link = new Link("/some-href", "foo");
Link link = Link.of("/some-href", "foo");
assertThat(mapper.writeValueAsString(new Jackson2HalModule.HalLink(link, ""))) //
.isEqualTo("{\"href\":\"/some-href\"}");
@@ -526,9 +526,9 @@ class Jackson2HalIntegrationTest {
@Test // #1132
void forwardsPropertyNamingStrategyToNonIanaLinkRelations() throws JsonProcessingException {
CollectionModel<Object> model = new CollectionModel<>(Arrays.asList(new SomeSample()));
model.add(new Link("/foo", LinkRelation.of("someSample")));
model.add(new Link("/foo/form", IanaLinkRelations.EDIT_FORM));
CollectionModel<Object> model = CollectionModel.of(Arrays.asList(new SomeSample()));
model.add(Link.of("/foo", LinkRelation.of("someSample")));
model.add(Link.of("/foo/form", IanaLinkRelations.EDIT_FORM));
ObjectMapper objectMapper = mapper.copy() //
.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) //
@@ -548,8 +548,8 @@ class Jackson2HalIntegrationTest {
@Test // #1132
void doesNotApplyPropertyNamingStrategyToLinkRelationsIfConfigurationOptsOut() throws Exception {
CollectionModel<Object> model = new CollectionModel<>(Arrays.asList(new SomeSample()));
model.add(new Link("/foo", LinkRelation.of("someSample")));
CollectionModel<Object> model = CollectionModel.of(Arrays.asList(new SomeSample()));
model.add(Link.of("/foo", LinkRelation.of("someSample")));
ObjectMapper mapper = HalTestUtils.halObjectMapper(new HalConfiguration() //
.withApplyPropertyNamingStrategy(false)) //
@@ -571,7 +571,7 @@ class Jackson2HalIntegrationTest {
map.put("key", "value");
map.put("anotherKey", "anotherValue");
EntityModel<?> model = new EntityModel<>(map, new Link("foo", IanaLinkRelations.SELF));
EntityModel<?> model = EntityModel.of(map, Link.of("foo", IanaLinkRelations.SELF));
DocumentContext context = JsonPath.parse(mapper.writeValueAsString(model));
@@ -621,7 +621,7 @@ class Jackson2HalIntegrationTest {
ObjectMapper objectMapper = getCuriedObjectMapper(CurieProvider.NONE, messageSource);
RepresentationModel<?> resource = new RepresentationModel<>();
resource.add(new Link("target", "ns:foobar"));
resource.add(Link.of("target", "ns:foobar"));
assertThat(objectMapper.writeValueAsString(resource)).isEqualTo(LINK_WITH_TITLE);
}
@@ -629,28 +629,28 @@ class Jackson2HalIntegrationTest {
private static CollectionModel<EntityModel<SimpleAnnotatedPojo>> setupAnnotatedPagedResources() {
List<EntityModel<SimpleAnnotatedPojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test1", 1), new Link("localhost")));
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test2", 2), new Link("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test1", 1), Link.of("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test2", 2), Link.of("localhost")));
return new PagedModel<>(content, new PageMetadata(2, 0, 4), PAGINATION_LINKS);
return PagedModel.of(content, new PageMetadata(2, 0, 4), PAGINATION_LINKS);
}
private static CollectionModel<EntityModel<SimpleAnnotatedPojo>> setupAnnotatedResources() {
List<EntityModel<SimpleAnnotatedPojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test1", 1), new Link("localhost")));
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test2", 2), new Link("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test1", 1), Link.of("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test2", 2), Link.of("localhost")));
return new CollectionModel<>(content);
return CollectionModel.of(content);
}
private static CollectionModel<EntityModel<SimplePojo>> setupResources() {
List<EntityModel<SimplePojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost")));
content.add(new EntityModel<>(new SimplePojo("test2", 2), new Link("localhost")));
content.add(EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost")));
content.add(EntityModel.of(new SimplePojo("test2", 2), Link.of("localhost")));
return new CollectionModel<>(content);
return CollectionModel.of(content);
}
private ObjectMapper getCuriedObjectMapper() {

View File

@@ -119,7 +119,7 @@ class RenderHypermediaForDefaultAcceptHeadersTest {
Link selfLink = linkTo(methodOn(EmployeeController.class).all()).withSelfRel();
// Return the collection of employee resources along with the composite affordance
return new CollectionModel<>(employees, selfLink);
return CollectionModel.of(employees, selfLink);
}
@GetMapping("/employees/{id}")
@@ -132,7 +132,7 @@ class RenderHypermediaForDefaultAcceptHeadersTest {
Link employeesLink = linkTo(methodOn(EmployeeController.class).all()).withRel("employees");
// Return the affordance + a link back to the entire collection resource.
return new EntityModel<>(EMPLOYEES.get(id), findOneLink, employeesLink);
return EntityModel.of(EMPLOYEES.get(id), findOneLink, employeesLink);
}
}

View File

@@ -115,8 +115,8 @@ class HalFormsMessageConverterUnitTest {
.andProperty(property); //
HalFormsDocument expected = HalFormsDocument.empty() //
.andLink(new Link("/employees").withRel("collection")) //
.andLink(new Link("/employees/1").withSelfRel())//
.andLink(Link.of("/employees").withRel("collection")) //
.andLink(Link.of("/employees/1").withSelfRel())//
.andTemplate("foo", template);
final ByteArrayOutputStream stream = new ByteArrayOutputStream();

View File

@@ -48,7 +48,7 @@ class HalFormsTemplateBuilderUnitTest {
HalFormsTemplateBuilder builder = new HalFormsTemplateBuilder(configuration, MessageResolver.DEFAULTS_ONLY);
PatternExample resource = new PatternExample();
resource.add(Affordances.of(new Link("/examples")) //
resource.add(Affordances.of(Link.of("/examples")) //
.afford(HttpMethod.POST) //
.withInput(PatternExample.class) //
.toLink());
@@ -66,12 +66,12 @@ class HalFormsTemplateBuilderUnitTest {
@Test
void allPropertiesAreOptionalForPatchRequests() throws Exception {
Affordances.of(new Link("/example")) //
Affordances.of(Link.of("/example")) //
.afford(HttpMethod.PATCH) //
.withInput(RequiredProperty.class);
RequiredProperty model = new RequiredProperty();
model.add(Affordances.of(new Link("/example")) //
model.add(Affordances.of(Link.of("/example")) //
.afford(HttpMethod.PATCH) //
.withInput(RequiredProperty.class) //
.andAfford(HttpMethod.POST) //

View File

@@ -79,8 +79,8 @@ import com.jayway.jsonpath.PathNotFoundException;
class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegrationTest {
static final Links PAGINATION_LINKS = Links.of( //
new Link("foo", IanaLinkRelations.NEXT), //
new Link("bar", IanaLinkRelations.PREV) //
Link.of("foo", IanaLinkRelations.NEXT), //
Link.of("bar", IanaLinkRelations.PREV) //
);
@BeforeEach
@@ -100,7 +100,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void rendersSingleLinkAsObject() throws Exception {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost"));
resourceSupport.add(Link.of("localhost"));
assertThat(write(resourceSupport))
.isEqualTo(MappingUtils.read(new ClassPathResource("single-link-reference.json", getClass())));
@@ -110,7 +110,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void deserializeSingleLink() throws Exception {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost"));
expected.add(Link.of("localhost"));
assertThat(read(MappingUtils.read(new ClassPathResource("single-link-reference.json", getClass())),
RepresentationModel.class)).isEqualTo(expected);
@@ -120,8 +120,8 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void rendersMultipleLinkAsArray() throws Exception {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost"));
resourceSupport.add(new Link("localhost2"));
resourceSupport.add(Link.of("localhost"));
resourceSupport.add(Link.of("localhost2"));
assertThat(write(resourceSupport))
.isEqualTo(MappingUtils.read(new ClassPathResource("list-link-reference.json", getClass())));
@@ -131,8 +131,8 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void deserializeMultipleLinks() throws Exception {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost"));
expected.add(new Link("localhost2"));
expected.add(Link.of("localhost"));
expected.add(Link.of("localhost2"));
assertThat(read(MappingUtils.read(new ClassPathResource("list-link-reference.json", getClass())),
RepresentationModel.class)).isEqualTo(expected);
@@ -143,7 +143,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
EmployeeResource resource = new EmployeeResource("Frodo Baggins");
Link link = Affordances.of(new Link("/employees/1")) //
Link link = Affordances.of(Link.of("/employees/1")) //
.afford(HttpMethod.POST) //
.withInputAndOutput(EmployeeResource.class) //
.withName("foo") //
@@ -158,7 +158,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
@Test
void rendersResource() throws Exception {
EntityModel<SimplePojo> resource = new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost"));
EntityModel<SimplePojo> resource = EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost"));
assertThat(write(resource))
.isEqualTo(MappingUtils.read(new ClassPathResource("simple-resource-unwrapped.json", getClass())));
@@ -167,7 +167,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
@Test
void deserializesResource() throws IOException {
EntityModel<SimplePojo> expected = new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost"));
EntityModel<SimplePojo> expected = EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost"));
EntityModel<SimplePojo> result = mapper.readValue(
MappingUtils.read(new ClassPathResource("simple-resource-unwrapped.json", getClass())),
@@ -183,8 +183,8 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
content.add("first");
content.add("second");
CollectionModel<String> resources = new CollectionModel<>(content);
resources.add(new Link("localhost"));
CollectionModel<String> resources = CollectionModel.of(content);
resources.add(Link.of("localhost"));
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("simple-embedded-resource-reference.json", getClass())));
@@ -197,8 +197,8 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
content.add("first");
content.add("second");
CollectionModel<String> expected = new CollectionModel<>(content);
expected.add(new Link("localhost"));
CollectionModel<String> expected = CollectionModel.of(content);
expected.add(Link.of("localhost"));
CollectionModel<String> result = mapper.readValue(
MappingUtils.read(new ClassPathResource("simple-embedded-resource-reference.json", getClass())),
@@ -212,10 +212,10 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void rendersSingleResourceResourcesAsEmbedded() throws Exception {
List<EntityModel<SimplePojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost")));
content.add(EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost")));
CollectionModel<EntityModel<SimplePojo>> resources = new CollectionModel<>(content);
resources.add(new Link("localhost"));
CollectionModel<EntityModel<SimplePojo>> resources = CollectionModel.of(content);
resources.add(Link.of("localhost"));
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("single-embedded-resource-reference.json", getClass())));
@@ -225,10 +225,10 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void deserializesSingleResourceResourcesAsEmbedded() throws Exception {
List<EntityModel<SimplePojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost")));
content.add(EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost")));
CollectionModel<EntityModel<SimplePojo>> expected = new CollectionModel<>(content);
expected.add(new Link("localhost"));
CollectionModel<EntityModel<SimplePojo>> expected = CollectionModel.of(content);
expected.add(Link.of("localhost"));
CollectionModel<EntityModel<SimplePojo>> result = mapper.readValue(
MappingUtils.read(new ClassPathResource("single-embedded-resource-reference.json", getClass())),
@@ -242,7 +242,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void rendersMultipleResourceResourcesAsEmbedded() throws Exception {
CollectionModel<EntityModel<SimplePojo>> resources = setupResources();
resources.add(new Link("localhost"));
resources.add(Link.of("localhost"));
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("multiple-resource-resources.json", getClass())));
@@ -252,7 +252,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void deserializesMultipleResourceResourcesAsEmbedded() throws Exception {
CollectionModel<EntityModel<SimplePojo>> expected = setupResources();
expected.add(new Link("localhost"));
expected.add(Link.of("localhost"));
CollectionModel<EntityModel<SimplePojo>> result = mapper.readValue(
MappingUtils.read(new ClassPathResource("multiple-resource-resources.json", getClass())),
@@ -266,10 +266,10 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void serializesAnnotatedResourceResourcesAsEmbedded() throws Exception {
List<EntityModel<SimpleAnnotatedPojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test1", 1), new Link("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test1", 1), Link.of("localhost")));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> resources = new CollectionModel<>(content);
resources.add(new Link("localhost"));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> resources = CollectionModel.of(content);
resources.add(Link.of("localhost"));
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("annotated-resource-resources.json", getClass())));
@@ -279,10 +279,10 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void deserializesAnnotatedResourceResourcesAsEmbedded() throws Exception {
List<EntityModel<SimpleAnnotatedPojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test1", 1), new Link("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test1", 1), Link.of("localhost")));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> expected = new CollectionModel<>(content);
expected.add(new Link("localhost"));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> expected = CollectionModel.of(content);
expected.add(Link.of("localhost"));
CollectionModel<EntityModel<SimpleAnnotatedPojo>> result = mapper.readValue(
MappingUtils.read(new ClassPathResource("annotated-resource-resources.json", getClass())),
@@ -328,8 +328,8 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
@Test
void rendersCuriesCorrectly() throws Exception {
CollectionModel<Object> resources = new CollectionModel<>(Collections.emptySet(), new Link("foo"),
new Link("bar", "myrel"));
CollectionModel<Object> resources = CollectionModel.of(Collections.emptySet(), Link.of("foo"),
Link.of("bar", "myrel"));
assertThat(getCuriedObjectMapper().writeValueAsString(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("curied-document.json", getClass())));
@@ -338,7 +338,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
@Test
void doesNotRenderCuriesIfNoLinkIsPresent() throws Exception {
CollectionModel<Object> resources = new CollectionModel<>(Collections.emptySet());
CollectionModel<Object> resources = CollectionModel.of(Collections.emptySet());
assertThat(getCuriedObjectMapper().writeValueAsString(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("empty-document.json", getClass())));
}
@@ -346,8 +346,8 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
@Test
void doesNotRenderCuriesIfNoCurieLinkIsPresent() throws Exception {
CollectionModel<Object> resources = new CollectionModel<>(Collections.emptySet());
resources.add(new Link("foo"));
CollectionModel<Object> resources = CollectionModel.of(Collections.emptySet());
resources.add(Link.of("foo"));
assertThat(getCuriedObjectMapper().writeValueAsString(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("single-non-curie-document.json", getClass())));
@@ -357,7 +357,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void rendersTemplate() throws Exception {
RepresentationModel<?> support = new RepresentationModel<>();
support.add(new Link("/foo{?bar}", "search"));
support.add(Link.of("/foo{?bar}", "search"));
assertThat(write(support)).isEqualTo(MappingUtils.read(new ClassPathResource("link-template.json", getClass())));
}
@@ -365,8 +365,8 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
@Test
void rendersMultipleCuries() throws Exception {
CollectionModel<Object> resources = new CollectionModel<>(Collections.emptySet());
resources.add(new Link("foo", "myrel"));
CollectionModel<Object> resources = CollectionModel.of(Collections.emptySet());
resources.add(Link.of("foo", "myrel"));
CurieProvider provider = new DefaultCurieProvider("default", UriTemplate.of("/doc{?rel}")) {
@Override
@@ -387,7 +387,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
List<Object> values = new ArrayList<>();
values.add(wrappers.emptyCollectionOf(SimpleAnnotatedPojo.class));
CollectionModel<Object> resources = new CollectionModel<>(values);
CollectionModel<Object> resources = CollectionModel.of(values);
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("empty-embedded-pojos.json", getClass())));
@@ -410,7 +410,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
void handleTemplatedLinksOnDeserialization() throws IOException {
RepresentationModel<?> original = new RepresentationModel<>();
original.add(new Link("/orders{?id}", "order"));
original.add(Link.of("/orders{?id}", "order"));
String serialized = mapper.writeValueAsString(original);
@@ -432,14 +432,14 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
StaticMessageSource source = new StaticMessageSource();
source.addMessage(key, Locale.US, "Vorname");
Link link = Affordances.of(new Link("some:link")) //
Link link = Affordances.of(Link.of("some:link")) //
.afford(HttpMethod.POST) //
.withInput(HalFormsPayload.class) //
.withOutput(Object.class) //
.withName("sample") //
.toLink();
EntityModel<HalFormsPayload> model = new EntityModel<>(new HalFormsPayload(), link);
EntityModel<HalFormsPayload> model = EntityModel.of(new HalFormsPayload(), link);
ObjectMapper mapper = getCuriedObjectMapper(CurieProvider.NONE, source);
assertThatCode(() -> {
@@ -465,12 +465,12 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
StaticMessageSource source = new StaticMessageSource();
source.addMessage(key, Locale.US, "Template title");
Link link = Affordances.of(new Link("some:link")) //
Link link = Affordances.of(Link.of("some:link")) //
.afford(HttpMethod.POST) //
.withInput(HalFormsPayload.class) //
.toLink();
EntityModel<HalFormsPayload> model = new EntityModel<>(new HalFormsPayload(), link);
EntityModel<HalFormsPayload> model = EntityModel.of(new HalFormsPayload(), link);
ObjectMapper mapper = getCuriedObjectMapper(CurieProvider.NONE, source);
assertThatCode(() -> {
@@ -504,12 +504,12 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
@Test
void considersJsr303AnnotationsForTemplates() throws Exception {
Link link = Affordances.of(new Link("localhost:8080")) //
Link link = Affordances.of(Link.of("localhost:8080")) //
.afford(HttpMethod.POST) //
.withInput(Jsr303Sample.class) //
.toLink();
EntityModel<Jsr303Sample> model = new EntityModel<>(new Jsr303Sample(), link);
EntityModel<Jsr303Sample> model = EntityModel.of(new Jsr303Sample(), link);
assertValueForPath(model, "$._templates.default.properties[0].readOnly", true);
assertValueForPath(model, "$._templates.default.properties[0].regex", "[\\w\\s]");
@@ -549,7 +549,7 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
ObjectMapper objectMapper = getCuriedObjectMapper(CurieProvider.NONE, messageSource);
RepresentationModel<?> resource = new RepresentationModel<>();
resource.add(new Link("target", "ns:foobar"));
resource.add(Link.of("target", "ns:foobar"));
assertThat(objectMapper.writeValueAsString(resource))
.isEqualTo(MappingUtils.read(new ClassPathResource("link-with-title.json", getClass())));
@@ -558,28 +558,28 @@ class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegra
private static CollectionModel<EntityModel<SimplePojo>> setupResources() {
List<EntityModel<SimplePojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost")));
content.add(new EntityModel<>(new SimplePojo("test2", 2), new Link("localhost")));
content.add(EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost")));
content.add(EntityModel.of(new SimplePojo("test2", 2), Link.of("localhost")));
return new CollectionModel<>(content);
return CollectionModel.of(content);
}
private static CollectionModel<EntityModel<SimpleAnnotatedPojo>> setupAnnotatedResources() {
List<EntityModel<SimpleAnnotatedPojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test1", 1), new Link("localhost")));
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test2", 2), new Link("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test1", 1), Link.of("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test2", 2), Link.of("localhost")));
return new CollectionModel<>(content);
return CollectionModel.of(content);
}
private static CollectionModel<EntityModel<SimpleAnnotatedPojo>> setupAnnotatedPagedResources() {
List<EntityModel<SimpleAnnotatedPojo>> content = new ArrayList<>();
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test1", 1), new Link("localhost")));
content.add(new EntityModel<>(new SimpleAnnotatedPojo("test2", 2), new Link("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test1", 1), Link.of("localhost")));
content.add(EntityModel.of(new SimpleAnnotatedPojo("test2", 2), Link.of("localhost")));
return new PagedModel<>(content, new PagedModel.PageMetadata(2, 0, 4), PAGINATION_LINKS);
return PagedModel.of(content, new PagedModel.PageMetadata(2, 0, 4), PAGINATION_LINKS);
}
private ObjectMapper getCuriedObjectMapper() {

View File

@@ -51,9 +51,9 @@ import com.fasterxml.jackson.databind.SerializationFeature;
class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegrationTest {
static final Links PAGINATION_LINKS = Links.of( //
new Link("localhost", IanaLinkRelations.SELF), //
new Link("foo", IanaLinkRelations.NEXT), //
new Link("bar", IanaLinkRelations.PREV) //
Link.of("localhost", IanaLinkRelations.SELF), //
Link.of("foo", IanaLinkRelations.NEXT), //
Link.of("bar", IanaLinkRelations.PREV) //
);
@BeforeEach
@@ -70,7 +70,7 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void rendersSingleLinkAsObject() throws Exception {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost").withSelfRel());
resourceSupport.add(Link.of("localhost").withSelfRel());
assertThat(write(resourceSupport))
.isEqualTo(MappingUtils.read(new ClassPathResource("resource-support.json", getClass())));
@@ -83,7 +83,7 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeSingleLink() throws Exception {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost"));
expected.add(Link.of("localhost"));
assertThat(
read(MappingUtils.read(new ClassPathResource("resource-support.json", getClass())), RepresentationModel.class))
@@ -97,8 +97,8 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void rendersMultipleLinkAsArray() throws Exception {
RepresentationModel<?> resourceSupport = new RepresentationModel<>();
resourceSupport.add(new Link("localhost"));
resourceSupport.add(new Link("localhost2").withRel("orders"));
resourceSupport.add(Link.of("localhost"));
resourceSupport.add(Link.of("localhost2").withRel("orders"));
assertThat(write(resourceSupport))
.isEqualTo(MappingUtils.read(new ClassPathResource("resource-support-2.json", getClass())));
@@ -111,8 +111,8 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeMultipleLinks() throws Exception {
RepresentationModel<?> expected = new RepresentationModel<>();
expected.add(new Link("localhost"));
expected.add(new Link("localhost2").withRel("orders"));
expected.add(Link.of("localhost"));
expected.add(Link.of("localhost2").withRel("orders"));
assertThat(read(MappingUtils.read(new ClassPathResource("resource-support-2.json", getClass())),
RepresentationModel.class)).isEqualTo(expected);
@@ -128,8 +128,8 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
content.add("first");
content.add("second");
CollectionModel<String> resources = new CollectionModel<>(content);
resources.add(new Link("localhost"));
CollectionModel<String> resources = CollectionModel.of(content);
resources.add(Link.of("localhost"));
assertThat(write(resources)).isEqualTo(MappingUtils.read(new ClassPathResource("resources.json", getClass())));
}
@@ -144,8 +144,8 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
content.add("first");
content.add("second");
CollectionModel<String> expected = new CollectionModel<>(content);
expected.add(new Link("localhost"));
CollectionModel<String> expected = CollectionModel.of(content);
expected.add(Link.of("localhost"));
String resourcesJson = MappingUtils.read(new ClassPathResource("resources.json", getClass()));
JavaType resourcesType = mapper.getTypeFactory().constructParametricType(CollectionModel.class, String.class);
@@ -161,11 +161,11 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeComplexResourcesSimply() throws IOException {
List<EntityModel<String>> content = new ArrayList<>();
content.add(new EntityModel<>("first"));
content.add(new EntityModel<>("second"));
content.add(EntityModel.of("first"));
content.add(EntityModel.of("second"));
CollectionModel<EntityModel<String>> expected = new CollectionModel<>(content);
expected.add(new Link("localhost"));
CollectionModel<EntityModel<String>> expected = CollectionModel.of(content);
expected.add(Link.of("localhost"));
String resourcesJson = MappingUtils.read(new ClassPathResource("resources.json", getClass()));
@@ -183,7 +183,7 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
@Test
void renderSimpleResource() throws Exception {
EntityModel<String> data = new EntityModel<>("first", new Link("localhost"));
EntityModel<String> data = EntityModel.of("first", Link.of("localhost"));
assertThat(write(data)).isEqualTo(MappingUtils.read(new ClassPathResource("resource.json", getClass())));
}
@@ -194,7 +194,7 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
@Test
void renderResourceWithCustomRel() throws Exception {
EntityModel<String> data2 = new EntityModel<>("second", new Link("localhost").withRel("custom"));
EntityModel<String> data2 = EntityModel.of("second", Link.of("localhost").withRel("custom"));
assertThat(write(data2)).isEqualTo(MappingUtils.read(new ClassPathResource("resource2.json", getClass())));
}
@@ -205,8 +205,8 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
@Test
void renderResourceWithMultipleLinks() throws Exception {
EntityModel<String> data3 = new EntityModel<>("third", new Link("localhost"), new Link("second").withRel("second"),
new Link("third").withRel("third"));
EntityModel<String> data3 = EntityModel.of("third", Link.of("localhost"), Link.of("second").withRel("second"),
Link.of("third").withRel("third"));
assertThat(write(data3)).isEqualTo(MappingUtils.read(new ClassPathResource("resource3.json", getClass())));
}
@@ -217,9 +217,9 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
@Test
void renderResourceWithMultipleRels() throws Exception {
EntityModel<String> data4 = new EntityModel<>("third", new Link("localhost"),
new Link("localhost").withRel("https://example.org/rels/todo"), new Link("second").withRel("second"),
new Link("third").withRel("third"));
EntityModel<String> data4 = EntityModel.of("third", Link.of("localhost"),
Link.of("localhost").withRel("https://example.org/rels/todo"), Link.of("second").withRel("second"),
Link.of("third").withRel("third"));
assertThat(write(data4)).isEqualTo(MappingUtils.read(new ClassPathResource("resource4.json", getClass())));
}
@@ -232,28 +232,28 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
JavaType resourceStringType = mapper.getTypeFactory().constructParametricType(EntityModel.class, String.class);
EntityModel<?> expected = new EntityModel<>("first", new Link("localhost"));
EntityModel<?> expected = EntityModel.of("first", Link.of("localhost"));
EntityModel<String> actual = mapper.readValue(MappingUtils.read(new ClassPathResource("resource.json", getClass())),
resourceStringType);
assertThat(actual).isEqualTo(expected);
EntityModel<String> expected2 = new EntityModel<>("second", new Link("localhost").withRel("custom"));
EntityModel<String> expected2 = EntityModel.of("second", Link.of("localhost").withRel("custom"));
EntityModel<String> actual2 = mapper
.readValue(MappingUtils.read(new ClassPathResource("resource2.json", getClass())), resourceStringType);
assertThat(actual2).isEqualTo(expected2);
EntityModel<String> expected3 = new EntityModel<>("third", new Link("localhost"),
new Link("second").withRel("second"), new Link("third").withRel("third"));
EntityModel<String> expected3 = EntityModel.of("third", Link.of("localhost"),
Link.of("second").withRel("second"), Link.of("third").withRel("third"));
EntityModel<String> actual3 = mapper
.readValue(MappingUtils.read(new ClassPathResource("resource3.json", getClass())), resourceStringType);
assertThat(actual3).isEqualTo(expected3);
EntityModel<String> expected4 = new EntityModel<>("third", new Link("localhost"),
new Link("localhost").withRel("https://example.org/rels/todo"), new Link("second").withRel("second"),
new Link("third").withRel("third"));
EntityModel<String> expected4 = EntityModel.of("third", Link.of("localhost"),
Link.of("localhost").withRel("https://example.org/rels/todo"), Link.of("second").withRel("second"),
Link.of("third").withRel("third"));
EntityModel<String> actual4 = mapper
.readValue(MappingUtils.read(new ClassPathResource("resource4.json", getClass())), resourceStringType);
@@ -267,12 +267,12 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void renderComplexStructure() throws Exception {
List<EntityModel<String>> data = new ArrayList<>();
data.add(new EntityModel<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new EntityModel<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
data.add(EntityModel.of("first", Link.of("localhost"), Link.of("orders").withRel("orders")));
data.add(EntityModel.of("second", Link.of("remotehost"), Link.of("order").withRel("orders")));
CollectionModel<EntityModel<String>> resources = new CollectionModel<>(data);
resources.add(new Link("localhost"));
resources.add(new Link("/page/2").withRel("next"));
CollectionModel<EntityModel<String>> resources = CollectionModel.of(data);
resources.add(Link.of("localhost"));
resources.add(Link.of("/page/2").withRel("next"));
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())));
@@ -285,12 +285,12 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeResources() throws Exception {
List<EntityModel<String>> data = new ArrayList<>();
data.add(new EntityModel<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new EntityModel<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
data.add(EntityModel.of("first", Link.of("localhost"), Link.of("orders").withRel("orders")));
data.add(EntityModel.of("second", Link.of("remotehost"), Link.of("order").withRel("orders")));
CollectionModel<?> expected = new CollectionModel<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
CollectionModel<?> expected = CollectionModel.of(data);
expected.add(Link.of("localhost"));
expected.add(Link.of("/page/2").withRel("next"));
CollectionModel<EntityModel<String>> actual = mapper.readValue(
MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())),
@@ -307,12 +307,12 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeEmptyValue() throws Exception {
List<EntityModel<String>> data = new ArrayList<>();
data.add(new EntityModel<>("", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new EntityModel<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
data.add(EntityModel.of("", Link.of("localhost"), Link.of("orders").withRel("orders")));
data.add(EntityModel.of("second", Link.of("remotehost"), Link.of("order").withRel("orders")));
CollectionModel<?> expected = new CollectionModel<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
CollectionModel<?> expected = CollectionModel.of(data);
expected.add(Link.of("localhost"));
expected.add(Link.of("/page/2").withRel("next"));
CollectionModel<EntityModel<String>> actual = mapper.readValue(
MappingUtils.read(new ClassPathResource("resources-with-resource-objects-and-empty-value.json", getClass())),
@@ -329,12 +329,12 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void serializeEmptyResources() throws Exception {
List<EntityModel<String>> data = new ArrayList<>();
data.add(new EntityModel<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new EntityModel<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
data.add(EntityModel.of("first", Link.of("localhost"), Link.of("orders").withRel("orders")));
data.add(EntityModel.of("second", Link.of("remotehost"), Link.of("order").withRel("orders")));
CollectionModel<?> source = new CollectionModel<>(data);
source.add(new Link("localhost"));
source.add(new Link("/page/2").withRel("next"));
CollectionModel<?> source = CollectionModel.of(data);
source.add(Link.of("localhost"));
source.add(Link.of("/page/2").withRel("next"));
assertThat(write(source))
.isEqualTo(MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())));
@@ -347,12 +347,12 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeEmptyResources() {
List<EntityModel<String>> data = new ArrayList<>();
data.add(new EntityModel<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new EntityModel<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
data.add(EntityModel.of("first", Link.of("localhost"), Link.of("orders").withRel("orders")));
data.add(EntityModel.of("second", Link.of("remotehost"), Link.of("order").withRel("orders")));
CollectionModel<?> expected = new CollectionModel<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
CollectionModel<?> expected = CollectionModel.of(data);
expected.add(Link.of("localhost"));
expected.add(Link.of("/page/2").withRel("next"));
assertThatThrownBy(() -> mapper.readValue( //
MappingUtils.read(new ClassPathResource("resources-with-empty-resource-objects.json", getClass())), //
@@ -374,9 +374,9 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
data.add("first");
data.add("second");
CollectionModel<?> expected = new CollectionModel<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
CollectionModel<?> expected = CollectionModel.of(data);
expected.add(Link.of("localhost"));
expected.add(Link.of("/page/2").withRel("next"));
CollectionModel<String> actual = mapper.readValue(
MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())),
@@ -392,7 +392,7 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void serializeWrappedSimplePojo() throws Exception {
Employee employee = new Employee("Frodo", "ring bearer");
EntityModel<Employee> expected = new EntityModel<>(employee, new Link("/employees/1").withSelfRel());
EntityModel<Employee> expected = EntityModel.of(employee, Link.of("/employees/1").withSelfRel());
String actual = MappingUtils.read(new ClassPathResource("resource-with-simple-pojo.json", getClass()));
@@ -406,7 +406,7 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeWrappedSimplePojo() throws IOException {
Employee employee = new Employee("Frodo", "ring bearer");
EntityModel<Employee> expected = new EntityModel<>(employee, new Link("/employees/1").withSelfRel());
EntityModel<Employee> expected = EntityModel.of(employee, Link.of("/employees/1").withSelfRel());
EntityModel<Employee> actual = mapper.readValue(
MappingUtils.read(new ClassPathResource("resource-with-simple-pojo.json", getClass())),
@@ -422,7 +422,7 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeWrappedEmptyPojo() throws IOException {
Employee employee = new Employee();
EntityModel<Employee> expected = new EntityModel<>(employee, new Link("/employees/1").withSelfRel());
EntityModel<Employee> expected = EntityModel.of(employee, Link.of("/employees/1").withSelfRel());
EntityModel<Employee> actual = mapper.readValue(
MappingUtils.read(new ClassPathResource("resource-with-empty-pojo.json", getClass())),
@@ -438,8 +438,8 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void serializeConcreteResourceSupport() throws Exception {
EmployeeResource expected = new EmployeeResource("Frodo", "ring bearer");
expected.add(new Link("/employees/1").withSelfRel());
expected.add(new Link("/employees").withRel("employees"));
expected.add(Link.of("/employees/1").withSelfRel());
expected.add(Link.of("/employees").withRel("employees"));
String actual = MappingUtils.read(new ClassPathResource("resource-support-pojo.json", getClass()));
@@ -453,8 +453,8 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeConcreteResourceSupport() throws Exception {
EmployeeResource expected = new EmployeeResource("Frodo", "ring bearer");
expected.add(new Link("/employees/1").withSelfRel());
expected.add(new Link("/employees").withRel("employees"));
expected.add(Link.of("/employees/1").withSelfRel());
expected.add(Link.of("/employees").withRel("employees"));
EmployeeResource actual = mapper.readValue(
MappingUtils.read(new ClassPathResource("resource-support-pojo.json", getClass())), EmployeeResource.class);
@@ -469,8 +469,8 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void deserializeEmptyConcreteResourceSupport() throws Exception {
EmployeeResource expected = new EmployeeResource(null, null);
expected.add(new Link("/employees/1").withSelfRel());
expected.add(new Link("/employees").withRel("employees"));
expected.add(Link.of("/employees/1").withSelfRel());
expected.add(Link.of("/employees").withRel("employees"));
EmployeeResource actual = mapper.readValue(
MappingUtils.read(new ClassPathResource("resource-support-pojo-empty.json", getClass())),
@@ -524,7 +524,7 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
void handleTemplatedLinksOnDeserialization() throws IOException {
RepresentationModel<?> original = new RepresentationModel<>();
original.add(new Link("/orders{?id}", "order"));
original.add(Link.of("/orders{?id}", "order"));
String serialized = mapper.writeValueAsString(original);
@@ -547,10 +547,10 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration
List<EntityModel<Employee>> content = new ArrayList<>();
Employee employee = new Employee("Frodo", "ring bearer");
EntityModel<Employee> employeeResource = new EntityModel<>(employee, new Link("/employees/1").withSelfRel());
EntityModel<Employee> employeeResource = EntityModel.of(employee, Link.of("/employees/1").withSelfRel());
content.add(employeeResource);
return new PagedModel<>(content, new PagedModel.PageMetadata(size, 0, totalElements), PAGINATION_LINKS);
return PagedModel.of(content, new PagedModel.PageMetadata(size, 0, totalElements), PAGINATION_LINKS);
}
@Data

View File

@@ -65,9 +65,9 @@ class VndErrorsMarshallingTest {
String expected = read(new ClassPathResource("vnderror-single-item.json", getClass()));
VndError actual = new VndError("Validation failed", "/username", 42,
new Link("http://path.to/user/resource/1", IanaLinkRelations.ABOUT),
new Link("http://path.to/describes", IanaLinkRelations.DESCRIBES),
new Link("http://path.to/help", IanaLinkRelations.HELP));
Link.of("http://path.to/user/resource/1", IanaLinkRelations.ABOUT),
Link.of("http://path.to/describes", IanaLinkRelations.DESCRIBES),
Link.of("http://path.to/help", IanaLinkRelations.HELP));
assertThat(this.mapper.readValue(expected, VndError.class)).isEqualTo(actual);
}
@@ -76,9 +76,9 @@ class VndErrorsMarshallingTest {
public void singleItemVndErrorShouldSerialize() throws IOException {
VndError error = new VndError("Validation failed", "/username", 42, //
new Link("http://path.to/user/resource/1", IanaLinkRelations.ABOUT),
new Link("http://path.to/describes", IanaLinkRelations.DESCRIBES),
new Link("http://path.to/help", IanaLinkRelations.HELP));
Link.of("http://path.to/user/resource/1", IanaLinkRelations.ABOUT),
Link.of("http://path.to/describes", IanaLinkRelations.DESCRIBES),
Link.of("http://path.to/help", IanaLinkRelations.HELP));
String json = read(new ClassPathResource("vnderror-single-item.json", getClass()));
@@ -91,10 +91,10 @@ class VndErrorsMarshallingTest {
String json = read(new ClassPathResource("vnderror-multiple-items.json", getClass()));
VndError error1 = new VndError("\"username\" field validation failed", null, 50, //
new Link("http://.../", IanaLinkRelations.HELP));
Link.of("http://.../", IanaLinkRelations.HELP));
VndError error2 = new VndError("\"postcode\" field validation failed", null, 55, //
new Link("http://.../", IanaLinkRelations.HELP));
Link.of("http://.../", IanaLinkRelations.HELP));
VndErrors vndErrors = new VndErrors().withError(error1).withError(error2);
@@ -105,10 +105,10 @@ class VndErrorsMarshallingTest {
public void multipleItemVndErrorsShouldSerialize() throws IOException {
VndError error1 = new VndError("\"username\" field validation failed", null, 50, //
new Link("http://.../", IanaLinkRelations.HELP));
Link.of("http://.../", IanaLinkRelations.HELP));
VndError error2 = new VndError("\"postcode\" field validation failed", null, 55, //
new Link("http://.../", IanaLinkRelations.HELP));
Link.of("http://.../", IanaLinkRelations.HELP));
VndErrors vndErrors = new VndErrors().withError(error1).withError(error2);
@@ -121,12 +121,12 @@ class VndErrorsMarshallingTest {
public void nestedVndErrorsShouldSerialize() throws IOException {
VndError error = new VndError("Username must contain at least three characters", "/username", (Integer) null, //
new Link("http://path.to/user/resource/1", IanaLinkRelations.ABOUT));
Link.of("http://path.to/user/resource/1", IanaLinkRelations.ABOUT));
VndErrors vndErrors = new VndErrors().withError(error)
.withLink(new Link("http://path.to/describes").withRel(IanaLinkRelations.DESCRIBES))
.withLink(new Link("http://path.to/help").withRel(IanaLinkRelations.HELP))
.withLink(new Link("http://path.to/user/resource/1").withRel(IanaLinkRelations.ABOUT))
.withLink(Link.of("http://path.to/describes").withRel(IanaLinkRelations.DESCRIBES))
.withLink(Link.of("http://path.to/help").withRel(IanaLinkRelations.HELP))
.withLink(Link.of("http://path.to/user/resource/1").withRel(IanaLinkRelations.ABOUT))
.withMessage("Validation failed").withLogref(42);
String json = read(new ClassPathResource("vnderror-nested.json", getClass()));

View File

@@ -54,12 +54,12 @@ class VndErrorsUnitTest {
@Test
public void vndErrorsUsingSingleErrorArguments() {
VndErrors errors = new VndErrors().withError(new VndError("message", "/path", 50, new Link("/link").withSelfRel()));
VndErrors errors = new VndErrors().withError(new VndError("message", "/path", 50, Link.of("/link").withSelfRel()));
assertThat(errors.getTotal()).isNull();
assertThat(errors.getContent()).hasSize(1);
assertThat(errors.getContent())
.containsExactly(new VndError("message", "/path", 50, new Link("/link").withSelfRel()));
.containsExactly(new VndError("message", "/path", 50, Link.of("/link").withSelfRel()));
}
/**
@@ -68,17 +68,17 @@ class VndErrorsUnitTest {
@Test
public void appendingVndErrorsShouldWork() {
VndErrors errors = new VndErrors().withError(new VndError("message", "/path", 50, new Link("/link").withSelfRel()));
VndErrors errors = new VndErrors().withError(new VndError("message", "/path", 50, Link.of("/link").withSelfRel()));
assertThat(errors.getContent()).hasSize(1);
errors.getContent().add(new VndError("message2", "/path2", 51, new Link("/link2", "link2")));
errors.getContent().add(new VndError("message2", "/path2", 51, Link.of("/link2", "link2")));
assertThat(errors.getContent()).hasSize(2);
}
@Test
void vndErrorRendersToStringCorrectly() {
VndError error = new VndError("message", "path", 42, new Link("foo", "bar"));
VndError error = new VndError("message", "path", 42, Link.of("foo", "bar"));
assertThat(error.toString()).isEqualTo("VndError[logref: 42, message: message, links: [<foo>;rel=\"bar\"]]");
}
@@ -86,7 +86,7 @@ class VndErrorsUnitTest {
@Test
void vndErrorsRendersToStringCorrectly() {
VndErrors errors = new VndErrors(new VndError("message", "path", 42, new Link("foo", "bar")));
VndErrors errors = new VndErrors(new VndError("message", "path", 42, Link.of("foo", "bar")));
assertThat(errors.toString())
.isEqualTo("VndErrors[VndError[logref: 42, message: message, links: [<foo>;rel=\"bar\"]]]");
}

View File

@@ -49,6 +49,6 @@ class ControllerLinkBuilderOutsideSpringMvcUnitTest {
methodOn(ControllerLinkBuilderUnitTest.PersonsAddressesController.class, 15).getAddressesForCountry("DE"))
.withSelfRel();
assertThat(link).isEqualTo(new Link("/people/15/addresses/DE").withSelfRel());
assertThat(link).isEqualTo(Link.of("/people/15/addresses/DE").withSelfRel());
}
}

View File

@@ -35,9 +35,9 @@ import org.springframework.http.ResponseEntity;
class HeaderLinksResponseEntityUnitTest {
static final Object CONTENT = new Object();
static final Link LINK = new Link("href", "rel");
static final Link LINK = Link.of("href", "rel");
EntityModel<Object> resource = new EntityModel<>(CONTENT, LINK);
EntityModel<Object> resource = EntityModel.of(CONTENT, LINK);
ResponseEntity<EntityModel<Object>> entity = new ResponseEntity<>(resource, HttpStatus.OK);
@Test

View File

@@ -451,7 +451,7 @@ class MultiMediaTypeWebMvcIntegrationTest {
.andAffordance(afford(methodOn(EmployeeController.class).search(null, null)));
// Return the collection of employee resources along with the composite affordance
return new CollectionModel<>(employees, selfLink);
return CollectionModel.of(employees, selfLink);
}
@GetMapping("/employees/search")
@@ -482,7 +482,7 @@ class MultiMediaTypeWebMvcIntegrationTest {
.andAffordance(afford(methodOn(EmployeeController.class).search(null, null)));
// Return the collection of employee resources along with the composite affordance
return new CollectionModel<>(employees, selfLink);
return CollectionModel.of(employees, selfLink);
}
@GetMapping("/employees/{id}")
@@ -495,7 +495,7 @@ class MultiMediaTypeWebMvcIntegrationTest {
Link employeesLink = linkTo(methodOn(EmployeeController.class).all()).withRel("employees");
// Return the affordance + a link back to the entire collection resource.
return new EntityModel<>(EMPLOYEES.get(id),
return EntityModel.of(EMPLOYEES.get(id),
findOneLink.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, id))) //
.andAffordance(afford(methodOn(EmployeeController.class).partiallyUpdateEmployee(null, id))),
employeesLink);

View File

@@ -161,7 +161,7 @@ public class RepresentationModelProcessorIntegrationTest {
public EntityModel<Employee> process(EntityModel<Employee> model) {
triggered = true;
model.add(new Link("/entity/link", ENTITY_LINK_RELATION));
model.add(Link.of("/entity/link", ENTITY_LINK_RELATION));
return model;
}
}
@@ -175,7 +175,7 @@ public class RepresentationModelProcessorIntegrationTest {
public CollectionModel<EntityModel<Employee>> process(CollectionModel<EntityModel<Employee>> model) {
triggered = true;
model.add(new Link("/collection/link", COLLECTION_LINK_RELATION));
model.add(Link.of("/collection/link", COLLECTION_LINK_RELATION));
return model;
}
}
@@ -188,7 +188,7 @@ public class RepresentationModelProcessorIntegrationTest {
public CollectionModel<?> process(CollectionModel<?> model) {
triggered = true;
model.add(new Link("/non-specific-collection/link", WILDCARD_LINK_RELATION));
model.add(Link.of("/non-specific-collection/link", WILDCARD_LINK_RELATION));
return model;
}
}

View File

@@ -61,21 +61,21 @@ import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
@ExtendWith(MockitoExtension.class)
class ResourceProcessorHandlerMethodReturnValueHandlerUnitTest {
static final EntityModel<String> FOO = new EntityModel<>("foo");
static final CollectionModel<EntityModel<String>> FOOS = new CollectionModel<>(Collections.singletonList(FOO));
static final PagedModel<EntityModel<String>> FOO_PAGE = new PagedModel<>(singleton(FOO), new PageMetadata(1, 0, 10));
static final EntityModel<String> FOO = EntityModel.of("foo");
static final CollectionModel<EntityModel<String>> FOOS = CollectionModel.of(Collections.singletonList(FOO));
static final PagedModel<EntityModel<String>> FOO_PAGE = PagedModel.of(singleton(FOO), new PageMetadata(1, 0, 10));
static final StringResource FOO_RES = new StringResource("foo");
static final HttpEntity<EntityModel<String>> FOO_ENTITY = new HttpEntity<>(FOO);
static final ResponseEntity<EntityModel<String>> FOO_RESP_ENTITY = new ResponseEntity<>(FOO, HttpStatus.OK);
static final HttpEntity<StringResource> FOO_RES_ENTITY = new HttpEntity<>(FOO_RES);
static final EntityModel<String> BAR = new EntityModel<>("bar");
static final CollectionModel<EntityModel<String>> BARS = new CollectionModel<>(Collections.singletonList(BAR));
static final EntityModel<String> BAR = EntityModel.of("bar");
static final CollectionModel<EntityModel<String>> BARS = CollectionModel.of(Collections.singletonList(BAR));
static final StringResource BAR_RES = new StringResource("bar");
static final HttpEntity<EntityModel<String>> BAR_ENTITY = new HttpEntity<>(BAR);
static final ResponseEntity<EntityModel<String>> BAR_RESP_ENTITY = new ResponseEntity<>(BAR, HttpStatus.OK);
static final HttpEntity<StringResource> BAR_RES_ENTITY = new HttpEntity<>(BAR_RES);
static final EntityModel<Long> LONG_10 = new EntityModel<>(10L);
static final EntityModel<Long> LONG_20 = new EntityModel<>(20L);
static final EntityModel<Long> LONG_10 = EntityModel.of(10L);
static final EntityModel<Long> LONG_20 = EntityModel.of(20L);
static final LongResource LONG_10_RES = new LongResource(10L);
static final LongResource LONG_20_RES = new LongResource(20L);
static final HttpEntity<EntityModel<Long>> LONG_10_ENTITY = new HttpEntity<>(LONG_10);
@@ -250,7 +250,7 @@ class ResourceProcessorHandlerMethodReturnValueHandlerUnitTest {
private void usesHeaderLinksResponseEntityIfConfigured(Function<Object, Object> mapper) throws Exception {
EntityModel<String> resource = new EntityModel<>("foo", new Link("href", "rel"));
EntityModel<String> resource = EntityModel.of("foo", Link.of("href", "rel"));
MethodParameter parameter = METHOD_PARAMS.get("resource");
RepresentationModelProcessorHandlerMethodReturnValueHandler handler = new RepresentationModelProcessorHandlerMethodReturnValueHandler(
@@ -280,7 +280,7 @@ class ResourceProcessorHandlerMethodReturnValueHandlerUnitTest {
void doesNotInvokeAProcessorForASpecializedType() throws Exception {
EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
CollectionModel<Object> value = new CollectionModel<>(singleton(wrappers.emptyCollectionOf(Object.class)));
CollectionModel<Object> value = CollectionModel.of(singleton(wrappers.emptyCollectionOf(Object.class)));
CollectionModelProcessorWrapper wrapper = new CollectionModelProcessorWrapper(new SpecialResourcesProcessor());
ResolvableType type = ResolvableType.forMethodReturnType(Controller.class.getMethod("resourcesOfObject"));

View File

@@ -49,6 +49,6 @@ class WebMvcLinkBuilderOutsideSpringMvcUnitTest {
methodOn(WebMvcLinkBuilderUnitTest.PersonsAddressesController.class, 15).getAddressesForCountry("DE"))
.withSelfRel();
assertThat(link).isEqualTo(new Link("/people/15/addresses/DE").withSelfRel());
assertThat(link).isEqualTo(Link.of("/people/15/addresses/DE").withSelfRel());
}
}

View File

@@ -78,7 +78,7 @@ class HypermediaWebFilterTest {
.expectNextMatches(resourceSupport -> {
assertThat(resourceSupport.getLinks())//
.containsExactly(new Link("https://example.com/api", IanaLinkRelations.SELF));
.containsExactly(Link.of("https://example.com/api", IanaLinkRelations.SELF));
return true;
}).verifyComplete();

View File

@@ -69,7 +69,7 @@ class ReactiveResourceAssemblerUnitTest {
assertThat(employeeResource.getEmployee()).isEqualTo(new Employee("Frodo Baggins"));
AssertionsForInterfaceTypes.assertThat(employeeResource.getLinks())
.containsExactlyInAnyOrder(new Link("/employees", "employees"));
.containsExactlyInAnyOrder(Link.of("/employees", "employees"));
return true;
}).verifyComplete();
@@ -90,7 +90,7 @@ class ReactiveResourceAssemblerUnitTest {
.extracting("employee") //
.containsExactly(new Employee("Frodo Baggins"));
assertThat(content.iterator().next().getLinks()).containsExactly(new Link("/employees", "employees"));
assertThat(content.iterator().next().getLinks()).containsExactly(Link.of("/employees", "employees"));
assertThat(employeeResources.getLinks()).isEmpty();
return true;
@@ -108,12 +108,12 @@ class ReactiveResourceAssemblerUnitTest {
.expectNextMatches(employeeResources -> {
assertThat(employeeResources.getLinks()) //
.containsExactlyInAnyOrder(new Link("/employees").withSelfRel(), new Link("/", "root"));
.containsExactlyInAnyOrder(Link.of("/employees").withSelfRel(), Link.of("/", "root"));
EmployeeResource content = employeeResources.getContent().iterator().next();
assertThat(content.getEmployee()).isEqualTo(new Employee("Frodo Baggins"));
assertThat(content.getLinks()).containsExactly(new Link("/employees", "employees"));
assertThat(content.getLinks()).containsExactly(Link.of("/employees", "employees"));
return true;
}).verifyComplete();
@@ -125,7 +125,7 @@ class ReactiveResourceAssemblerUnitTest {
public Mono<EmployeeResource> toModel(Employee entity, ServerWebExchange exchange) {
EmployeeResource employeeResource = new EmployeeResource(entity);
employeeResource.add(new Link("/employees", "employees"));
employeeResource.add(Link.of("/employees", "employees"));
return Mono.just(employeeResource);
}
@@ -139,11 +139,11 @@ class ReactiveResourceAssemblerUnitTest {
return entities.flatMap(entity -> toModel(entity, exchange)).collectList().map(listOfResources -> {
CollectionModel<EmployeeResource> employeeResources = new CollectionModel<>(
CollectionModel<EmployeeResource> employeeResources = CollectionModel.of(
listOfResources);
employeeResources.add(new Link("/employees").withSelfRel());
employeeResources.add(new Link("/", "root"));
employeeResources.add(Link.of("/employees").withSelfRel());
employeeResources.add(Link.of("/", "root"));
return employeeResources;
});

View File

@@ -72,7 +72,7 @@ class SimpleReactiveResourceAssemblerTest {
this.testResourceAssembler.toCollectionModel(Flux.just(new Employee("Frodo")), this.exchange)
.as(StepVerifier::create).expectNextMatches(resources -> {
assertThat(resources.getContent()).containsExactly(new EntityModel<>(new Employee("Frodo")));
assertThat(resources.getContent()).containsExactly(EntityModel.of(new Employee("Frodo")));
assertThat(resources.getLinks()).isEmpty();
return true;
@@ -89,7 +89,7 @@ class SimpleReactiveResourceAssemblerTest {
.expectNextMatches(resource -> {
assertThat(resource.getContent().getName()).isEqualTo("Frodo");
assertThat(resource.getLinks()).containsExactly(new Link("/employees").withRel("employees"));
assertThat(resource.getLinks()).containsExactly(Link.of("/employees").withRel("employees"));
return true;
}).verifyComplete();
@@ -105,8 +105,8 @@ class SimpleReactiveResourceAssemblerTest {
.as(StepVerifier::create).expectNextMatches(resources -> {
assertThat(resources.getContent()).containsExactly(
new EntityModel<>(new Employee("Frodo"), new Link("/employees").withRel("employees")));
assertThat(resources.getLinks()).containsExactly(new Link("/", "root"));
EntityModel.of(new Employee("Frodo"), Link.of("/employees").withRel("employees")));
assertThat(resources.getLinks()).containsExactly(Link.of("/", "root"));
return true;
}).verifyComplete();
@@ -119,13 +119,13 @@ class SimpleReactiveResourceAssemblerTest {
@Override
public EntityModel<Employee> addLinks(EntityModel<Employee> resource,
ServerWebExchange exchange) {
return resource.add(new Link("/employees").withRel("employees"));
return resource.add(Link.of("/employees").withRel("employees"));
}
@Override
public CollectionModel<EntityModel<Employee>> addLinks(
CollectionModel<EntityModel<Employee>> resources, ServerWebExchange exchange) {
return resources.add(new Link("/").withRel("root"));
return resources.add(Link.of("/").withRel("root"));
}
}

View File

@@ -19,6 +19,7 @@ import java.io.IOException;
import java.util.Scanner;
import org.springframework.core.io.Resource;
import org.springframework.hateoas.MappingTestUtils;
/**
* @author Greg Turnquist
@@ -31,7 +32,9 @@ public final class MappingUtils {
* @param resource as a {@link Resource}
* @return
* @throws IOException
* @deprecated 1.1, use {@link MappingTestUtils} instead.
*/
@Deprecated
public static String read(Resource resource) throws IOException {
try (Scanner scanner = new Scanner(resource.getInputStream())) {

View File

@@ -54,6 +54,7 @@ import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
/**
* Sample controller using {@link WebFluxLinkBuilder} to create {@link Affordance}s.
@@ -86,7 +87,7 @@ public class WebFluxEmployeeController {
.andAffordance(controller.newEmployee(null)) //
.andAffordance(controller.search(null, null)) //
.toMono() //
.map(selfLink -> new CollectionModel<>(resources, selfLink)));
.map(selfLink -> CollectionModel.of(resources, selfLink)));
}
@GetMapping("/employees/search")
@@ -113,7 +114,7 @@ public class WebFluxEmployeeController {
.andAffordance(controller.newEmployee(null)) //
.andAffordance(controller.search(null, null)) //
.toMono() //
.map(selfLink -> new CollectionModel<>(resources, selfLink)));
.map(selfLink -> CollectionModel.of(resources, selfLink)));
}
@GetMapping("/employees/{id}")
@@ -121,6 +122,12 @@ public class WebFluxEmployeeController {
WebFluxEmployeeController controller = methodOn(WebFluxEmployeeController.class);
Employee employee = EMPLOYEES.get(id);
if (employee == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
Mono<Link> selfLink = linkTo(controller.findOne(id)).withSelfRel() //
.andAffordance(controller.updateEmployee(null, id)) //
.andAffordance(controller.partiallyUpdateEmployee(null, id)) //
@@ -131,7 +138,7 @@ public class WebFluxEmployeeController {
return selfLink.zipWith(employeesLink) //
.map(function((left, right) -> Links.of(left, right))) //
.map(links -> new EntityModel<>(EMPLOYEES.get(id), links));
.map(links -> EntityModel.of(employee, links));
}
@PostMapping("/employees")

View File

@@ -80,7 +80,7 @@ public class WebMvcEmployeeController {
// Return the collection of employee resources along with the composite affordance
return IntStream.range(0, EMPLOYEES.size()) //
.mapToObj(this::findOne) //
.collect(Collectors.collectingAndThen(Collectors.toList(), it -> new CollectionModel<>(it, selfLink)));
.collect(Collectors.collectingAndThen(Collectors.toList(), it -> CollectionModel.of(it, selfLink)));
}
@GetMapping("/employees/search")
@@ -117,7 +117,7 @@ public class WebMvcEmployeeController {
.andAffordance(afford(controller.search(null, null)));
// Return the collection of employee resources along with the composite affordance
return new CollectionModel<>(employees, selfLink);
return CollectionModel.of(employees, selfLink);
}
@GetMapping("/employees/{id}")
@@ -132,7 +132,7 @@ public class WebMvcEmployeeController {
Link employeesLink = linkTo(controller.all()).withRel("employees");
// Return the affordance + a link back to the entire collection resource.
return new EntityModel<>(EMPLOYEES.get(id), //
return EntityModel.of(EMPLOYEES.get(id), //
findOneLink //
.andAffordance(afford(controller.updateEmployee(null, id))) // //
.andAffordance(afford(controller.partiallyUpdateEmployee(null, id))), //