diff --git a/src/docs/java/org/springframework/hateoas/EmployeeController.java b/src/docs/java/org/springframework/hateoas/EmployeeController.java index 14dad0bb..2b2430da 100644 --- a/src/docs/java/org/springframework/hateoas/EmployeeController.java +++ b/src/docs/java/org/springframework/hateoas/EmployeeController.java @@ -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> diff --git a/src/docs/java/org/springframework/hateoas/FundamentalsTest.java b/src/docs/java/org/springframework/hateoas/FundamentalsTest.java index 018ec078..ff473dab 100644 --- a/src/docs/java/org/springframework/hateoas/FundamentalsTest.java +++ b/src/docs/java/org/springframework/hateoas/FundamentalsTest.java @@ -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> diff --git a/src/docs/java/org/springframework/hateoas/PaymentProcessor.java b/src/docs/java/org/springframework/hateoas/PaymentProcessor.java index 7216c239..598de2ac 100644 --- a/src/docs/java/org/springframework/hateoas/PaymentProcessor.java +++ b/src/docs/java/org/springframework/hateoas/PaymentProcessor.java @@ -28,7 +28,7 @@ public class PaymentProcessor implements RepresentationModelProcessor process(EntityModel 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> diff --git a/src/main/asciidoc/fundamentals.adoc b/src/main/asciidoc/fundamentals.adoc index d53955e0..07ae89df 100644 --- a/src/main/asciidoc/fundamentals.adoc +++ b/src/main/asciidoc/fundamentals.adoc @@ -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 model = new EntityModel<>(person); +EntityModel model = EntityModel.of(person); ---- ==== @@ -192,6 +192,6 @@ Its elements can either be simple objects or `RepresentationModel` instances in [source, java] ---- Collection people = Collections.singleton(new Person("Dave", "Matthews")); -CollectionModel model = new CollectionModel<>(people); +CollectionModel model = CollectionModel.of(people); ---- ==== diff --git a/src/main/java/org/springframework/hateoas/CollectionModel.java b/src/main/java/org/springframework/hateoas/CollectionModel.java index bef7c41b..b0b8512a 100644 --- a/src/main/java/org/springframework/hateoas/CollectionModel.java +++ b/src/main/java/org/springframework/hateoas/CollectionModel.java @@ -48,7 +48,9 @@ public class CollectionModel extends RepresentationModel> * * @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 content, Link... links) { this(content, Arrays.asList(links)); } @@ -58,7 +60,9 @@ public class CollectionModel extends RepresentationModel> * * @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 content, Iterable links) { Assert.notNull(content, "Content must not be null!"); @@ -68,9 +72,56 @@ public class CollectionModel extends RepresentationModel> for (T element : content) { this.content.add(element); } + this.add(links); } + /** + * Creates a new empty collection model. + * + * @param + * @return + */ + public static CollectionModel 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 CollectionModel of(Iterable 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 CollectionModel of(Iterable 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 CollectionModel of(Iterable content, Iterable 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 extends RepresentationModel> ArrayList 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); } /** diff --git a/src/main/java/org/springframework/hateoas/EntityModel.java b/src/main/java/org/springframework/hateoas/EntityModel.java index 6fb47021..d7fee163 100644 --- a/src/main/java/org/springframework/hateoas/EntityModel.java +++ b/src/main/java/org/springframework/hateoas/EntityModel.java @@ -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 extends RepresentationModel> { * * @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 extends RepresentationModel> { * * @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 links) { + @Deprecated + public EntityModel(T content, Iterable 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 EntityModel 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 EntityModel 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 EntityModel of(T content, Iterable links) { + return new EntityModel<>(content, links); + } + /** * Returns the underlying entity. * @@ -81,7 +123,9 @@ public class EntityModel extends RepresentationModel> { // Hacks to allow deserialization into an EntityModel> + @Nullable @JsonAnyGetter + @SuppressWarnings("unchecked") private Map getMapContent() { return Map.class.isInstance(content) ? (Map) content : null; } diff --git a/src/main/java/org/springframework/hateoas/Link.java b/src/main/java/org/springframework/hateoas/Link.java index a17ab07c..12ff82d1 100755 --- a/src/main/java/org/springframework/hateoas/Link.java +++ b/src/main/java/org/springframework/hateoas/Link.java @@ -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 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")); diff --git a/src/main/java/org/springframework/hateoas/PagedModel.java b/src/main/java/org/springframework/hateoas/PagedModel.java index 8ef9a5ac..b6d61922 100644 --- a/src/main/java/org/springframework/hateoas/PagedModel.java +++ b/src/main/java/org/springframework/hateoas/PagedModel.java @@ -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 extends CollectionModel { * @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 content, @Nullable PageMetadata metadata, Link... links) { this(content, metadata, Arrays.asList(links)); } @@ -62,7 +65,9 @@ public class PagedModel extends CollectionModel { * @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 content, @Nullable PageMetadata metadata, Iterable links) { super(content, links); @@ -70,6 +75,62 @@ public class PagedModel extends CollectionModel { this.metadata = metadata; } + /** + * Creates an empty {@link PagedModel}. + * + * @param + * @return + * @since 1.1 + */ + public static PagedModel empty() { + return empty(null); + } + + /** + * Creates an empty {@link PagedModel} with the given {@link PageMetadata}. + * + * @param + * @param metadata can be {@literal null}. + * @return + * @since 1.1 + */ + public static PagedModel 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 PagedModel of(Collection 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 PagedModel of(Collection 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 PagedModel of(Collection content, @Nullable PageMetadata metadata, Iterable links) { + return new PagedModel<>(content, metadata, links); + } + /** * Returns the pagination metadata. * @@ -95,10 +156,10 @@ public class PagedModel extends CollectionModel { ArrayList 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); } /** diff --git a/src/main/java/org/springframework/hateoas/RepresentationModel.java b/src/main/java/org/springframework/hateoas/RepresentationModel.java index 0d8856f8..b4a75f5e 100755 --- a/src/main/java/org/springframework/hateoas/RepresentationModel.java +++ b/src/main/java/org/springframework/hateoas/RepresentationModel.java @@ -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> { this.links.add(initialLink); } - public RepresentationModel(List initialLinks) { + public RepresentationModel(Iterable 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 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 RepresentationModel of(@Nullable T object, Iterable links) { + + if (object == null) { + return new RepresentationModel<>(links); + } + + if (Collection.class.isInstance(object)) { + return CollectionModel.of((Collection) object, links); + } + + return EntityModel.of(object, links); } /** diff --git a/src/main/java/org/springframework/hateoas/client/JsonPathLinkDiscoverer.java b/src/main/java/org/springframework/hateoas/client/JsonPathLinkDiscoverer.java index 38080afc..79148727 100644 --- a/src/main/java/org/springframework/hateoas/client/JsonPathLinkDiscoverer.java +++ b/src/main/java/org/springframework/hateoas/client/JsonPathLinkDiscoverer.java @@ -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 Optional firstOrEmpty(Iterable source) { diff --git a/src/main/java/org/springframework/hateoas/client/Rels.java b/src/main/java/org/springframework/hateoas/client/Rels.java index c1af5769..018c8e6e 100644 --- a/src/main/java/org/springframework/hateoas/client/Rels.java +++ b/src/main/java/org/springframework/hateoas/client/Rels.java @@ -143,7 +143,7 @@ class Rels { */ @Override public Optional 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)); } } } diff --git a/src/main/java/org/springframework/hateoas/client/Traverson.java b/src/main/java/org/springframework/hateoas/client/Traverson.java index b4cc029c..0445cae6 100644 --- a/src/main/java/org/springframework/hateoas/client/Traverson.java +++ b/src/main/java/org/springframework/hateoas/client/Traverson.java @@ -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()); } diff --git a/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJson.java b/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJson.java index 20a9e6fd..96b22d56 100644 --- a/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJson.java +++ b/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJson.java @@ -100,7 +100,7 @@ class CollectionJson { 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() { diff --git a/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonItem.java b/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonItem.java index 62596073..0b570495 100644 --- a/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonItem.java +++ b/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonItem.java @@ -53,7 +53,7 @@ class CollectionJsonItem { private @Nullable String href; private List 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 { 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 { 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)); } } diff --git a/src/main/java/org/springframework/hateoas/mediatype/collectionjson/Jackson2CollectionJsonModule.java b/src/main/java/org/springframework/hateoas/mediatype/collectionjson/Jackson2CollectionJsonModule.java index 57a28515..c50b57c7 100644 --- a/src/main/java/org/springframework/hateoas/mediatype/collectionjson/Jackson2CollectionJsonModule.java +++ b/src/main/java/org/springframework/hateoas/mediatype/collectionjson/Jackson2CollectionJsonModule.java @@ -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, Links, PagedModel> FINISHER = (content, - links) -> new PagedModel<>(content, null, links); + links) -> PagedModel.of(content, null, links); private static final Function>> CONTEXTUAL_CREATOR = CollectionJsonPagedResourcesDeserializer::new; CollectionJsonPagedResourcesDeserializer() { diff --git a/src/main/java/org/springframework/hateoas/mediatype/hal/DefaultCurieProvider.java b/src/main/java/org/springframework/hateoas/mediatype/hal/DefaultCurieProvider.java index f3164c81..74aaed43 100644 --- a/src/main/java/org/springframework/hateoas/mediatype/hal/DefaultCurieProvider.java +++ b/src/main/java/org/springframework/hateoas/mediatype/hal/DefaultCurieProvider.java @@ -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"); diff --git a/src/main/java/org/springframework/hateoas/mediatype/hal/HalLinkDiscoverer.java b/src/main/java/org/springframework/hateoas/mediatype/hal/HalLinkDiscoverer.java index c62735ab..6f0b169c 100644 --- a/src/main/java/org/springframework/hateoas/mediatype/hal/HalLinkDiscoverer.java +++ b/src/main/java/org/springframework/hateoas/mediatype/hal/HalLinkDiscoverer.java @@ -57,7 +57,7 @@ public class HalLinkDiscoverer extends JsonPathLinkDiscoverer { Map json = (Map) 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")) // diff --git a/src/main/java/org/springframework/hateoas/mediatype/hal/Jackson2HalModule.java b/src/main/java/org/springframework/hateoas/mediatype/hal/Jackson2HalModule.java index aff4223e..43e6c8a6 100644 --- a/src/main/java/org/springframework/hateoas/mediatype/hal/Jackson2HalModule.java +++ b/src/main/java/org/springframework/hateoas/mediatype/hal/Jackson2HalModule.java @@ -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())); } } diff --git a/src/main/java/org/springframework/hateoas/mediatype/uber/Jackson2UberModule.java b/src/main/java/org/springframework/hateoas/mediatype/uber/Jackson2UberModule.java index 7562e9db..1ec14902 100644 --- a/src/main/java/org/springframework/hateoas/mediatype/uber/Jackson2UberModule.java +++ b/src/main/java/org/springframework/hateoas/mediatype/uber/Jackson2UberModule.java @@ -576,7 +576,7 @@ public class Jackson2UberModule extends SimpleModule { /** * Custom {@link StdDeserializer} to deserialize {@link EntityModel}. */ - static class UberEntityModelDeserializer extends ContainerDeserializerBase> + static class UberEntityModelDeserializer extends ContainerDeserializerBase> 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 convertToResource(UberData uberData, Links links) { + private RepresentationModel convertToResource(UberData uberData, Links links) { // Primitive type List 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 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 resourceLinks = new ArrayList<>(); - EntityModel resource = null; + RepresentationModel resource = null; List 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>... */ - return new CollectionModel<>(content, doc.getUber().getLinks()); + return CollectionModel.of(content, doc.getUber().getLinks()); } else { /* * ...or return a Resources @@ -898,7 +898,7 @@ public class Jackson2UberModule extends SimpleModule { List 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()); } } diff --git a/src/main/java/org/springframework/hateoas/mediatype/uber/UberData.java b/src/main/java/org/springframework/hateoas/mediatype/uber/UberData.java index de4155dc..9e81a9a8 100644 --- a/src/main/java/org/springframework/hateoas/mediatype/uber/UberData.java +++ b/src/main/java/org/springframework/hateoas/mediatype/uber/UberData.java @@ -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 rels = new ArrayList<>(link.getRel()); + List rels = new ArrayList<>(data.getRel()); rels.addAll(affordance.getRel()); return affordance.withName(rels.get(0).value()) // diff --git a/src/main/java/org/springframework/hateoas/mediatype/vnderrors/VndErrors.java b/src/main/java/org/springframework/hateoas/mediatype/vnderrors/VndErrors.java index 4fdc7269..4361d460 100644 --- a/src/main/java/org/springframework/hateoas/mediatype/vnderrors/VndErrors.java +++ b/src/main/java/org/springframework/hateoas/mediatype/vnderrors/VndErrors.java @@ -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 { @@ -177,8 +179,16 @@ public class VndErrors extends CollectionModel { /** * 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 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 { * * @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 { diff --git a/src/main/java/org/springframework/hateoas/server/SimpleRepresentationModelAssembler.java b/src/main/java/org/springframework/hateoas/server/SimpleRepresentationModelAssembler.java index 4aa34ce3..0b06e991 100644 --- a/src/main/java/org/springframework/hateoas/server/SimpleRepresentationModelAssembler.java +++ b/src/main/java/org/springframework/hateoas/server/SimpleRepresentationModelAssembler.java @@ -29,8 +29,7 @@ import org.springframework.util.Assert; * @author Greg Turnquist * @since 1.0 */ -public interface SimpleRepresentationModelAssembler - extends RepresentationModelAssembler> { +public interface SimpleRepresentationModelAssembler extends RepresentationModelAssembler> { /** * Converts the given entity into a {@link EntityModel}. @@ -40,7 +39,7 @@ public interface SimpleRepresentationModelAssembler */ default EntityModel toModel(T entity) { - EntityModel resource = new EntityModel<>(entity); + EntityModel resource = EntityModel.of(entity); addLinks(resource); return resource; } @@ -60,8 +59,7 @@ public interface SimpleRepresentationModelAssembler * @return {@link CollectionModel} containing {@link EntityModel} of {@code T}. */ @Override - default CollectionModel> toCollectionModel( - Iterable entities) { + default CollectionModel> toCollectionModel(Iterable entities) { Assert.notNull(entities, "entities must not be null!"); List> resourceList = new ArrayList<>(); @@ -70,8 +68,7 @@ public interface SimpleRepresentationModelAssembler resourceList.add(toModel(entity)); } - CollectionModel> resources = new CollectionModel<>( - resourceList); + CollectionModel> resources = CollectionModel.of(resourceList); addLinks(resources); return resources; } diff --git a/src/main/java/org/springframework/hateoas/server/core/LinkBuilderSupport.java b/src/main/java/org/springframework/hateoas/server/core/LinkBuilderSupport.java index 4032c75e..34c14e3c 100644 --- a/src/main/java/org/springframework/hateoas/server/core/LinkBuilderSupport.java +++ b/src/main/java/org/springframework/hateoas/server/core/LinkBuilderSupport.java @@ -139,7 +139,7 @@ public abstract class LinkBuilderSupport implements LinkB */ public Link withRel(LinkRelation rel) { - return new Link(toString(), rel) // + return Link.of(toString(), rel) // .withAffordances(affordances); } diff --git a/src/main/java/org/springframework/hateoas/server/core/SpringAffordanceBuilder.java b/src/main/java/org/springframework/hateoas/server/core/SpringAffordanceBuilder.java index 0213e854..aca96700 100644 --- a/src/main/java/org/springframework/hateoas/server/core/SpringAffordanceBuilder.java +++ b/src/main/java/org/springframework/hateoas/server/core/SpringAffordanceBuilder.java @@ -50,7 +50,7 @@ public class SpringAffordanceBuilder { public static List 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); diff --git a/src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelAssemblerSupport.java b/src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelAssemblerSupport.java index 040d85b4..d7d5acae 100755 --- a/src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelAssemblerSupport.java +++ b/src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelAssemblerSupport.java @@ -161,7 +161,7 @@ public abstract class RepresentationModelAssemblerSupport toResources() { - return new CollectionModel<>(toListOfResources()); + return CollectionModel.of(toListOfResources()); } } } diff --git a/src/main/java/org/springframework/hateoas/server/mvc/package-info.java b/src/main/java/org/springframework/hateoas/server/mvc/package-info.java index d8f8bfa5..9cd4fc7f 100644 --- a/src/main/java/org/springframework/hateoas/server/mvc/package-info.java +++ b/src/main/java/org/springframework/hateoas/server/mvc/package-info.java @@ -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 diff --git a/src/main/java/org/springframework/hateoas/server/reactive/SimpleReactiveRepresentationModelAssembler.java b/src/main/java/org/springframework/hateoas/server/reactive/SimpleReactiveRepresentationModelAssembler.java index 1aace447..2b897240 100644 --- a/src/main/java/org/springframework/hateoas/server/reactive/SimpleReactiveRepresentationModelAssembler.java +++ b/src/main/java/org/springframework/hateoas/server/reactive/SimpleReactiveRepresentationModelAssembler.java @@ -42,7 +42,7 @@ public interface SimpleReactiveRepresentationModelAssembler @Override default Mono> toModel(T entity, ServerWebExchange exchange) { - EntityModel resource = new EntityModel<>(entity); + EntityModel resource = EntityModel.of(entity); return Mono.just(addLinks(resource, exchange)); } diff --git a/src/test/java/org/springframework/hateoas/CollectionModelUnitTest.java b/src/test/java/org/springframework/hateoas/CollectionModelUnitTest.java index 467b75dc..5a4c5b3e 100755 --- a/src/test/java/org/springframework/hateoas/CollectionModelUnitTest.java +++ b/src/test/java/org/springframework/hateoas/CollectionModelUnitTest.java @@ -29,21 +29,21 @@ import org.junit.jupiter.api.Test; */ class CollectionModelUnitTest { - Set> foo = Collections.singleton(new EntityModel<>("foo")); - Set> bar = Collections.singleton(new EntityModel<>("bar")); + Set> foo = Collections.singleton(EntityModel.of("foo")); + Set> bar = Collections.singleton(EntityModel.of("bar")); @Test void equalsForSelfReference() { - CollectionModel> resource = new CollectionModel<>(foo); + CollectionModel> resource = CollectionModel.of(foo); assertThat(resource).isEqualTo(resource); } @Test void equalsWithEqualContent() { - CollectionModel> left = new CollectionModel<>(foo); - CollectionModel> right = new CollectionModel<>(foo); + CollectionModel> left = CollectionModel.of(foo); + CollectionModel> right = CollectionModel.of(foo); assertThat(left).isEqualTo(right); assertThat(right).isEqualTo(left); @@ -52,8 +52,8 @@ class CollectionModelUnitTest { @Test void notEqualForDifferentContent() { - CollectionModel> left = new CollectionModel<>(foo); - CollectionModel> right = new CollectionModel<>(bar); + CollectionModel> left = CollectionModel.of(foo); + CollectionModel> right = CollectionModel.of(bar); assertThat(left).isNotEqualTo(right); assertThat(right).isNotEqualTo(left); @@ -62,9 +62,9 @@ class CollectionModelUnitTest { @Test void notEqualForDifferentLinks() { - CollectionModel> left = new CollectionModel<>(foo); - CollectionModel> right = new CollectionModel<>(bar); - right.add(new Link("localhost")); + CollectionModel> left = CollectionModel.of(foo); + CollectionModel> right = CollectionModel.of(bar); + right.add(Link.of("localhost")); assertThat(left).isNotEqualTo(right); assertThat(right).isNotEqualTo(left); diff --git a/src/test/java/org/springframework/hateoas/EntityModelIntegrationTest.java b/src/test/java/org/springframework/hateoas/EntityModelIntegrationTest.java index b887285d..05b8356e 100755 --- a/src/test/java/org/springframework/hateoas/EntityModelIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/EntityModelIntegrationTest.java @@ -39,8 +39,8 @@ class EntityModelIntegrationTest extends AbstractJackson2MarshallingIntegrationT person.firstname = "Dave"; person.lastname = "Matthews"; - EntityModel resource = new EntityModel<>(person); - resource.add(new Link("localhost")); + EntityModel 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"); } diff --git a/src/test/java/org/springframework/hateoas/EntityModelUnitTest.java b/src/test/java/org/springframework/hateoas/EntityModelUnitTest.java index 3595d4d0..4133700c 100755 --- a/src/test/java/org/springframework/hateoas/EntityModelUnitTest.java +++ b/src/test/java/org/springframework/hateoas/EntityModelUnitTest.java @@ -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 resource = new EntityModel<>("foo"); + EntityModel resource = EntityModel.of("foo"); assertThat(resource).isEqualTo(resource); } @Test void equalsWithEqualContent() { - EntityModel left = new EntityModel<>("foo"); - EntityModel right = new EntityModel<>("foo"); + EntityModel left = EntityModel.of("foo"); + EntityModel right = EntityModel.of("foo"); assertThat(left).isEqualTo(right); assertThat(right).isEqualTo(left); @@ -48,8 +48,8 @@ class EntityModelUnitTest { @Test void notEqualForDifferentContent() { - EntityModel left = new EntityModel<>("foo"); - EntityModel right = new EntityModel<>("bar"); + EntityModel left = EntityModel.of("foo"); + EntityModel right = EntityModel.of("bar"); assertThat(left).isNotEqualTo(right); assertThat(right).isNotEqualTo(left); @@ -58,9 +58,9 @@ class EntityModelUnitTest { @Test void notEqualForDifferentLinks() { - EntityModel left = new EntityModel<>("foo"); - EntityModel right = new EntityModel<>("foo"); - right.add(new Link("localhost")); + EntityModel left = EntityModel.of("foo"); + EntityModel 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(Collections.emptyList()); + EntityModel.of(Collections.emptyList()); }); } } diff --git a/src/test/java/org/springframework/hateoas/Jackson2LinkIntegrationTest.java b/src/test/java/org/springframework/hateoas/Jackson2LinkIntegrationTest.java index eaedecca..f19b9169 100755 --- a/src/test/java/org/springframework/hateoas/Jackson2LinkIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/Jackson2LinkIntegrationTest.java @@ -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); } /** diff --git a/src/test/java/org/springframework/hateoas/Jackson2PagedResourcesIntegrationTest.java b/src/test/java/org/springframework/hateoas/Jackson2PagedResourcesIntegrationTest.java index 99b15a8f..1008f00f 100755 --- a/src/test/java/org/springframework/hateoas/Jackson2PagedResourcesIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/Jackson2PagedResourcesIntegrationTest.java @@ -65,7 +65,7 @@ class Jackson2PagedResourcesIntegrationTest { user.lastname = "Matthews"; PageMetadata metadata = new PagedModel.PageMetadata(1, 0, 2); - PagedModel resources = new PagedModel<>(Collections.singleton(user), metadata); + PagedModel resources = PagedModel.of(Collections.singleton(user), metadata); Method method = Sample.class.getMethod("someMethod"); StringWriter writer = new StringWriter(); diff --git a/src/test/java/org/springframework/hateoas/Jackson2ResourceIntegrationTest.java b/src/test/java/org/springframework/hateoas/Jackson2ResourceIntegrationTest.java index 2324b991..df360261 100755 --- a/src/test/java/org/springframework/hateoas/Jackson2ResourceIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/Jackson2ResourceIntegrationTest.java @@ -27,8 +27,8 @@ class Jackson2ResourceIntegrationTest extends AbstractJackson2MarshallingIntegra person.firstname = "Dave"; person.lastname = "Matthews"; - EntityModel resource = new EntityModel<>(person); - resource.add(new Link("localhost")); + EntityModel 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"); } diff --git a/src/test/java/org/springframework/hateoas/Jackson2ResourceSupportIntegrationTest.java b/src/test/java/org/springframework/hateoas/Jackson2ResourceSupportIntegrationTest.java index d20ef9c4..e16de8fa 100755 --- a/src/test/java/org/springframework/hateoas/Jackson2ResourceSupportIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/Jackson2ResourceSupportIntegrationTest.java @@ -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")); } } diff --git a/src/test/java/org/springframework/hateoas/LinkIntegrationTest.java b/src/test/java/org/springframework/hateoas/LinkIntegrationTest.java index b7c464f3..09c64fc4 100755 --- a/src/test/java/org/springframework/hateoas/LinkIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/LinkIntegrationTest.java @@ -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); } /** diff --git a/src/test/java/org/springframework/hateoas/LinkUnitTest.java b/src/test/java/org/springframework/hateoas/LinkUnitTest.java index 8f6dd996..0c40784d 100755 --- a/src/test/java/org/springframework/hateoas/LinkUnitTest.java +++ b/src/test/java/org/springframework/hateoas/LinkUnitTest.java @@ -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(";rel=\"foo\"")).isEqualTo(new Link("/something", "foo")); + softly.assertThat(Link.valueOf(";rel=\"foo\"")).isEqualTo(Link.of("/something", "foo")); softly.assertThat(Link.valueOf(";rel=\"foo\";title=\"Some title\"")) - .isEqualTo(new Link("/something", "foo")); + .isEqualTo(Link.of("/something", "foo")); softly.assertThat(Link.valueOf(";" // + "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()); } } diff --git a/src/test/java/org/springframework/hateoas/LinksUnitTest.java b/src/test/java/org/springframework/hateoas/LinksUnitTest.java index 506e9fab..b466391e 100755 --- a/src/test/java/org/springframework/hateoas/LinksUnitTest.java +++ b/src/test/java/org/springframework/hateoas/LinksUnitTest.java @@ -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(); diff --git a/src/test/java/org/springframework/hateoas/MappingTestUtils.java b/src/test/java/org/springframework/hateoas/MappingTestUtils.java index dccafafa..3d3e44c1 100644 --- a/src/test/java/org/springframework/hateoas/MappingTestUtils.java +++ b/src/test/java/org/springframework/hateoas/MappingTestUtils.java @@ -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 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 readObject(String filename, Class type) { + + TypeFactory factory = mapper.getTypeFactory(); + JavaType javaType = factory.constructType(type); + + return readObject(filename, javaType); + } + + public S readObject(String filename, Class type, Class elementType) { + + TypeFactory factory = mapper.getTypeFactory(); + JavaType javaType = factory.constructParametricType(type, elementType); + + return readObject(filename, javaType); + } + + public 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); + } + } + + } } diff --git a/src/test/java/org/springframework/hateoas/PagedModelUnitTest.java b/src/test/java/org/springframework/hateoas/PagedModelUnitTest.java index c2504a66..ea1537a6 100755 --- a/src/test/java/org/springframework/hateoas/PagedModelUnitTest.java +++ b/src/test/java/org/springframework/hateoas/PagedModelUnitTest.java @@ -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(); } diff --git a/src/test/java/org/springframework/hateoas/RepresentationModelIntegrationTest.java b/src/test/java/org/springframework/hateoas/RepresentationModelIntegrationTest.java index fec74f27..ca4bed00 100755 --- a/src/test/java/org/springframework/hateoas/RepresentationModelIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/RepresentationModelIntegrationTest.java @@ -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")); } } diff --git a/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java b/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java index 249764c6..8666d18c 100755 --- a/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java +++ b/src/test/java/org/springframework/hateoas/RepresentationModelUnitTest.java @@ -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(); } } diff --git a/src/test/java/org/springframework/hateoas/SimpleRepresentationModelAssemblerTest.java b/src/test/java/org/springframework/hateoas/SimpleRepresentationModelAssemblerTest.java index 919630ea..167a2d8f 100644 --- a/src/test/java/org/springframework/hateoas/SimpleRepresentationModelAssemblerTest.java +++ b/src/test/java/org/springframework/hateoas/SimpleRepresentationModelAssemblerTest.java @@ -53,7 +53,7 @@ class SimpleRepresentationModelAssemblerTest { CollectionModel> 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 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 resource) { - resource.add(new Link("/employees").withRel("employees")); + resource.add(Link.of("/employees").withRel("employees")); } @Override diff --git a/src/test/java/org/springframework/hateoas/client/LinkDiscovererUnitTest.java b/src/test/java/org/springframework/hateoas/client/LinkDiscovererUnitTest.java index 02a2af31..bae5808f 100755 --- a/src/test/java/org/springframework/hateoas/client/LinkDiscovererUnitTest.java +++ b/src/test/java/org/springframework/hateoas/client/LinkDiscovererUnitTest.java @@ -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 diff --git a/src/test/java/org/springframework/hateoas/client/Server.java b/src/test/java/org/springframework/hateoas/client/Server.java index d6cec16c..36064cd9 100644 --- a/src/test/java/org/springframework/hateoas/client/Server.java +++ b/src/test/java/org/springframework/hateoas/client/Server.java @@ -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 resources = new CollectionModel<>(Collections.emptyList()); + CollectionModel resources = CollectionModel.of(Collections.emptyList()); for (Link link : baseResources.keySet()) { resources.add(link); - CollectionModel nested = new CollectionModel<>(Collections.emptyList()); + CollectionModel nested = CollectionModel.of(Collections.emptyList()); nested.add(baseResources.get(link)); register(link.getHref(), nested); diff --git a/src/test/java/org/springframework/hateoas/client/TraversonTest.java b/src/test/java/org/springframework/hateoas/client/TraversonTest.java index 627c2f6a..18c9769f 100755 --- a/src/test/java/org/springframework/hateoas/client/TraversonTest.java +++ b/src/test/java/org/springframework/hateoas/client/TraversonTest.java @@ -442,12 +442,12 @@ class TraversonTest { private static void setUpActors() { - EntityModel actor = new EntityModel<>(new Actor("Keanu Reaves")); + EntityModel actor = EntityModel.of(new Actor("Keanu Reaves")); String actorUri = server.mockResourceFor(actor); Movie movie = new Movie("The Matrix"); - EntityModel resource = new EntityModel<>(movie); - resource.add(new Link(actorUri, "actor")); + EntityModel resource = EntityModel.of(movie); + resource.add(Link.of(actorUri, "actor")); server.mockResourceFor(resource); server.finishMocking(); diff --git a/src/test/java/org/springframework/hateoas/config/CustomHypermediaWebFluxTest.java b/src/test/java/org/springframework/hateoas/config/CustomHypermediaWebFluxTest.java index 108374ea..3c321759 100644 --- a/src/test/java/org/springframework/hateoas/config/CustomHypermediaWebFluxTest.java +++ b/src/test/java/org/springframework/hateoas/config/CustomHypermediaWebFluxTest.java @@ -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)); // } } } diff --git a/src/test/java/org/springframework/hateoas/config/CustomHypermediaWebMvcTest.java b/src/test/java/org/springframework/hateoas/config/CustomHypermediaWebMvcTest.java index d7e8a381..a1eb17b4 100644 --- a/src/test/java/org/springframework/hateoas/config/CustomHypermediaWebMvcTest.java +++ b/src/test/java/org/springframework/hateoas/config/CustomHypermediaWebMvcTest.java @@ -95,7 +95,7 @@ class CustomHypermediaWebMvcTest { @GetMapping("/employees/1") public EntityModel 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()); } } diff --git a/src/test/java/org/springframework/hateoas/config/EnableHypermediaSupportIntegrationTest.java b/src/test/java/org/springframework/hateoas/config/EnableHypermediaSupportIntegrationTest.java index 3c143471..3e2353eb 100755 --- a/src/test/java/org/springframework/hateoas/config/EnableHypermediaSupportIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/config/EnableHypermediaSupportIntegrationTest.java @@ -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\"}]}}"); // } // diff --git a/src/test/java/org/springframework/hateoas/config/HypermediaWebClientBeanPostProcessorTest.java b/src/test/java/org/springframework/hateoas/config/HypermediaWebClientBeanPostProcessorTest.java index 079883a9..d2efddff 100644 --- a/src/test/java/org/springframework/hateoas/config/HypermediaWebClientBeanPostProcessorTest.java +++ b/src/test/java/org/springframework/hateoas/config/HypermediaWebClientBeanPostProcessorTest.java @@ -53,12 +53,12 @@ class HypermediaWebClientBeanPostProcessorTest { this.server = new Server(); - EntityModel actor = new EntityModel<>(new Actor("Keanu Reaves")); + EntityModel actor = EntityModel.of(new Actor("Keanu Reaves")); String actorUri = this.server.mockResourceFor(actor); Movie movie = new Movie("The Matrix"); - EntityModel resource = new EntityModel<>(movie); - resource.add(new Link(actorUri, "actor")); + EntityModel 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(); }); } diff --git a/src/test/java/org/springframework/hateoas/config/HypermediaWebFluxConfigurerTest.java b/src/test/java/org/springframework/hateoas/config/HypermediaWebFluxConfigurerTest.java index 19cefb2c..8db90301 100644 --- a/src/test/java/org/springframework/hateoas/config/HypermediaWebFluxConfigurerTest.java +++ b/src/test/java/org/springframework/hateoas/config/HypermediaWebFluxConfigurerTest.java @@ -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 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> 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 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> resources) { - resources.add(new Link("/employees").withSelfRel()); + resources.add(Link.of("/employees").withSelfRel()); } } diff --git a/src/test/java/org/springframework/hateoas/config/HypermediaWebMvcConfigurerTest.java b/src/test/java/org/springframework/hateoas/config/HypermediaWebMvcConfigurerTest.java index cbbe0e89..b5c6e36a 100644 --- a/src/test/java/org/springframework/hateoas/config/HypermediaWebMvcConfigurerTest.java +++ b/src/test/java/org/springframework/hateoas/config/HypermediaWebMvcConfigurerTest.java @@ -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> resources = mapper.readValue(json, collectionModelType); - assertThat(resources.getLinks()).containsExactlyInAnyOrder(new Link("/employees", IanaLinkRelations.SELF)); + assertThat(resources.getLinks()).containsExactlyInAnyOrder(Link.of("/employees", IanaLinkRelations.SELF)); Collection> 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 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 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> resources) { - resources.add(new Link("/employees").withSelfRel()); + resources.add(Link.of("/employees").withSelfRel()); } } diff --git a/src/test/java/org/springframework/hateoas/mediatype/AffordancesUnitTests.java b/src/test/java/org/springframework/hateoas/mediatype/AffordancesUnitTests.java index e63a1b3b..68c8786d 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/AffordancesUnitTests.java +++ b/src/test/java/org/springframework/hateoas/mediatype/AffordancesUnitTests.java @@ -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(); diff --git a/src/test/java/org/springframework/hateoas/mediatype/PropertyUtilsTest.java b/src/test/java/org/springframework/hateoas/mediatype/PropertyUtilsTest.java index 4081a4c0..bf673bcb 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/PropertyUtilsTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/PropertyUtilsTest.java @@ -68,7 +68,7 @@ class PropertyUtilsTest { void simpleObjectWrappedAsResource() { Employee employee = new Employee("Frodo Baggins", "ring bearer"); - EntityModel employeeResource = new EntityModel<>(employee); + EntityModel employeeResource = EntityModel.of(employee); Map properties = PropertyUtils.extractPropertyValues(employeeResource); diff --git a/src/test/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonSpecTest.java b/src/test/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonSpecTest.java index 43545936..71f85172 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonSpecTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonSpecTest.java @@ -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> 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/")); } /** diff --git a/src/test/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonWebMvcIntegrationTest.java b/src/test/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonWebMvcIntegrationTest.java index 1510d60f..99efcf70 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonWebMvcIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonWebMvcIntegrationTest.java @@ -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); diff --git a/src/test/java/org/springframework/hateoas/mediatype/collectionjson/Jackson2CollectionJsonIntegrationTest.java b/src/test/java/org/springframework/hateoas/mediatype/collectionjson/Jackson2CollectionJsonIntegrationTest.java index 151c83e4..74ac72c7 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/collectionjson/Jackson2CollectionJsonIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/collectionjson/Jackson2CollectionJsonIntegrationTest.java @@ -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 content = new ArrayList<>(); content.add("first"); content.add("second"); - CollectionModel resources = new CollectionModel<>(content); - resources.add(new Link("localhost")); + CollectionModel 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 expected = new CollectionModel<>(content); - expected.add(new Link("localhost")); + CollectionModel expected = CollectionModel.of(content); + expected.add(Link.of("localhost")); - CollectionModel result = mapper.readValue( - MappingUtils.read(new ClassPathResource("resources.json", getClass())), - mapper.getTypeFactory().constructParametricType(CollectionModel.class, String.class)); + CollectionModel result = mapper.readObject("resources.json", CollectionModel.class, String.class); assertThat(result).isEqualTo(expected); } @Test - void renderResource() throws Exception { + void renderResource() { - EntityModel 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 actual = mapper.readObject("resource.json", EntityModel.class, String.class); - String source = MappingUtils.read(new ClassPathResource("resource.json", getClass())); - EntityModel 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> 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> resources = new CollectionModel<>( - data); - resources.add(new Link("localhost")); - resources.add(new Link("/page/2").withRel("next")); + CollectionModel> 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> 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> 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> 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> resources = new CollectionModel<>( - data); - resources.add(new Link("localhost")); - resources.add(new Link("/page/2").withRel("next")); + CollectionModel> 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> 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> setupAnnotatedPagedResources() { List> 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 diff --git a/src/test/java/org/springframework/hateoas/mediatype/collectionjson/JacksonSerializationTest.java b/src/test/java/org/springframework/hateoas/mediatype/collectionjson/JacksonSerializationTest.java index 0e6bd0db..698c84f6 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/collectionjson/JacksonSerializationTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/collectionjson/JacksonSerializationTest.java @@ -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); diff --git a/src/test/java/org/springframework/hateoas/mediatype/hal/DefaultCurieProviderUnitTest.java b/src/test/java/org/springframework/hateoas/mediatype/hal/DefaultCurieProviderUnitTest.java index 2fd578e9..61edcc6a 100755 --- a/src/test/java/org/springframework/hateoas/mediatype/hal/DefaultCurieProviderUnitTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/hal/DefaultCurieProviderUnitTest.java @@ -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 curies = provider.getCurieInformation(links); assertThat(curies).hasSize(1); diff --git a/src/test/java/org/springframework/hateoas/mediatype/hal/Jackson2HalIntegrationTest.java b/src/test/java/org/springframework/hateoas/mediatype/hal/Jackson2HalIntegrationTest.java index 31840c9e..6e9d43ba 100755 --- a/src/test/java/org/springframework/hateoas/mediatype/hal/Jackson2HalIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/hal/Jackson2HalIntegrationTest.java @@ -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 resources = new CollectionModel<>(content); - resources.add(new Link("localhost")); + CollectionModel 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 expected = new CollectionModel<>(content); - expected.add(new Link("localhost")); + CollectionModel expected = CollectionModel.of(content); + expected.add(Link.of("localhost")); CollectionModel 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> 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> resources = new CollectionModel<>(content); - resources.add(new Link("localhost")); + CollectionModel> 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> 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> expected = new CollectionModel<>(content); - expected.add(new Link("localhost")); + CollectionModel> expected = CollectionModel.of(content); + expected.add(Link.of("localhost")); TypeFactory typeFactory = mapper.getTypeFactory(); CollectionModel> result = mapper.readValue(SINGLE_EMBEDDED_RESOURCE_REFERENCE, @@ -268,7 +268,7 @@ class Jackson2HalIntegrationTest { void rendersMultipleResourceResourcesAsEmbedded() throws Exception { CollectionModel> 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> expected = setupResources(); - expected.add(new Link("localhost")); + expected.add(Link.of("localhost")); CollectionModel> result = mapper.readValue(LIST_EMBEDDED_RESOURCE_REFERENCE, mapper.getTypeFactory().constructParametricType(CollectionModel.class, @@ -293,10 +293,10 @@ class Jackson2HalIntegrationTest { void serializesAnnotatedResourceResourcesAsEmbedded() throws Exception { List> 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> resources = new CollectionModel<>(content); - resources.add(new Link("localhost")); + CollectionModel> 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> 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> expected = new CollectionModel<>(content); - expected.add(new Link("localhost")); + CollectionModel> expected = CollectionModel.of(content); + expected.add(Link.of("localhost")); CollectionModel> result = mapper.readValue(ANNOTATED_EMBEDDED_RESOURCE_REFERENCE, mapper.getTypeFactory().constructParametricType(CollectionModel.class, @@ -367,8 +367,8 @@ class Jackson2HalIntegrationTest { @Test void rendersCuriesCorrectly() throws Exception { - CollectionModel resources = new CollectionModel<>(Collections.emptySet(), new Link("foo"), - new Link("bar", "myrel")); + CollectionModel 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 resources = new CollectionModel<>(Collections.emptySet()); + CollectionModel resources = CollectionModel.of(Collections.emptySet()); assertThat(getCuriedObjectMapper().writeValueAsString(resources)).isEqualTo(EMPTY_DOCUMENT); } @@ -389,8 +389,8 @@ class Jackson2HalIntegrationTest { @Test void doesNotRenderCuriesIfNoCurieLinkIsPresent() throws Exception { - CollectionModel resources = new CollectionModel<>(Collections.emptySet()); - resources.add(new Link("foo")); + CollectionModel 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 resources = new CollectionModel<>(Collections.emptySet()); - resources.add(new Link("foo", "myrel")); + CollectionModel 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 values = new ArrayList<>(); values.add(wrappers.emptyCollectionOf(SimpleAnnotatedPojo.class)); - CollectionModel resources = new CollectionModel<>(values); + CollectionModel 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 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 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 model = new CollectionModel<>(Arrays.asList(new SomeSample())); - model.add(new Link("/foo", LinkRelation.of("someSample"))); + CollectionModel 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> setupAnnotatedPagedResources() { List> 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> setupAnnotatedResources() { List> 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> setupResources() { List> 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() { diff --git a/src/test/java/org/springframework/hateoas/mediatype/hal/RenderHypermediaForDefaultAcceptHeadersTest.java b/src/test/java/org/springframework/hateoas/mediatype/hal/RenderHypermediaForDefaultAcceptHeadersTest.java index bd269ee4..6e27cb5b 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/hal/RenderHypermediaForDefaultAcceptHeadersTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/hal/RenderHypermediaForDefaultAcceptHeadersTest.java @@ -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); } } diff --git a/src/test/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsMessageConverterUnitTest.java b/src/test/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsMessageConverterUnitTest.java index 100d50af..ca683fee 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsMessageConverterUnitTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsMessageConverterUnitTest.java @@ -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(); diff --git a/src/test/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsTemplateBuilderUnitTest.java b/src/test/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsTemplateBuilderUnitTest.java index d311e83c..82696bbb 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsTemplateBuilderUnitTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsTemplateBuilderUnitTest.java @@ -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) // diff --git a/src/test/java/org/springframework/hateoas/mediatype/hal/forms/Jackson2HalFormsIntegrationTest.java b/src/test/java/org/springframework/hateoas/mediatype/hal/forms/Jackson2HalFormsIntegrationTest.java index 34772b40..bb410865 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/hal/forms/Jackson2HalFormsIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/hal/forms/Jackson2HalFormsIntegrationTest.java @@ -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 resource = new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost")); + EntityModel 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 expected = new EntityModel<>(new SimplePojo("test1", 1), new Link("localhost")); + EntityModel expected = EntityModel.of(new SimplePojo("test1", 1), Link.of("localhost")); EntityModel 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 resources = new CollectionModel<>(content); - resources.add(new Link("localhost")); + CollectionModel 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 expected = new CollectionModel<>(content); - expected.add(new Link("localhost")); + CollectionModel expected = CollectionModel.of(content); + expected.add(Link.of("localhost")); CollectionModel 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> 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> resources = new CollectionModel<>(content); - resources.add(new Link("localhost")); + CollectionModel> 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> 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> expected = new CollectionModel<>(content); - expected.add(new Link("localhost")); + CollectionModel> expected = CollectionModel.of(content); + expected.add(Link.of("localhost")); CollectionModel> 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> 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> expected = setupResources(); - expected.add(new Link("localhost")); + expected.add(Link.of("localhost")); CollectionModel> 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> 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> resources = new CollectionModel<>(content); - resources.add(new Link("localhost")); + CollectionModel> 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> 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> expected = new CollectionModel<>(content); - expected.add(new Link("localhost")); + CollectionModel> expected = CollectionModel.of(content); + expected.add(Link.of("localhost")); CollectionModel> 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 resources = new CollectionModel<>(Collections.emptySet(), new Link("foo"), - new Link("bar", "myrel")); + CollectionModel 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 resources = new CollectionModel<>(Collections.emptySet()); + CollectionModel 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 resources = new CollectionModel<>(Collections.emptySet()); - resources.add(new Link("foo")); + CollectionModel 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 resources = new CollectionModel<>(Collections.emptySet()); - resources.add(new Link("foo", "myrel")); + CollectionModel 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 values = new ArrayList<>(); values.add(wrappers.emptyCollectionOf(SimpleAnnotatedPojo.class)); - CollectionModel resources = new CollectionModel<>(values); + CollectionModel 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 model = new EntityModel<>(new HalFormsPayload(), link); + EntityModel 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 model = new EntityModel<>(new HalFormsPayload(), link); + EntityModel 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 model = new EntityModel<>(new Jsr303Sample(), link); + EntityModel 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> setupResources() { List> 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> setupAnnotatedResources() { List> 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> setupAnnotatedPagedResources() { List> 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() { diff --git a/src/test/java/org/springframework/hateoas/mediatype/uber/Jackson2UberIntegrationTest.java b/src/test/java/org/springframework/hateoas/mediatype/uber/Jackson2UberIntegrationTest.java index bc959ff9..d7c23a78 100644 --- a/src/test/java/org/springframework/hateoas/mediatype/uber/Jackson2UberIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/uber/Jackson2UberIntegrationTest.java @@ -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 resources = new CollectionModel<>(content); - resources.add(new Link("localhost")); + CollectionModel 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 expected = new CollectionModel<>(content); - expected.add(new Link("localhost")); + CollectionModel 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> content = new ArrayList<>(); - content.add(new EntityModel<>("first")); - content.add(new EntityModel<>("second")); + content.add(EntityModel.of("first")); + content.add(EntityModel.of("second")); - CollectionModel> expected = new CollectionModel<>(content); - expected.add(new Link("localhost")); + CollectionModel> 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 data = new EntityModel<>("first", new Link("localhost")); + EntityModel 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 data2 = new EntityModel<>("second", new Link("localhost").withRel("custom")); + EntityModel 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 data3 = new EntityModel<>("third", new Link("localhost"), new Link("second").withRel("second"), - new Link("third").withRel("third")); + EntityModel 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 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 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 actual = mapper.readValue(MappingUtils.read(new ClassPathResource("resource.json", getClass())), resourceStringType); assertThat(actual).isEqualTo(expected); - EntityModel expected2 = new EntityModel<>("second", new Link("localhost").withRel("custom")); + EntityModel expected2 = EntityModel.of("second", Link.of("localhost").withRel("custom")); EntityModel actual2 = mapper .readValue(MappingUtils.read(new ClassPathResource("resource2.json", getClass())), resourceStringType); assertThat(actual2).isEqualTo(expected2); - EntityModel expected3 = new EntityModel<>("third", new Link("localhost"), - new Link("second").withRel("second"), new Link("third").withRel("third")); + EntityModel expected3 = EntityModel.of("third", Link.of("localhost"), + Link.of("second").withRel("second"), Link.of("third").withRel("third")); EntityModel actual3 = mapper .readValue(MappingUtils.read(new ClassPathResource("resource3.json", getClass())), resourceStringType); assertThat(actual3).isEqualTo(expected3); - EntityModel 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 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 actual4 = mapper .readValue(MappingUtils.read(new ClassPathResource("resource4.json", getClass())), resourceStringType); @@ -267,12 +267,12 @@ class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegration void renderComplexStructure() throws Exception { List> 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> resources = new CollectionModel<>(data); - resources.add(new Link("localhost")); - resources.add(new Link("/page/2").withRel("next")); + CollectionModel> 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> 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> 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> 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> 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> 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> 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 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 expected = new EntityModel<>(employee, new Link("/employees/1").withSelfRel()); + EntityModel 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 expected = new EntityModel<>(employee, new Link("/employees/1").withSelfRel()); + EntityModel expected = EntityModel.of(employee, Link.of("/employees/1").withSelfRel()); EntityModel 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 expected = new EntityModel<>(employee, new Link("/employees/1").withSelfRel()); + EntityModel expected = EntityModel.of(employee, Link.of("/employees/1").withSelfRel()); EntityModel 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> content = new ArrayList<>(); Employee employee = new Employee("Frodo", "ring bearer"); - EntityModel employeeResource = new EntityModel<>(employee, new Link("/employees/1").withSelfRel()); + EntityModel 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 diff --git a/src/test/java/org/springframework/hateoas/mediatype/vnderror/VndErrorsMarshallingTest.java b/src/test/java/org/springframework/hateoas/mediatype/vnderror/VndErrorsMarshallingTest.java index 0a332af0..e83e4d6b 100755 --- a/src/test/java/org/springframework/hateoas/mediatype/vnderror/VndErrorsMarshallingTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/vnderror/VndErrorsMarshallingTest.java @@ -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())); diff --git a/src/test/java/org/springframework/hateoas/mediatype/vnderror/VndErrorsUnitTest.java b/src/test/java/org/springframework/hateoas/mediatype/vnderror/VndErrorsUnitTest.java index ade4cf32..01953421 100755 --- a/src/test/java/org/springframework/hateoas/mediatype/vnderror/VndErrorsUnitTest.java +++ b/src/test/java/org/springframework/hateoas/mediatype/vnderror/VndErrorsUnitTest.java @@ -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: [;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: [;rel=\"bar\"]]]"); } diff --git a/src/test/java/org/springframework/hateoas/server/mvc/ControllerLinkBuilderOutsideSpringMvcUnitTest.java b/src/test/java/org/springframework/hateoas/server/mvc/ControllerLinkBuilderOutsideSpringMvcUnitTest.java index 8cdc5631..aabf6e2d 100755 --- a/src/test/java/org/springframework/hateoas/server/mvc/ControllerLinkBuilderOutsideSpringMvcUnitTest.java +++ b/src/test/java/org/springframework/hateoas/server/mvc/ControllerLinkBuilderOutsideSpringMvcUnitTest.java @@ -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()); } } diff --git a/src/test/java/org/springframework/hateoas/server/mvc/HeaderLinksResponseEntityUnitTest.java b/src/test/java/org/springframework/hateoas/server/mvc/HeaderLinksResponseEntityUnitTest.java index 52b36145..df61027d 100755 --- a/src/test/java/org/springframework/hateoas/server/mvc/HeaderLinksResponseEntityUnitTest.java +++ b/src/test/java/org/springframework/hateoas/server/mvc/HeaderLinksResponseEntityUnitTest.java @@ -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 resource = new EntityModel<>(CONTENT, LINK); + EntityModel resource = EntityModel.of(CONTENT, LINK); ResponseEntity> entity = new ResponseEntity<>(resource, HttpStatus.OK); @Test diff --git a/src/test/java/org/springframework/hateoas/server/mvc/MultiMediaTypeWebMvcIntegrationTest.java b/src/test/java/org/springframework/hateoas/server/mvc/MultiMediaTypeWebMvcIntegrationTest.java index 4bdd0039..4a77cf8c 100644 --- a/src/test/java/org/springframework/hateoas/server/mvc/MultiMediaTypeWebMvcIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/server/mvc/MultiMediaTypeWebMvcIntegrationTest.java @@ -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); diff --git a/src/test/java/org/springframework/hateoas/server/mvc/RepresentationModelProcessorIntegrationTest.java b/src/test/java/org/springframework/hateoas/server/mvc/RepresentationModelProcessorIntegrationTest.java index 1e393472..d47f3a3d 100644 --- a/src/test/java/org/springframework/hateoas/server/mvc/RepresentationModelProcessorIntegrationTest.java +++ b/src/test/java/org/springframework/hateoas/server/mvc/RepresentationModelProcessorIntegrationTest.java @@ -161,7 +161,7 @@ public class RepresentationModelProcessorIntegrationTest { public EntityModel process(EntityModel 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> process(CollectionModel> 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; } } diff --git a/src/test/java/org/springframework/hateoas/server/mvc/ResourceProcessorHandlerMethodReturnValueHandlerUnitTest.java b/src/test/java/org/springframework/hateoas/server/mvc/ResourceProcessorHandlerMethodReturnValueHandlerUnitTest.java index f9d210d9..87b828ee 100644 --- a/src/test/java/org/springframework/hateoas/server/mvc/ResourceProcessorHandlerMethodReturnValueHandlerUnitTest.java +++ b/src/test/java/org/springframework/hateoas/server/mvc/ResourceProcessorHandlerMethodReturnValueHandlerUnitTest.java @@ -61,21 +61,21 @@ import org.springframework.web.method.support.HandlerMethodReturnValueHandler; @ExtendWith(MockitoExtension.class) class ResourceProcessorHandlerMethodReturnValueHandlerUnitTest { - static final EntityModel FOO = new EntityModel<>("foo"); - static final CollectionModel> FOOS = new CollectionModel<>(Collections.singletonList(FOO)); - static final PagedModel> FOO_PAGE = new PagedModel<>(singleton(FOO), new PageMetadata(1, 0, 10)); + static final EntityModel FOO = EntityModel.of("foo"); + static final CollectionModel> FOOS = CollectionModel.of(Collections.singletonList(FOO)); + static final PagedModel> FOO_PAGE = PagedModel.of(singleton(FOO), new PageMetadata(1, 0, 10)); static final StringResource FOO_RES = new StringResource("foo"); static final HttpEntity> FOO_ENTITY = new HttpEntity<>(FOO); static final ResponseEntity> FOO_RESP_ENTITY = new ResponseEntity<>(FOO, HttpStatus.OK); static final HttpEntity FOO_RES_ENTITY = new HttpEntity<>(FOO_RES); - static final EntityModel BAR = new EntityModel<>("bar"); - static final CollectionModel> BARS = new CollectionModel<>(Collections.singletonList(BAR)); + static final EntityModel BAR = EntityModel.of("bar"); + static final CollectionModel> BARS = CollectionModel.of(Collections.singletonList(BAR)); static final StringResource BAR_RES = new StringResource("bar"); static final HttpEntity> BAR_ENTITY = new HttpEntity<>(BAR); static final ResponseEntity> BAR_RESP_ENTITY = new ResponseEntity<>(BAR, HttpStatus.OK); static final HttpEntity BAR_RES_ENTITY = new HttpEntity<>(BAR_RES); - static final EntityModel LONG_10 = new EntityModel<>(10L); - static final EntityModel LONG_20 = new EntityModel<>(20L); + static final EntityModel LONG_10 = EntityModel.of(10L); + static final EntityModel 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> LONG_10_ENTITY = new HttpEntity<>(LONG_10); @@ -250,7 +250,7 @@ class ResourceProcessorHandlerMethodReturnValueHandlerUnitTest { private void usesHeaderLinksResponseEntityIfConfigured(Function mapper) throws Exception { - EntityModel resource = new EntityModel<>("foo", new Link("href", "rel")); + EntityModel 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 value = new CollectionModel<>(singleton(wrappers.emptyCollectionOf(Object.class))); + CollectionModel value = CollectionModel.of(singleton(wrappers.emptyCollectionOf(Object.class))); CollectionModelProcessorWrapper wrapper = new CollectionModelProcessorWrapper(new SpecialResourcesProcessor()); ResolvableType type = ResolvableType.forMethodReturnType(Controller.class.getMethod("resourcesOfObject")); diff --git a/src/test/java/org/springframework/hateoas/server/mvc/WebMvcLinkBuilderOutsideSpringMvcUnitTest.java b/src/test/java/org/springframework/hateoas/server/mvc/WebMvcLinkBuilderOutsideSpringMvcUnitTest.java index ec18ce5d..ea7312d4 100644 --- a/src/test/java/org/springframework/hateoas/server/mvc/WebMvcLinkBuilderOutsideSpringMvcUnitTest.java +++ b/src/test/java/org/springframework/hateoas/server/mvc/WebMvcLinkBuilderOutsideSpringMvcUnitTest.java @@ -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()); } } diff --git a/src/test/java/org/springframework/hateoas/server/reactive/HypermediaWebFilterTest.java b/src/test/java/org/springframework/hateoas/server/reactive/HypermediaWebFilterTest.java index 99c566c7..a9a0f498 100644 --- a/src/test/java/org/springframework/hateoas/server/reactive/HypermediaWebFilterTest.java +++ b/src/test/java/org/springframework/hateoas/server/reactive/HypermediaWebFilterTest.java @@ -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(); diff --git a/src/test/java/org/springframework/hateoas/server/reactive/ReactiveResourceAssemblerUnitTest.java b/src/test/java/org/springframework/hateoas/server/reactive/ReactiveResourceAssemblerUnitTest.java index e82e34bc..181a07b7 100644 --- a/src/test/java/org/springframework/hateoas/server/reactive/ReactiveResourceAssemblerUnitTest.java +++ b/src/test/java/org/springframework/hateoas/server/reactive/ReactiveResourceAssemblerUnitTest.java @@ -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 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 employeeResources = new CollectionModel<>( + CollectionModel 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; }); diff --git a/src/test/java/org/springframework/hateoas/server/reactive/SimpleReactiveResourceAssemblerTest.java b/src/test/java/org/springframework/hateoas/server/reactive/SimpleReactiveResourceAssemblerTest.java index 2461bcef..ea57abda 100644 --- a/src/test/java/org/springframework/hateoas/server/reactive/SimpleReactiveResourceAssemblerTest.java +++ b/src/test/java/org/springframework/hateoas/server/reactive/SimpleReactiveResourceAssemblerTest.java @@ -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 addLinks(EntityModel resource, ServerWebExchange exchange) { - return resource.add(new Link("/employees").withRel("employees")); + return resource.add(Link.of("/employees").withRel("employees")); } @Override public CollectionModel> addLinks( CollectionModel> resources, ServerWebExchange exchange) { - return resources.add(new Link("/").withRel("root")); + return resources.add(Link.of("/").withRel("root")); } } diff --git a/src/test/java/org/springframework/hateoas/support/MappingUtils.java b/src/test/java/org/springframework/hateoas/support/MappingUtils.java index a3aa28ed..45ee6f64 100644 --- a/src/test/java/org/springframework/hateoas/support/MappingUtils.java +++ b/src/test/java/org/springframework/hateoas/support/MappingUtils.java @@ -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())) { diff --git a/src/test/java/org/springframework/hateoas/support/WebFluxEmployeeController.java b/src/test/java/org/springframework/hateoas/support/WebFluxEmployeeController.java index 5d86d9aa..a9878893 100644 --- a/src/test/java/org/springframework/hateoas/support/WebFluxEmployeeController.java +++ b/src/test/java/org/springframework/hateoas/support/WebFluxEmployeeController.java @@ -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 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") diff --git a/src/test/java/org/springframework/hateoas/support/WebMvcEmployeeController.java b/src/test/java/org/springframework/hateoas/support/WebMvcEmployeeController.java index 7913169b..50622b8b 100644 --- a/src/test/java/org/springframework/hateoas/support/WebMvcEmployeeController.java +++ b/src/test/java/org/springframework/hateoas/support/WebMvcEmployeeController.java @@ -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))), //