#812 - General overhaul and refactorings.

Cleanups in Affordance API and implementations of hypermedia type (de)serializers. Added a lot more domain methods and types to Link, ResourceSupport etc. to be able to move a lot of representation building logic into those.

AffordanceModelFactory is not a Spring Plugin anymore as that functionality is not needed currently as we statically look up all factories via the SpringFactoriesLoader mechanism.

Redesigned LinkRelation to become a first class abstraction in the codebase. IanaLinkRelations is now a collection of constants. Link now keeps a LinkRelation instance around instead of a plain String.

Tweaked LinkDiscoverer API to return Optional and Links instead of nullable Link and List<Link>.

Tweaked API of CurieProvider to make use of the newly introduced HalLinkRelation based on the general LinkRelation.

Additional fixes for the Kotlin extension functions. Make Kotlin build setup compile with JDK 8. Removed Objects helper class in favor of Spring's already existing Assert and it's usage in ResourceAssemblerSupport.
This commit is contained in:
Oliver Drotbohm
2019-02-12 22:04:36 +01:00
committed by Oliver Drotbohm
parent 38b98af786
commit 9e5db1874e
116 changed files with 3282 additions and 2594 deletions

View File

@@ -31,7 +31,7 @@ public class IanaLinkRelationUnitTest {
*/
@Test
public void extractingValueOfIanaLinkRelationShouldWork() {
assertThat(IanaLinkRelation.ABOUT.value()).isEqualTo("about");
assertThat(IanaLinkRelations.ABOUT.value()).isEqualTo("about");
}
/**
@@ -40,13 +40,13 @@ public class IanaLinkRelationUnitTest {
@Test
public void testingForOfficialIanaLinkRelation() {
assertThat(IanaLinkRelation.isIanaRel((String) null)).isFalse();
assertThat(IanaLinkRelation.isIanaRel((LinkRelation) null)).isFalse();
assertThat(IanaLinkRelation.isIanaRel("")).isFalse();
assertThat(IanaLinkRelation.isIanaRel("foo-bar")).isFalse();
assertThat(IanaLinkRelations.isIanaRel((String) null)).isFalse();
assertThat(IanaLinkRelations.isIanaRel((LinkRelation) null)).isFalse();
assertThat(IanaLinkRelations.isIanaRel("")).isFalse();
assertThat(IanaLinkRelations.isIanaRel("foo-bar")).isFalse();
assertThat(IanaLinkRelation.isIanaRel("about")).isTrue();
assertThat(IanaLinkRelation.isIanaRel("ABOUT")).isTrue();
assertThat(IanaLinkRelations.isIanaRel("about")).isTrue();
assertThat(IanaLinkRelations.isIanaRel("ABOUT")).isTrue();
}
/**
@@ -55,26 +55,26 @@ public class IanaLinkRelationUnitTest {
@Test
public void parsingIanaLinkRelationsShouldWork() {
assertThat(IanaLinkRelation.parse("about")).isEqualTo(IanaLinkRelation.ABOUT);
assertThat(IanaLinkRelation.parse("ABOUT")).isEqualTo(IanaLinkRelation.ABOUT);
assertThat(IanaLinkRelations.parse("about")).isEqualTo(IanaLinkRelations.ABOUT);
assertThat(IanaLinkRelations.parse("ABOUT")).isEqualTo(IanaLinkRelations.ABOUT);
assertThatIllegalArgumentException().isThrownBy(() -> IanaLinkRelation.parse(null));
assertThatIllegalArgumentException().isThrownBy(() -> IanaLinkRelation.parse(""));
assertThatIllegalArgumentException().isThrownBy(() -> IanaLinkRelation.parse("faulty"));
assertThatIllegalArgumentException().isThrownBy(() -> IanaLinkRelation.parse("FAULTY"));
assertThatIllegalArgumentException().isThrownBy(() -> IanaLinkRelations.parse(null));
assertThatIllegalArgumentException().isThrownBy(() -> IanaLinkRelations.parse(""));
assertThatIllegalArgumentException().isThrownBy(() -> IanaLinkRelations.parse("faulty"));
assertThatIllegalArgumentException().isThrownBy(() -> IanaLinkRelations.parse("FAULTY"));
}
@Test
public void testIanaLinkRelationShouldPass() {
assertThat(IanaLinkRelation.isIanaRel(IanaLinkRelation.ABOUT)).isTrue();
assertThat(IanaLinkRelations.isIanaRel(IanaLinkRelations.ABOUT)).isTrue();
}
@Test
public void comparingNonIanaLinkRelationsToIanaLinkRelationsDontGuaranteeAMatch() {
assertThat(IanaLinkRelation.isIanaRel(new CustomLinkRelation("about"))).isTrue();
assertThat(IanaLinkRelation.isIanaRel(new CustomLinkRelation("ABOUT"))).isTrue();
assertThat(IanaLinkRelation.isIanaRel(new CustomLinkRelation("something-new"))).isFalse();
assertThat(IanaLinkRelations.isIanaRel(new CustomLinkRelation("about"))).isTrue();
assertThat(IanaLinkRelations.isIanaRel(new CustomLinkRelation("ABOUT"))).isTrue();
assertThat(IanaLinkRelations.isIanaRel(new CustomLinkRelation("something-new"))).isFalse();
}
/**

View File

@@ -21,7 +21,7 @@ import org.junit.Test;
/**
* Integration tests for {@link org.springframework.hateoas.Link} marshaling.
*
*
* @author Oliver Gierke
* @author Jon Brisbin
*/
@@ -44,6 +44,6 @@ public class Jackson2LinkIntegrationTest extends AbstractJackson2MarshallingInte
public void readsLinkCorrectly() throws Exception {
Link result = read(REFERENCE, Link.class);
assertThat(result.getHref()).isEqualTo("location");
assertThat(result.getRel()).isEqualTo("something");
assertThat(result.getRel()).isEqualTo(LinkRelation.of("something"));
}
}

View File

@@ -21,7 +21,7 @@ import org.junit.Test;
/**
* Integration tests for {@link Link} marshaling.
*
*
* @author Oliver Gierke
*/
public class LinkIntegrationTest extends AbstractJackson2MarshallingIntegrationTest {
@@ -44,7 +44,7 @@ public class LinkIntegrationTest extends AbstractJackson2MarshallingIntegrationT
Link result = read(REFERENCE, Link.class);
assertThat(result.getHref()).isEqualTo("location");
assertThat(result.getRel()).isEqualTo("something");
assertThat(result.getRel()).isEqualTo(LinkRelation.of("something"));
assertThat(result.getAffordances()).hasSize(0);
}
}

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.hateoas;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import lombok.Value;
@@ -43,11 +44,9 @@ public class LinkRelationUnitTest {
assertThat(MyOwnLinkRelation.FOO.value()).isEqualTo("foo");
assertThat(MyOwnLinkRelation.BAR.value()).isEqualTo("bar");
Set<LinkRelation> myOwnLinkRelations = Arrays.stream(MyOwnLinkRelation.values())
.collect(Collectors.toSet());
Set<LinkRelation> myOwnLinkRelations = Arrays.stream(MyOwnLinkRelation.values()).collect(Collectors.toSet());
assertThat(myOwnLinkRelations)
.containsExactlyInAnyOrder(MyOwnLinkRelation.FOO, MyOwnLinkRelation.BAR);
assertThat(myOwnLinkRelations).containsExactlyInAnyOrder(MyOwnLinkRelation.FOO, MyOwnLinkRelation.BAR);
}
/**
@@ -58,9 +57,13 @@ public class LinkRelationUnitTest {
private String value;
/*
* (non-Javadoc)
* @see org.springframework.hateoas.LinkRelation#value()
*/
@Override
public String value() {
return this.value;
return value;
}
}
@@ -69,8 +72,7 @@ public class LinkRelationUnitTest {
*/
enum MyOwnLinkRelation implements LinkRelation {
FOO("foo"),
BAR("bar");
FOO("foo"), BAR("bar");
private final String value;
@@ -78,9 +80,13 @@ public class LinkRelationUnitTest {
this.value = value;
}
/*
* (non-Javadoc)
* @see org.springframework.hateoas.LinkRelation#value()
*/
@Override
public String value() {
return this.value;
return value;
}
}

View File

@@ -21,44 +21,39 @@ import static org.assertj.core.api.SoftAssertions.*;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.hateoas.support.Employee;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
/**
* Unit tests for {@link Link}.
*
*
* @author Oliver Gierke
* @author Greg Turnquist
* @author Jens Schauder
*/
public class LinkUnitTest {
private static final Affordance TEST_AFFORDANCE = new Affordance(null, null, HttpMethod.GET, null, Collections.emptyList(), null);
private static final Affordance TEST_AFFORDANCE = new Affordance(null, null, HttpMethod.GET, null,
Collections.emptyList(), null);
@Test
public void linkWithHrefOnlyBecomesSelfLink() {
Link link = new Link("foo");
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(new Link("foo").hasRel(IanaLinkRelations.SELF)).isTrue();
}
@Test
public void createsLinkFromRelAndHref() {
Link link = new Link("foo", IanaLinkRelation.SELF.value());
Link link = new Link("foo", IanaLinkRelations.SELF);
assertSoftly(softly -> {
softly.assertThat(link.getHref()).isEqualTo("foo");
softly.assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
softly.assertThat(link.hasRel(IanaLinkRelations.SELF)).isTrue();
});
}
@@ -69,7 +64,7 @@ public class LinkUnitTest {
@Test(expected = IllegalArgumentException.class)
public void rejectsNullRel() {
new Link("foo", null);
new Link("foo", (String) null);
}
@Test(expected = IllegalArgumentException.class)
@@ -85,8 +80,8 @@ public class LinkUnitTest {
@Test
public void sameRelAndHrefMakeSameLink() {
Link left = new Link("foo", IanaLinkRelation.SELF.value());
Link right = new Link("foo", IanaLinkRelation.SELF.value());
Link left = new Link("foo", IanaLinkRelations.SELF);
Link right = new Link("foo", IanaLinkRelations.SELF);
TestUtils.assertEqualAndSameHashCode(left, right);
}
@@ -94,8 +89,8 @@ public class LinkUnitTest {
@Test
public void differentRelMakesDifferentLink() {
Link left = new Link("foo", IanaLinkRelation.PREV.value());
Link right = new Link("foo", IanaLinkRelation.NEXT.value());
Link left = new Link("foo", IanaLinkRelations.PREV);
Link right = new Link("foo", IanaLinkRelations.NEXT);
TestUtils.assertNotEqualAndDifferentHashCode(left, right);
}
@@ -103,8 +98,8 @@ public class LinkUnitTest {
@Test
public void differentHrefMakesDifferentLink() {
Link left = new Link("foo", IanaLinkRelation.SELF.value());
Link right = new Link("bar", IanaLinkRelation.SELF.value());
Link left = new Link("foo", IanaLinkRelations.SELF);
Link right = new Link("bar", IanaLinkRelations.SELF);
TestUtils.assertNotEqualAndDifferentHashCode(left, right);
}
@@ -162,12 +157,13 @@ public class LinkUnitTest {
*/
@Test
public void ignoresUnrecognizedAttributes() {
Link link = Link.valueOf("</something>;rel=\"foo\";unknown=\"should fail\"");
assertSoftly(softly -> {
softly.assertThat(link.getHref()).isEqualTo("/something");
softly.assertThat(link.getRel()).isEqualTo("foo");
softly.assertThat(link.hasRel("foo")).isTrue();
});
}
@@ -247,8 +243,8 @@ public class LinkUnitTest {
@Test
public void parsesLinkRelationWithDotAndMinus() {
assertThat(Link.valueOf("<http://localhost>; rel=\"rel-with-minus-and-.\"").getRel())
.isEqualTo("rel-with-minus-and-.");
assertThat(Link.valueOf("<http://localhost>; rel=\"rel-with-minus-and-.\"").hasRel("rel-with-minus-and-."))
.isTrue();
}
/**
@@ -258,7 +254,7 @@ public class LinkUnitTest {
public void parsesUriLinkRelations() {
assertThat(Link.valueOf("<http://localhost>; rel=\"http://acme.com/rels/foo-bar\"").getRel()) //
.isEqualTo("http://acme.com/rels/foo-bar");
.isEqualTo(LinkRelation.of("http://acme.com/rels/foo-bar"));
}
/**
@@ -305,66 +301,95 @@ public class LinkUnitTest {
Link link = new Link("/");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> link.hasRel(null));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> link.hasRel((String) null));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> link.hasRel(""));
}
@Test
public void affordanceConvenienceMethodChainsExistingLink() {
Link link = new Link("/").andAffordance("name", HttpMethod.POST, ResolvableType.forClass(Employee.class), Collections.emptyList(), ResolvableType.forClass(Employee.class));
Link link = new Link("/").andAffordance("name", HttpMethod.POST, ResolvableType.forClass(Employee.class),
Collections.emptyList(), ResolvableType.forClass(Employee.class));
assertThat(link.getHref()).isEqualTo("/");
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.hasRel(IanaLinkRelations.SELF)).isTrue();
assertThat(link.getAffordances()).hasSize(1);
assertThat(link.getAffordances().get(0).getAffordanceModels()).hasSize(3);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getName()).isEqualTo("name");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getHttpMethod()).isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getInputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getQueryMethodParameters()).hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getOutputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getHttpMethod())
.isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getInputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getQueryMethodParameters())
.hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getOutputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getName()).isEqualTo("name");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getHttpMethod()).isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getInputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getQueryMethodParameters()).hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getOutputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getHttpMethod())
.isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getInputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getQueryMethodParameters())
.hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getOutputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getName()).isEqualTo("name");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getHttpMethod()).isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getInputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getQueryMethodParameters()).hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getOutputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getHttpMethod())
.isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getInputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getQueryMethodParameters())
.hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getOutputType().resolve())
.isEqualTo(Employee.class);
}
@Test
public void affordanceConvenienceMethodDefaultsNameBasedOnHttpVerb() {
Link link = new Link("/").andAffordance(HttpMethod.POST, ResolvableType.forClass(Employee.class), Collections.emptyList(), ResolvableType.forClass(Employee.class));
Link link = new Link("/").andAffordance(HttpMethod.POST, ResolvableType.forClass(Employee.class),
Collections.emptyList(), ResolvableType.forClass(Employee.class));
assertThat(link.getHref()).isEqualTo("/");
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.hasRel(IanaLinkRelations.SELF)).isTrue();
assertThat(link.getAffordances()).hasSize(1);
assertThat(link.getAffordances().get(0).getAffordanceModels()).hasSize(3);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getName()).isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getHttpMethod()).isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getInputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getQueryMethodParameters()).hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getOutputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getName())
.isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getHttpMethod())
.isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getInputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getQueryMethodParameters())
.hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getOutputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getName()).isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getHttpMethod()).isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getInputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getQueryMethodParameters()).hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getOutputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getName())
.isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getHttpMethod())
.isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getInputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getQueryMethodParameters())
.hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getOutputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getName()).isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getHttpMethod()).isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getInputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getQueryMethodParameters()).hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getOutputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getName())
.isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getHttpMethod())
.isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getInputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getQueryMethodParameters())
.hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getOutputType().resolve())
.isEqualTo(Employee.class);
}
@Test
@@ -373,26 +398,41 @@ public class LinkUnitTest {
Link link = new Link("/").andAffordance(HttpMethod.POST, Employee.class, Collections.emptyList(), Employee.class);
assertThat(link.getHref()).isEqualTo("/");
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.hasRel(IanaLinkRelations.SELF)).isTrue();
assertThat(link.getAffordances()).hasSize(1);
assertThat(link.getAffordances().get(0).getAffordanceModels()).hasSize(3);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getName()).isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getHttpMethod()).isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getInputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getQueryMethodParameters()).hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getOutputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getName())
.isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getHttpMethod())
.isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getInputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getQueryMethodParameters())
.hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.COLLECTION_JSON).getOutputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getName()).isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getHttpMethod()).isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getInputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getQueryMethodParameters()).hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getOutputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getName())
.isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getHttpMethod())
.isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getInputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getQueryMethodParameters())
.hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.HAL_FORMS_JSON).getOutputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getName()).isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getHttpMethod()).isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getInputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getQueryMethodParameters()).hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getOutputType().resolve()).isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getName())
.isEqualTo("postEmployee");
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getHttpMethod())
.isEqualTo(HttpMethod.POST);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getInputType().resolve())
.isEqualTo(Employee.class);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getQueryMethodParameters())
.hasSize(0);
assertThat(link.getAffordances().get(0).getAffordanceModel(MediaTypes.UBER_JSON).getOutputType().resolve())
.isEqualTo(Employee.class);
}
}

View File

@@ -43,30 +43,30 @@ public class LinksUnitTest {
static final String LINKS2 = StringUtils.collectionToCommaDelimitedString(Arrays.asList(THIRD, FOURTH));
static final Links reference = new Links(new Link("/something", "foo"), new Link("/somethingElse", "bar"));
static final Links reference2 = new Links(new Link("/something", "foo").withHreflang("en"),
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"));
@Test
public void parsesLinkHeaderLinks() {
assertThat(Links.valueOf(LINKS)).isEqualTo(reference);
assertThat(Links.valueOf(LINKS2)).isEqualTo(reference2);
assertThat(Links.parse(LINKS)).isEqualTo(reference);
assertThat(Links.parse(LINKS2)).isEqualTo(reference2);
assertThat(reference.toString()).isEqualTo(LINKS);
assertThat(reference2.toString()).isEqualTo(LINKS2);
}
@Test
public void skipsEmptyLinkElements() {
assertThat(Links.valueOf(LINKS + ",,,")).isEqualTo(reference);
assertThat(Links.valueOf(LINKS2 + ",,,")).isEqualTo(reference2);
assertThat(Links.parse(LINKS + ",,,")).isEqualTo(reference);
assertThat(Links.parse(LINKS2 + ",,,")).isEqualTo(reference2);
}
@Test
public void returnsNullForNullOrEmptySource() {
assertThat(Links.valueOf(null)).isEqualTo(Links.NO_LINKS);
assertThat(Links.valueOf("")).isEqualTo(Links.NO_LINKS);
assertThat(Links.parse(null)).isEqualTo(Links.NONE);
assertThat(Links.parse("")).isEqualTo(Links.NONE);
}
/**
@@ -87,9 +87,9 @@ public class LinksUnitTest {
Link withComma = new Link("http://localhost:8080/test?page=0&filter=foo,bar", "foo");
assertThat(Links.valueOf(WITH_COMMA).getLink("foo")).isEqualTo(Optional.of(withComma));
assertThat(Links.parse(WITH_COMMA).getLink("foo")).isEqualTo(Optional.of(withComma));
Links twoWithCommaInFirst = Links.valueOf(WITH_COMMA.concat(",").concat(SECOND));
Links twoWithCommaInFirst = Links.parse(WITH_COMMA.concat(",").concat(SECOND));
assertThat(twoWithCommaInFirst.getLink("foo")).hasValue(withComma);
assertThat(twoWithCommaInFirst.getLink("bar")).hasValue(new Link("/somethingElse", "bar"));
@@ -100,14 +100,14 @@ public class LinksUnitTest {
*/
@Test
public void parsesLinksWithWhitespace() {
assertThat(Links.valueOf(WITH_WHITESPACE)).isEqualTo(reference);
assertThat(Links.parse(WITH_WHITESPACE)).isEqualTo(reference);
}
@Test // #805
public void returnsRequiredLink() {
Link reference = new Link("http://localhost", "someRel");
Links links = new Links(reference);
Links links = Links.of(reference);
assertThat(links.getRequiredLink("someRel")).isEqualTo(reference);
}
@@ -115,10 +115,24 @@ public class LinksUnitTest {
@Test // #805
public void rejectsMissingLinkWithIllegalArgumentException() {
Links links = new Links();
Links links = Links.of();
assertThatExceptionOfType(IllegalArgumentException.class) //
.isThrownBy(() -> links.getRequiredLink("self")) //
.withMessageContaining("self");
}
@Test
public void detectsContainedLinks() {
Link first = new Link("http://localhost", "someRel");
Link second = new Link("http://localhost", "someOtherRel");
assertThat(Links.of(first).contains(first)).isTrue();
assertThat(Links.of(first).contains(second)).isFalse();
assertThat(Links.of(first).containsSameLinksAs(Links.of(first, second))).isFalse();
assertThat(Links.of(first, second).containsSameLinksAs(Links.of(first))).isFalse();
assertThat(Links.of(first, second).containsSameLinksAs(Links.of(first, second))).isTrue();
}
}

View File

@@ -42,7 +42,7 @@ public class PagedResourcesUnitTest {
@Test
public void discoversNextLink() {
resources.add(new Link("foo", IanaLinkRelation.NEXT.value()));
resources.add(new Link("foo", IanaLinkRelations.NEXT.value()));
assertThat(resources.getNextLink()).isNotNull();
}
@@ -50,7 +50,7 @@ public class PagedResourcesUnitTest {
@Test
public void discoversPreviousLink() {
resources.add(new Link("custom", IanaLinkRelation.PREV.value()));
resources.add(new Link("custom", IanaLinkRelations.PREV.value()));
assertThat(resources.getPreviousLink()).isNotNull();
}

View File

@@ -33,15 +33,15 @@ public class ResourceSupportUnitTest {
ResourceSupport support = new ResourceSupport();
assertThat(support.hasLinks()).isFalse();
assertThat(support.hasLink(IanaLinkRelation.SELF.value())).isFalse();
assertThat(support.hasLink(IanaLinkRelations.SELF.value())).isFalse();
assertThat(support.getLinks().isEmpty()).isTrue();
assertThat(support.getLinks(IanaLinkRelation.SELF.value()).isEmpty()).isTrue();
assertThat(support.getLinks(IanaLinkRelations.SELF.value()).isEmpty()).isTrue();
}
@Test
public void addsLinkCorrectly() {
Link link = new Link("foo", IanaLinkRelation.NEXT.value());
Link link = new Link("foo", IanaLinkRelations.NEXT.value());
ResourceSupport support = new ResourceSupport();
support.add(link);
@@ -49,7 +49,7 @@ public class ResourceSupportUnitTest {
assertThat(support.hasLinks()).isTrue();
assertThat(support.hasLink(link.getRel())).isTrue();
assertThat(support.getLink(link.getRel())).hasValue(link);
assertThat(support.getLinks(IanaLinkRelation.NEXT.value())).contains(link);
assertThat(support.getLinks(IanaLinkRelations.NEXT.value())).contains(link);
}
@Test
@@ -69,8 +69,8 @@ public class ResourceSupportUnitTest {
@Test
public void addsLinksCorrectly() {
Link first = new Link("foo", IanaLinkRelation.PREV.value());
Link second = new Link("bar", IanaLinkRelation.NEXT.value());
Link first = new Link("foo", IanaLinkRelations.PREV.value());
Link second = new Link("bar", IanaLinkRelations.NEXT.value());
ResourceSupport support = new ResourceSupport();
support.add(Arrays.asList(first, second));
@@ -79,8 +79,8 @@ public class ResourceSupportUnitTest {
assertThat(support.hasLinks()).isTrue();
assertThat(support.getLinks()).contains(first, second);
assertThat(support.getLinks()).hasSize(2);
assertThat(support.getLinks(IanaLinkRelation.PREV.value())).contains(first);
assertThat(support.getLinks(IanaLinkRelation.NEXT.value())).contains(second);
assertThat(support.getLinks(IanaLinkRelations.PREV.value())).contains(first);
assertThat(support.getLinks(IanaLinkRelations.NEXT.value())).contains(second);
}
@Test

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.hateoas;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Unit tests for {@link StringLinkRelation}.
*
* @author Oliver Gierke
*/
public class StringLinkRelationUnitTests {
@Test
public void serializesAsPlainString() throws Exception {
Sample sample = new Sample();
sample.relation = StringLinkRelation.of("foo");
ObjectMapper mapper = new ObjectMapper();
assertThat(mapper.writeValueAsString(sample)).isEqualTo("{\"relation\":\"foo\"}");
}
@Test
public void deserializesUsingFactoryMethod() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Sample result = mapper.readValue("{\"relation\":\"foo\"}", Sample.class);
assertThat(result.relation).isEqualTo(StringLinkRelation.of("foo"));
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
static class Sample {
StringLinkRelation relation;
}
}

View File

@@ -31,7 +31,7 @@ import org.springframework.hateoas.TemplateVariable.VariableType;
/**
* Unit tests for {@link UriTemplate}.
*
*
* @author Oliver Gierke
* @author JamesE Richardson
*/
@@ -270,26 +270,30 @@ public class UriTemplateUnitTest {
UriTemplate template = new UriTemplate("/foo{&bar,foobar*}");
assertVariables(template,
new TemplateVariable("bar", VariableType.REQUEST_PARAM_CONTINUED),
new TemplateVariable("foobar", VariableType.COMPOSITE_PARAM));
assertVariables(template, new TemplateVariable("bar", VariableType.REQUEST_PARAM_CONTINUED),
new TemplateVariable("foobar", VariableType.COMPOSITE_PARAM));
}
/**
* @see #483
*/
@Test
@SuppressWarnings("serial")
public void expandsCompositeValueAsAssociativeArray() {
UriTemplate template = new UriTemplate("/foo{&bar,foobar*}");
String expandedTemplate = template.expand(new HashMap<String, Object>(){{
put("bar", "barExpanded");
put("foobar", new HashMap<String, String>(){{
put("city", "Clarksville");
put("state", "TN");
}});
}}).toString();
String expandedTemplate = template.expand(new HashMap<String, Object>() {
{
put("bar", "barExpanded");
put("foobar", new HashMap<String, String>() {
{
put("city", "Clarksville");
put("state", "TN");
}
});
}
}).toString();
assertThat(expandedTemplate).isEqualTo("/foo?bar=barExpanded&city=Clarksville&state=TN");
}
@@ -298,14 +302,17 @@ public class UriTemplateUnitTest {
* @see #483
*/
@Test
@SuppressWarnings("serial")
public void expandsCompositeValueAsList() {
UriTemplate template = new UriTemplate("/foo{&bar,foobar*}");
String expandedTemplate = template.expand(new HashMap<String, Object>(){{
put("bar", "barExpanded");
put("foobar", Arrays.asList("foo1", "foo2"));
}}).toString();
String expandedTemplate = template.expand(new HashMap<String, Object>() {
{
put("bar", "barExpanded");
put("foobar", Arrays.asList("foo1", "foo2"));
}
}).toString();
assertThat(expandedTemplate).isEqualTo("/foo?bar=barExpanded&foobar=foo1&foobar=foo2");
}
@@ -314,14 +321,17 @@ public class UriTemplateUnitTest {
* @see #483
*/
@Test
@SuppressWarnings("serial")
public void handlesCompositeValueAsSingleValue() {
UriTemplate template = new UriTemplate("/foo{&bar,foobar*}");
String expandedTemplate = template.expand(new HashMap<String, Object>(){{
put("bar", "barExpanded");
put("foobar", "singleValue");
}}).toString();
String expandedTemplate = template.expand(new HashMap<String, Object>() {
{
put("bar", "barExpanded");
put("foobar", "singleValue");
}
}).toString();
assertThat(expandedTemplate).isEqualTo("/foo?bar=barExpanded&foobar=singleValue");
}

View File

@@ -73,7 +73,9 @@ public class VndErrorsMarshallingTest {
*/
@Test
public void jackson2Marshalling() throws Exception {
assertThat(jackson2Mapper.writeValueAsString(errors)).isEqualToIgnoringWhitespace(json2Reference);
assertThat(jackson2Mapper.writeValueAsString(errors)) //
.isEqualToIgnoringWhitespace(json2Reference);
}
/**

View File

@@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Optional;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
@@ -29,7 +30,7 @@ import org.springframework.util.StreamUtils;
/**
* Unit tests for {@link AlpsLinkDiscoverer}.
*
*
* @author Greg Turnquist
* @author Oliver Gierke
*/
@@ -40,10 +41,11 @@ public class AlpsLinkDiscoverUnitTest extends AbstractLinkDiscovererUnitTest {
@Test
public void discoversFullyQualifiedRel() {
Link link = getDiscoverer().findLinkWithRel("http://foo.com/bar", getInputString());
Optional<Link> link = getDiscoverer().findLinkWithRel("http://foo.com/bar", getInputString());
assertThat(link).isNotNull();
assertThat(link.getHref()).isEqualTo("fullRelHref");
assertThat(link) //
.map(Link::getHref) //
.hasValue("fullRelHref");
}
/**

View File

@@ -27,6 +27,7 @@ import java.util.UUID;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkRelation;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.RelProvider;
import org.springframework.hateoas.Resource;
@@ -43,7 +44,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Helper class for integration tests.
*
*
* @author Oliver Gierke
* @author Greg Turnquist
*/
@@ -172,10 +173,10 @@ public class Server implements Closeable {
Object content = resource.getContent();
Class<?> type = content.getClass();
String collectionRel = relProvider.getCollectionResourceRelFor(type);
String singleRel = relProvider.getItemResourceRelFor(type);
LinkRelation collectionRel = relProvider.getCollectionResourceRelFor(type);
LinkRelation singleRel = relProvider.getItemResourceRelFor(type);
String baseResourceUri = String.format("%s/%s", rootResource(), collectionRel);
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));
@@ -217,7 +218,7 @@ public class Server implements Closeable {
}
}
/*
/*
* (non-Javadoc)
* @see java.io.Closeable#close()
*/

View File

@@ -28,8 +28,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.hateoas.Link;
@@ -50,34 +51,39 @@ import org.springframework.web.client.RestTemplate;
/**
* Integration tests for {@link Traverson}.
*
*
* @author Oliver Gierke
* @author Greg Turnquist
* @since 0.11
*/
public class TraversonTest {
URI baseUri;
static URI baseUri;
static Server server;
Server server;
Traverson traverson;
@Before
public void setUp() {
@BeforeClass
public static void setUpClass() {
this.server = new Server();
this.baseUri = URI.create(this.server.rootResource());
this.traverson = new Traverson(this.baseUri, MediaTypes.HAL_JSON_UTF8, MediaTypes.HAL_JSON);
server = new Server();
baseUri = URI.create(server.rootResource());
setUpActors();
}
@After
public void tearDown() throws IOException {
@Before
public void setUp() {
if (this.server != null) {
this.server.close();
this.traverson = new Traverson(baseUri, MediaTypes.HAL_JSON_UTF8, MediaTypes.HAL_JSON);
}
@AfterClass
public static void tearDown() throws IOException {
if (server != null) {
server.close();
}
}
@@ -94,7 +100,7 @@ public class TraversonTest {
*/
@Test(expected = IllegalArgumentException.class)
public void rejectsEmptyMediaTypes() {
new Traverson(this.baseUri);
new Traverson(baseUri);
}
/**
@@ -107,8 +113,7 @@ public class TraversonTest {
verifyThatRequest() //
.havingPathEqualTo("/") //
.havingHeader("Accept", contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)) //
.receivedOnce();
.havingHeader("Accept", contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)); //
}
/**
@@ -193,7 +198,7 @@ public class TraversonTest {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Arrays.asList(interceptor));
this.traverson = new Traverson(this.baseUri, MediaTypes.HAL_JSON);
this.traverson = new Traverson(baseUri, MediaTypes.HAL_JSON);
this.traverson.setRestOperations(restTemplate);
traverson.follow("movies", "movie", "actor").<String> toObject("$.name");
@@ -206,7 +211,7 @@ public class TraversonTest {
@Test
public void usesCustomLinkDiscoverer() {
this.traverson = new Traverson(URI.create(this.server.rootResource() + "/github"), MediaType.APPLICATION_JSON);
this.traverson = new Traverson(URI.create(server.rootResource() + "/github"), MediaType.APPLICATION_JSON);
this.traverson.setLinkDiscoverers(Arrays.asList(new GitHubLinkDiscoverer()));
String value = this.traverson.follow("foo").toObject("$.key");
@@ -222,7 +227,7 @@ public class TraversonTest {
Link result = traverson.follow("movies").asLink();
assertThat(result.getHref()).endsWith("/movies");
assertThat(result.getRel()).isEqualTo("movies");
assertThat(result.hasRel("movies")).isTrue();
}
/**
@@ -231,7 +236,7 @@ public class TraversonTest {
@Test
public void returnsTemplatedLinkIfRequested() {
TraversalBuilder follow = new Traverson(URI.create(this.server.rootResource().concat("/link")), MediaTypes.HAL_JSON)
TraversalBuilder follow = new Traverson(URI.create(server.rootResource().concat("/link")), MediaTypes.HAL_JSON)
.follow("self");
Link link = follow.asTemplatedLink();
@@ -269,8 +274,7 @@ public class TraversonTest {
@Test
public void returnsDefaultMessageConverters() {
List<HttpMessageConverter<?>> converters = Traverson
.getDefaultMessageConverters(Collections.emptyList());
List<HttpMessageConverter<?>> converters = Traverson.getDefaultMessageConverters(Collections.emptyList());
assertThat(converters).hasSize(1);
assertThat(converters.get(0)).isInstanceOf(StringHttpMessageConverter.class);
@@ -310,7 +314,7 @@ public class TraversonTest {
.isEqualTo(server.rootResource() + "/springagram/items/1");
final Item item = itemResource.getContent();
assertThat(item.image).isEqualTo(this.server.rootResource() + "/springagram/file/cat");
assertThat(item.image).isEqualTo(server.rootResource() + "/springagram/file/cat");
assertThat(item.description).isEqualTo("cat");
}
@@ -320,7 +324,7 @@ public class TraversonTest {
@Test
public void allowAlteringTheDetailsOfASingleHopByMapOperations() {
this.traverson = new Traverson(URI.create(this.server.rootResource() + "/springagram"), MediaTypes.HAL_JSON);
this.traverson = new Traverson(URI.create(server.rootResource() + "/springagram"), MediaTypes.HAL_JSON);
// tag::hop-put[]
ParameterizedTypeReference<Resource<Item>> resourceParameterizedTypeReference = new ParameterizedTypeReference<Resource<Item>>() {};
@@ -335,10 +339,10 @@ public class TraversonTest {
assertThat(itemResource.hasLink("self")).isTrue();
assertThat(itemResource.getRequiredLink("self").expand().getHref())
.isEqualTo(this.server.rootResource() + "/springagram/items/1");
.isEqualTo(server.rootResource() + "/springagram/items/1");
final Item item = itemResource.getContent();
assertThat(item.image).isEqualTo(this.server.rootResource() + "/springagram/file/cat");
assertThat(item.image).isEqualTo(server.rootResource() + "/springagram/file/cat");
assertThat(item.description).isEqualTo("cat");
}
@@ -348,7 +352,7 @@ public class TraversonTest {
@Test
public void allowGlobalsToImpactSingleHops() {
this.traverson = new Traverson(URI.create(this.server.rootResource() + "/springagram"), MediaTypes.HAL_JSON);
this.traverson = new Traverson(URI.create(server.rootResource() + "/springagram"), MediaTypes.HAL_JSON);
Map<String, Object> params = new HashMap<>();
params.put("projection", "thisShouldGetOverwrittenByLocalHop");
@@ -360,10 +364,10 @@ public class TraversonTest {
assertThat(itemResource.hasLink("self")).isTrue();
assertThat(itemResource.getRequiredLink("self").expand().getHref())
.isEqualTo(this.server.rootResource() + "/springagram/items/1");
.isEqualTo(server.rootResource() + "/springagram/items/1");
final Item item = itemResource.getContent();
assertThat(item.image).isEqualTo(this.server.rootResource() + "/springagram/file/cat");
assertThat(item.image).isEqualTo(server.rootResource() + "/springagram/file/cat");
assertThat(item.description).isEqualTo("cat");
}
@@ -373,7 +377,7 @@ public class TraversonTest {
@Test
public void doesNotDoubleEncodeURI() {
this.traverson = new Traverson(URI.create(this.server.rootResource() + "/springagram"), MediaTypes.HAL_JSON);
this.traverson = new Traverson(URI.create(server.rootResource() + "/springagram"), MediaTypes.HAL_JSON);
Resource<?> itemResource = traverson.//
follow(rel("items").withParameters(Collections.singletonMap("projection", "no images"))).//
@@ -381,7 +385,7 @@ public class TraversonTest {
assertThat(itemResource.hasLink("self")).isTrue();
assertThat(itemResource.getRequiredLink("self").expand().getHref())
.isEqualTo(this.server.rootResource() + "/springagram/items");
.isEqualTo(server.rootResource() + "/springagram/items");
}
@Test
@@ -390,50 +394,40 @@ public class TraversonTest {
String customHeaderName = "X-CustomHeader";
traverson
.follow(rel("movies")
.header(customHeaderName, "alpha")
.header(HttpHeaders.LOCATION, "http://localhost:8080/my/custom/location"))
.follow(rel("movie").header(customHeaderName, "bravo"))
.follow(rel("actor").header(customHeaderName, "charlie"))
.toObject("$.name");
.follow(rel("movies").header(customHeaderName, "alpha").header(HttpHeaders.LOCATION,
"http://localhost:8080/my/custom/location"))
.follow(rel("movie").header(customHeaderName, "bravo")).follow(rel("actor").header(customHeaderName, "charlie"))
.toObject("$.name");
verifyThatRequest() //
.havingPathEqualTo("/") //
.havingHeader(HttpHeaders.ACCEPT, contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)) //
.receivedOnce();
.havingPathEqualTo("/") //
.havingHeader(HttpHeaders.ACCEPT, contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)); //
verifyThatRequest()
.havingPathEqualTo("/movies") // aggregate root movies
.havingHeader(HttpHeaders.ACCEPT, contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)) //
.havingHeader(customHeaderName, contains("alpha")) //
.havingHeader(HttpHeaders.LOCATION, contains("http://localhost:8080/my/custom/location")) //
.receivedOnce();
verifyThatRequest().havingPathEqualTo("/movies") // aggregate root movies
.havingHeader(HttpHeaders.ACCEPT, contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)) //
.havingHeader(customHeaderName, contains("alpha")) //
.havingHeader(HttpHeaders.LOCATION, contains("http://localhost:8080/my/custom/location")); //
verifyThatRequest()
.havingPath(startsWith("/movies/")) // single movie
.havingHeader(HttpHeaders.ACCEPT, contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)) //
.havingHeader(customHeaderName, contains("bravo")) //
.receivedOnce();
verifyThatRequest().havingPath(startsWith("/movies/")) // single movie
.havingHeader(HttpHeaders.ACCEPT, contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)) //
.havingHeader(customHeaderName, contains("bravo")); //
verifyThatRequest()
.havingPath(startsWith("/actors/")) // single actor
.havingHeader(HttpHeaders.ACCEPT, contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)) //
.havingHeader(customHeaderName, contains("charlie")) //
.receivedOnce();
verifyThatRequest().havingPath(startsWith("/actors/")) // single actor
.havingHeader(HttpHeaders.ACCEPT, contains(MediaTypes.HAL_JSON_UTF8_VALUE + ", " + MediaTypes.HAL_JSON_VALUE)) //
.havingHeader(customHeaderName, contains("charlie")); //
}
private void setUpActors() {
private static void setUpActors() {
Resource<Actor> actor = new Resource<>(new Actor("Keanu Reaves"));
String actorUri = this.server.mockResourceFor(actor);
String actorUri = server.mockResourceFor(actor);
Movie movie = new Movie("The Matrix");
Resource<Movie> resource = new Resource<>(movie);
resource.add(new Link(actorUri, "actor"));
this.server.mockResourceFor(resource);
this.server.finishMocking();
server.mockResourceFor(resource);
server.finishMocking();
}
static class CountingInterceptor implements ClientHttpRequestInterceptor {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,7 @@ package org.springframework.hateoas.collectionjson;
import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
@@ -31,6 +31,7 @@ import org.springframework.hateoas.support.MappingUtils;
* Unit tests for {@link CollectionJsonLinkDiscoverer}.
*
* @author Greg Turnquist
* @author Oliver Drotbohm
*/
public class CollectionJsonLinkDiscovererUnitTest {
@@ -46,10 +47,11 @@ public class CollectionJsonLinkDiscovererUnitTest {
String specBasedJson = MappingUtils.read(new ClassPathResource("spec-part1.json", getClass()));
Link link = this.discoverer.findLinkWithRel("self", specBasedJson);
Optional<Link> link = this.discoverer.findLinkWithRel("self", specBasedJson);
assertThat(link).isNotNull();
assertThat(link.getHref()).isEqualTo("http://example.org/friends/");
assertThat(link) //
.map(Link::getHref) //
.hasValue("http://example.org/friends/");
}
@Test
@@ -57,32 +59,22 @@ public class CollectionJsonLinkDiscovererUnitTest {
String specBasedJson = MappingUtils.read(new ClassPathResource("spec-part2.json", getClass()));
Link selfLink = this.discoverer.findLinkWithRel("self", specBasedJson);
assertThat(this.discoverer.findLinkWithRel("self", specBasedJson)) //
.map(Link::getHref) //
.hasValue("http://example.org/friends/");
assertThat(selfLink).isNotNull();
assertThat(selfLink.getHref()).isEqualTo("http://example.org/friends/");
assertThat(this.discoverer.findLinkWithRel("feed", specBasedJson)) //
.map(Link::getHref) //
.hasValue("http://example.org/friends/rss");
Link feedLink = this.discoverer.findLinkWithRel("feed", specBasedJson);
assertThat(this.discoverer.findLinksWithRel("blog", specBasedJson)) //
.extracting("href") //
.containsExactlyInAnyOrder("http://examples.org/blogs/jdoe", "http://examples.org/blogs/msmith",
"http://examples.org/blogs/rwilliams");
assertThat(feedLink).isNotNull();
assertThat(feedLink.getHref()).isEqualTo("http://example.org/friends/rss");
List<Link> links = this.discoverer.findLinksWithRel("blog", specBasedJson);
assertThat(links)
.extracting("href")
.containsExactlyInAnyOrder(
"http://examples.org/blogs/jdoe",
"http://examples.org/blogs/msmith",
"http://examples.org/blogs/rwilliams");
links = this.discoverer.findLinksWithRel("avatar", specBasedJson);
assertThat(links)
.extracting("href")
.containsExactlyInAnyOrder(
"http://examples.org/images/jdoe",
"http://examples.org/images/msmith",
"http://examples.org/images/rwilliams");
assertThat(this.discoverer.findLinksWithRel("avatar", specBasedJson)) //
.extracting("href") //
.containsExactlyInAnyOrder("http://examples.org/images/jdoe", "http://examples.org/images/msmith",
"http://examples.org/images/rwilliams");
}
}

View File

@@ -26,7 +26,7 @@ import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceSupport;
@@ -37,11 +37,10 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* Unit tests leveraging spec fragments of JSON.
* Unit tests leveraging spec fragments of JSON. NOTE: Fields that don't map into Java property names (e.g.
* {@literal full-name}) are altered in the JSON to work properly. Alternative is to have some sort of injectable
* converter.
*
* NOTE: Fields that don't map into Java property names (e.g. {@literal full-name}) are altered in the JSON to work properly.
* Alternative is to have some sort of injectable converter.
*
* @author Greg Turnquist
*/
public class CollectionJsonSpecTest {
@@ -53,7 +52,6 @@ public class CollectionJsonSpecTest {
mapper = new ObjectMapper();
mapper.registerModule(new Jackson2CollectionJsonModule());
mapper.setHandlerInstantiator(new Jackson2CollectionJsonModule.CollectionJsonHandlerInstantiator(null));
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
}
@@ -69,7 +67,7 @@ public class CollectionJsonSpecTest {
ResourceSupport resource = mapper.readValue(specBasedJson, ResourceSupport.class);
assertThat(resource.getLinks()).hasSize(1);
assertThat(resource.getRequiredLink(IanaLinkRelation.SELF.value())).isEqualTo(new Link("http://example.org/friends/"));
assertThat(resource.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(new Link("http://example.org/friends/"));
}
/**
@@ -78,15 +76,15 @@ public class CollectionJsonSpecTest {
*/
@Test
public void specPart2() throws IOException {
String specBasedJson = MappingUtils.read(new ClassPathResource("spec-part2.json", getClass()));
Resources<Resource<Friend>> resources = mapper.readValue(specBasedJson,
mapper.getTypeFactory().constructParametricType(Resources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, Friend.class)));
mapper.getTypeFactory().constructParametricType(Resources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, Friend.class)));
assertThat(resources.getLinks()).hasSize(2);
assertThat(resources.getRequiredLink(IanaLinkRelation.SELF.value())).isEqualTo(new Link("http://example.org/friends/"));
assertThat(resources.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(new Link("http://example.org/friends/"));
assertThat(resources.getRequiredLink("feed")).isEqualTo(new Link("http://example.org/friends/rss", "feed"));
assertThat(resources.getContent()).hasSize(3);
@@ -94,21 +92,28 @@ public 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(IanaLinkRelation.SELF.value())).isEqualTo(new Link("http://example.org/friends/jdoe"));
assertThat(friends.get(0).getRequiredLink(IanaLinkRelations.SELF))
.isEqualTo(new Link("http://example.org/friends/jdoe"));
assertThat(friends.get(0).getRequiredLink("blog")).isEqualTo(new Link("http://examples.org/blogs/jdoe", "blog"));
assertThat(friends.get(0).getRequiredLink("avatar")).isEqualTo(new Link("http://examples.org/images/jdoe", "avatar"));
assertThat(friends.get(0).getRequiredLink("avatar"))
.isEqualTo(new Link("http://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(IanaLinkRelation.SELF.value())).isEqualTo(new Link("http://example.org/friends/msmith"));
assertThat(friends.get(1).getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("http://example.org/friends/msmith"));
assertThat(friends.get(1).getRequiredLink("blog")).isEqualTo(new Link("http://examples.org/blogs/msmith", "blog"));
assertThat(friends.get(1).getRequiredLink("avatar")).isEqualTo(new Link("http://examples.org/images/msmith", "avatar"));
assertThat(friends.get(1).getRequiredLink("avatar"))
.isEqualTo(new Link("http://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(IanaLinkRelation.SELF.value())).isEqualTo(new Link("http://example.org/friends/rwilliams"));
assertThat(friends.get(2).getRequiredLink("blog")).isEqualTo(new Link("http://examples.org/blogs/rwilliams", "blog"));
assertThat(friends.get(2).getRequiredLink("avatar")).isEqualTo(new Link("http://examples.org/images/rwilliams", "avatar"));
assertThat(friends.get(2).getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("http://example.org/friends/rwilliams"));
assertThat(friends.get(2).getRequiredLink("blog"))
.isEqualTo(new Link("http://examples.org/blogs/rwilliams", "blog"));
assertThat(friends.get(2).getRequiredLink("avatar"))
.isEqualTo(new Link("http://examples.org/images/rwilliams", "avatar"));
}
/**
@@ -124,10 +129,12 @@ public class CollectionJsonSpecTest {
mapper.getTypeFactory().constructParametricType(Resource.class, Friend.class));
assertThat(resource.getLinks()).hasSize(6);
assertThat(resource.getRequiredLink(IanaLinkRelation.SELF.value())).isEqualTo(new Link("http://example.org/friends/jdoe"));
assertThat(resource.getRequiredLink(IanaLinkRelations.SELF)).isEqualTo(new Link("http://example.org/friends/jdoe"));
assertThat(resource.getRequiredLink("feed")).isEqualTo(new Link("http://example.org/friends/rss", "feed"));
assertThat(resource.getRequiredLink("queries")).isEqualTo(new Link("http://example.org/friends/?queries", "queries"));
assertThat(resource.getRequiredLink("template")).isEqualTo(new Link("http://example.org/friends/?template", "template"));
assertThat(resource.getRequiredLink("queries"))
.isEqualTo(new Link("http://example.org/friends/?queries", "queries"));
assertThat(resource.getRequiredLink("template"))
.isEqualTo(new Link("http://example.org/friends/?template", "template"));
assertThat(resource.getRequiredLink("blog")).isEqualTo(new Link("http://examples.org/blogs/jdoe", "blog"));
assertThat(resource.getRequiredLink("avatar")).isEqualTo(new Link("http://examples.org/images/jdoe", "avatar"));
@@ -145,12 +152,14 @@ public class CollectionJsonSpecTest {
String specBasedJson = MappingUtils.read(new ClassPathResource("spec-part4.json", getClass()));
Resources<Resource<Friend>> resources = mapper.readValue(specBasedJson,
mapper.getTypeFactory().constructParametricType(Resources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, Friend.class)));
mapper.getTypeFactory().constructParametricType(Resources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, Friend.class)));
assertThat(resources.getContent()).hasSize(0);
assertThat(resources.getRequiredLink(IanaLinkRelation.SELF.value())).isEqualTo(new Link("http://example.org/friends/"));
assertThat(resources.getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("http://example.org/friends/"));
}
/**
* @see http://amundsen.com/media-types/collection/examples/ - Section 5. Template Representation
* @throws IOException
@@ -161,12 +170,14 @@ public class CollectionJsonSpecTest {
String specBasedJson = MappingUtils.read(new ClassPathResource("spec-part5.json", getClass()));
Resources<Resource<Friend>> resources = mapper.readValue(specBasedJson,
mapper.getTypeFactory().constructParametricType(Resources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, Friend.class)));
mapper.getTypeFactory().constructParametricType(Resources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, Friend.class)));
assertThat(resources.getContent()).hasSize(0);
assertThat(resources.getRequiredLink(IanaLinkRelation.SELF.value())).isEqualTo(new Link("http://example.org/friends/"));
assertThat(resources.getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("http://example.org/friends/"));
}
/**
* @see http://amundsen.com/media-types/collection/examples/ - Section 6. Error Representation
* @throws IOException
@@ -177,12 +188,14 @@ public class CollectionJsonSpecTest {
String specBasedJson = MappingUtils.read(new ClassPathResource("spec-part6.json", getClass()));
Resources<Resource<Friend>> resources = mapper.readValue(specBasedJson,
mapper.getTypeFactory().constructParametricType(Resources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, Friend.class)));
mapper.getTypeFactory().constructParametricType(Resources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, Friend.class)));
assertThat(resources.getContent()).hasSize(0);
assertThat(resources.getRequiredLink(IanaLinkRelation.SELF.value())).isEqualTo(new Link("http://example.org/friends/"));
assertThat(resources.getRequiredLink(IanaLinkRelations.SELF.value()))
.isEqualTo(new Link("http://example.org/friends/"));
}
/**
* @see http://amundsen.com/media-types/collection/examples/ - Section 7. Write Representation
* @throws IOException

View File

@@ -37,7 +37,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.Resource;
@@ -166,7 +166,8 @@ public class CollectionJsonWebMvcIntegrationTest {
.andExpect(status().isCreated()) //
.andExpect(header().stringValues(HttpHeaders.LOCATION, "http://localhost/employees/2"));
this.mockMvc.perform(get("/employees/2").accept(MediaTypes.COLLECTION_JSON)).andExpect(status().isOk()) //
this.mockMvc.perform(get("/employees/2").accept(MediaTypes.COLLECTION_JSON)) //
.andExpect(status().isOk()) //
.andExpect(jsonPath("$.collection.version", is("1.0")))
.andExpect(jsonPath("$.collection.href", is("http://localhost/employees/2")))
@@ -270,12 +271,10 @@ public class CollectionJsonWebMvcIntegrationTest {
EMPLOYEES.put(newEmployeeId, employee.getContent());
try {
return ResponseEntity
.created(
new URI(findOne(newEmployeeId) //
.getLink(IanaLinkRelation.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse(""))) //
return ResponseEntity.created(new URI(findOne(newEmployeeId) //
.getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse(""))) //
.build();
} catch (URISyntaxException e) {
return ResponseEntity.badRequest().body(e.getMessage());
@@ -290,7 +289,7 @@ public class CollectionJsonWebMvcIntegrationTest {
try {
return ResponseEntity.noContent() //
.location(new URI(findOne(id) //
.getLink(IanaLinkRelation.SELF.value()) //
.getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse(""))) //
.build();
@@ -319,7 +318,7 @@ public class CollectionJsonWebMvcIntegrationTest {
try {
return ResponseEntity.noContent() //
.location(new URI(findOne(id) //
.getLink(IanaLinkRelation.SELF.value()) //
.getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse(""))) //
.build();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,7 +29,7 @@ import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.AbstractJackson2MarshallingIntegrationTest;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Links;
import org.springframework.hateoas.PagedResources;
@@ -45,19 +45,19 @@ import com.fasterxml.jackson.databind.SerializationFeature;
* Integration test for Jackson 2 JSON+Collection
*
* @author Greg Turnquist
* @author Oliver Drotbohm
*/
public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2MarshallingIntegrationTest {
static final Links PAGINATION_LINKS = new Links(
new Link("localhost", IanaLinkRelation.SELF.value()),
new Link("foo", IanaLinkRelation.NEXT.value()),
new Link("bar", IanaLinkRelation.PREV.value()));
static final Links PAGINATION_LINKS = Links.of( //
new Link("localhost", IanaLinkRelations.SELF), //
new Link("foo", IanaLinkRelations.NEXT), //
new Link("bar", IanaLinkRelations.PREV));
@Before
public void setUpModule() {
mapper.registerModule(new Jackson2CollectionJsonModule());
mapper.setHandlerInstantiator(new Jackson2CollectionJsonModule.CollectionJsonHandlerInstantiator(null));
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
}
@@ -67,7 +67,8 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
ResourceSupport resourceSupport = new ResourceSupport();
resourceSupport.add(new Link("localhost").withSelfRel());
assertThat(write(resourceSupport)).isEqualTo(MappingUtils.read(new ClassPathResource("resource-support.json", getClass())));
assertThat(write(resourceSupport))
.isEqualTo(MappingUtils.read(new ClassPathResource("resource-support.json", getClass())));
}
@Test
@@ -76,8 +77,9 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
ResourceSupport expected = new ResourceSupport();
expected.add(new Link("localhost"));
assertThat(read(MappingUtils.read(new ClassPathResource("resource-support.json", getClass())), ResourceSupport.class))
.isEqualTo(expected);
assertThat(
read(MappingUtils.read(new ClassPathResource("resource-support.json", getClass())), ResourceSupport.class))
.isEqualTo(expected);
}
@Test
@@ -87,7 +89,8 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
resourceSupport.add(new Link("localhost"));
resourceSupport.add(new Link("localhost2").withRel("orders"));
assertThat(write(resourceSupport)).isEqualTo(MappingUtils.read(new ClassPathResource("resource-support-2.json", getClass())));
assertThat(write(resourceSupport))
.isEqualTo(MappingUtils.read(new ClassPathResource("resource-support-2.json", getClass())));
}
@Test
@@ -96,7 +99,8 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
ResourceWithAttributes resource = new ResourceWithAttributes("test value");
resource.add(new Link("localhost").withSelfRel());
assertThat(write(resource)).isEqualTo(MappingUtils.read(new ClassPathResource("resource-support-3.json", getClass())));
assertThat(write(resource))
.isEqualTo(MappingUtils.read(new ClassPathResource("resource-support-3.json", getClass())));
}
@Test
@@ -105,8 +109,8 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
ResourceWithAttributes expected = new ResourceWithAttributes("test value");
expected.add(new Link("localhost").withSelfRel());
assertThat(read(MappingUtils.read(new ClassPathResource("resource-support-3.json", getClass())), ResourceWithAttributes.class))
.isEqualTo(expected);
assertThat(read(MappingUtils.read(new ClassPathResource("resource-support-3.json", getClass())),
ResourceWithAttributes.class)).isEqualTo(expected);
}
@Test
@@ -116,8 +120,10 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
expected.add(new Link("localhost"));
expected.add(new Link("localhost2").withRel("orders"));
assertThat(read(MappingUtils.read(new ClassPathResource("resource-support-2.json", getClass())), ResourceSupport.class))
.isEqualTo(expected);
String read = MappingUtils.read(new ClassPathResource("resource-support-2.json", getClass()));
ResourceSupport readResourceSupport = read(read, ResourceSupport.class);
assertThat(readResourceSupport.getLinks()).containsAll(expected.getLinks());
}
@Test
@@ -149,7 +155,6 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
assertThat(result).isEqualTo(expected);
}
@Test
public void renderResource() throws Exception {
@@ -161,11 +166,12 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
@Test
public void deserializeResource() throws Exception {
Resource expected = new Resource<>("first", new Link("localhost"));
Resource<?> expected = new Resource<>("first", new Link("localhost"));
String source = MappingUtils.read(new ClassPathResource("resource.json", getClass()));
Resource<String> actual = mapper.readValue(source, mapper.getTypeFactory().constructParametricType(Resource.class, String.class));
Resource<String> actual = mapper.readValue(source,
mapper.getTypeFactory().constructParametricType(Resource.class, String.class));
assertThat(actual).isEqualTo(expected);
}
@@ -180,7 +186,8 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
resources.add(new Link("localhost"));
resources.add(new Link("/page/2").withRel("next"));
assertThat(write(resources)).isEqualTo(MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())));
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())));
}
@Test
@@ -190,11 +197,12 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
data.add(new Resource<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new Resource<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
Resources expected = new Resources<>(data);
Resources<?> expected = new Resources<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
Resources<Resource<String>> actual = mapper.readValue(MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())),
Resources<Resource<String>> actual = mapper.readValue(
MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())),
mapper.getTypeFactory().constructParametricType(Resources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, String.class)));
@@ -213,7 +221,8 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
resources.add(new Link("localhost"));
resources.add(new Link("/page/2").withRel("next"));
assertThat(write(resources)).isEqualTo(MappingUtils.read(new ClassPathResource("resources-simple-pojos.json", getClass())));
assertThat(write(resources))
.isEqualTo(MappingUtils.read(new ClassPathResource("resources-simple-pojos.json", getClass())));
}
@Test
@@ -226,7 +235,8 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
@Test
public void deserializesPagedResource() throws Exception {
PagedResources<Resource<SimplePojo>> result = mapper.readValue(MappingUtils.read(new ClassPathResource("paged-resources.json", getClass())),
PagedResources<Resource<SimplePojo>> result = mapper.readValue(
MappingUtils.read(new ClassPathResource("paged-resources.json", getClass())),
mapper.getTypeFactory().constructParametricType(PagedResources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, SimplePojo.class)));
@@ -247,7 +257,7 @@ public class Jackson2CollectionJsonIntegrationTest extends AbstractJackson2Marsh
@NoArgsConstructor
@AllArgsConstructor
public static class ResourceWithAttributes extends ResourceSupport {
private String attribute;
}

View File

@@ -19,15 +19,14 @@ import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Links;
import org.springframework.hateoas.support.MappingUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
@@ -42,28 +41,26 @@ public class JacksonSerializationTest {
public void setUp() {
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.registerModule(new Jackson2CollectionJsonModule());
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
}
@Test
public void createSimpleCollection() throws IOException {
CollectionJson<?> collection = new CollectionJson<>()
.withVersion("1.0")
.withHref("localhost")
.withLinks(Arrays.asList(new Link("foo").withSelfRel()))
.withItems(Arrays.asList(
new CollectionJsonItem<>()
.withHref("localhost")
.withRawData("Greetings programs")
.withLinks(Arrays.asList(new Link("localhost").withSelfRel())),
new CollectionJsonItem<>()
.withHref("localhost")
.withRawData("Yo")
.withLinks(Arrays.asList(new Link("localhost/orders").withRel("orders")))));
CollectionJson<?> collection = new CollectionJson<>().withVersion("1.0").withHref("localhost")
.withLinks(Links.of(new Link("foo").withSelfRel())) //
.withItems(new CollectionJsonItem<>() //
.withHref("localhost") //
.withRawData("Greetings programs") //
.withLinks(new Link("localhost").withSelfRel()), //
new CollectionJsonItem<>() //
.withHref("localhost") //
.withRawData("Yo") //
.withLinks(new Link("localhost/orders").withRel("orders")));
String actual = mapper.writeValueAsString(collection);
assertThat(actual, is(MappingUtils.read(new ClassPathResource("reference.json", getClass()))));
}
}

View File

@@ -69,7 +69,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Integration tests for {@link EnableHypermediaSupport}.
*
*
* @author Oliver Gierke
* @author Greg Turnquist
*/
@@ -106,8 +106,10 @@ public class EnableHypermediaSupportIntegrationTest {
LinkDiscoverers discoverers = context.getBean(LinkDiscoverers.class);
assertThat(discoverers).isNotNull();
assertThat(discoverers.getLinkDiscovererFor(MediaTypes.HAL_JSON)).isInstanceOf(HalLinkDiscoverer.class);
assertThat(discoverers.getLinkDiscovererFor(MediaTypes.HAL_JSON_UTF8)).isInstanceOf(HalLinkDiscoverer.class);
assertThat(discoverers.getLinkDiscovererFor(MediaTypes.HAL_JSON))
.hasValueSatisfying(HalLinkDiscoverer.class::isInstance);
assertThat(discoverers.getLinkDiscovererFor(MediaTypes.HAL_JSON_UTF8))
.hasValueSatisfying(HalLinkDiscoverer.class::isInstance);
assertRelProvidersSetUp(context);
});
}
@@ -121,7 +123,7 @@ public class EnableHypermediaSupportIntegrationTest {
assertThat(discoverers).isNotNull();
assertThat(discoverers.getLinkDiscovererFor(MediaTypes.HAL_FORMS_JSON))
.isInstanceOf(HalFormsLinkDiscoverer.class);
.hasValueSatisfying(HalFormsLinkDiscoverer.class::isInstance);
assertRelProvidersSetUp(context);
});
}
@@ -135,7 +137,7 @@ public class EnableHypermediaSupportIntegrationTest {
assertThat(discoverers).isNotNull();
assertThat(discoverers.getLinkDiscovererFor(MediaTypes.COLLECTION_JSON))
.isInstanceOf(CollectionJsonLinkDiscoverer.class);
.hasValueSatisfying(CollectionJsonLinkDiscoverer.class::isInstance);
assertRelProvidersSetUp(context);
});
}
@@ -148,7 +150,8 @@ public class EnableHypermediaSupportIntegrationTest {
LinkDiscoverers discoverers = context.getBean(LinkDiscoverers.class);
assertThat(discoverers).isNotNull();
assertThat(discoverers.getLinkDiscovererFor(MediaTypes.UBER_JSON)).isInstanceOf(UberLinkDiscoverer.class);
assertThat(discoverers.getLinkDiscovererFor(MediaTypes.UBER_JSON))
.hasValueSatisfying(UberLinkDiscoverer.class::isInstance);
assertRelProvidersSetUp(context);
});
}
@@ -298,8 +301,8 @@ public class EnableHypermediaSupportIntegrationTest {
assertThat(converters.get(0)).isInstanceOf(TypeConstrainedMappingJackson2HttpMessageConverter.class);
assertThat(converters.get(0).getSupportedMediaTypes()) //
.hasSize(1) //
.contains(MediaTypes.UBER_JSON);
.hasSize(1) //
.contains(MediaTypes.UBER_JSON);
}
}
@@ -393,8 +396,8 @@ public class EnableHypermediaSupportIntegrationTest {
RestTemplate template = context.getBean(RestTemplate.class);
assertThat(template.getMessageConverters().get(0).getSupportedMediaTypes()) //
.hasSize(1) //
.contains(MediaTypes.UBER_JSON);
.hasSize(1) //
.contains(MediaTypes.UBER_JSON);
});
}
@@ -480,7 +483,7 @@ public class EnableHypermediaSupportIntegrationTest {
assertThatCode(() -> {
assertThat(it.writeValueAsString(resourceSupport)) //
.isEqualTo("{\"_links\":{\"self\":{\"href\":\"localhost\"}}}");
.isEqualTo("{\"_links\":{\"self\":{\"href\":\"localhost\"}}}");
}).doesNotThrowAnyException();
});
});
@@ -581,7 +584,7 @@ public class EnableHypermediaSupportIntegrationTest {
/**
* Method to mitigate API changes between Spring 3.2 and 4.0.
*
*
* @param adapter
* @return
*/

View File

@@ -19,15 +19,15 @@ import static org.assertj.core.api.Assertions.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import org.junit.Test;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkDiscoverer;
import org.springframework.hateoas.Links;
/**
* Base class for unit tests for {@link LinkDiscoverer} implementations.
*
*
* @author Oliver Gierke
*/
public abstract class AbstractLinkDiscovererUnitTest {
@@ -35,9 +35,11 @@ public abstract class AbstractLinkDiscovererUnitTest {
@Test
public void findsSingleLink() {
assertThat(getDiscoverer().findLinkWithRel("self", getInputString())).isEqualTo(new Link("selfHref"));
assertThat(getDiscoverer().findLinkWithRel("self", getInputString())) //
.hasValue(new Link("selfHref"));
Links links = getDiscoverer().findLinksWithRel("self", getInputString());
List<Link> links = getDiscoverer().findLinksWithRel("self", getInputString());
assertThat(links).hasSize(1);
assertThat(links).contains(new Link("selfHref"));
}
@@ -46,46 +48,47 @@ public abstract class AbstractLinkDiscovererUnitTest {
public void findsFirstLink() {
assertThat(getDiscoverer().findLinkWithRel("relation", getInputString()))
.isEqualTo(new Link("firstHref", "relation"));
.hasValue(new Link("firstHref", "relation"));
}
@Test
public void findsAllLinks() {
List<Link> links = getDiscoverer().findLinksWithRel("relation", getInputString());
Links links = getDiscoverer().findLinksWithRel("relation", getInputString());
assertThat(links).hasSize(2);
assertThat(links).contains(new Link("firstHref", "relation"), new Link("secondHref", "relation"));
}
@Test
public void returnsForInexistingLink() {
assertThat(getDiscoverer().findLinkWithRel("something", getInputString())).isNull();
assertThat(getDiscoverer().findLinkWithRel("something", getInputString())).isEmpty();
}
@Test
public void returnsForInexistingLinkFromInputStream() throws Exception {
InputStream inputStream = new ByteArrayInputStream(getInputString().getBytes("UTF-8"));
assertThat(getDiscoverer().findLinkWithRel("something", inputStream)).isNull();
assertThat(getDiscoverer().findLinkWithRel("something", inputStream)).isEmpty();
}
@Test
public void returnsNullForNonExistingLinkContainer() {
assertThat(getDiscoverer().findLinksWithRel("something", getInputStringWithoutLinkContainer())).isEmpty();
assertThat(getDiscoverer().findLinkWithRel("something", getInputStringWithoutLinkContainer())).isNull();
assertThat(getDiscoverer().findLinkWithRel("something", getInputStringWithoutLinkContainer())).isEmpty();
}
/**
* Return the {@link LinkDiscoverer} to be tested.
*
*
* @return
*/
protected abstract LinkDiscoverer getDiscoverer();
/**
* Return the JSON structure we expect to find the links in.
*
*
* @return
*/
protected abstract String getInputString();

View File

@@ -18,6 +18,7 @@ package org.springframework.hateoas.core;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.hateoas.LinkRelation;
import org.springframework.hateoas.RelProvider;
import org.springframework.plugin.core.OrderAwarePluginRegistry;
import org.springframework.plugin.core.PluginRegistry;
@@ -38,12 +39,12 @@ public class DelegatingRelProviderUnitTest {
RelProvider delegatingProvider = new DelegatingRelProvider(registry);
assertThat(delegatingProvider.supports(Sample.class)).isTrue();
assertThat(delegatingProvider.getItemResourceRelFor(Sample.class)).isEqualTo("foo");
assertThat(delegatingProvider.getCollectionResourceRelFor(Sample.class)).isEqualTo("bar");
assertThat(delegatingProvider.getItemResourceRelFor(Sample.class)).isEqualTo(LinkRelation.of("foo"));
assertThat(delegatingProvider.getCollectionResourceRelFor(Sample.class)).isEqualTo(LinkRelation.of("bar"));
assertThat(delegatingProvider.supports(String.class)).isTrue();
assertThat(delegatingProvider.getItemResourceRelFor(String.class)).isEqualTo("string");
assertThat(delegatingProvider.getCollectionResourceRelFor(String.class)).isEqualTo("stringList");
assertThat(delegatingProvider.getItemResourceRelFor(String.class)).isEqualTo(LinkRelation.of("string"));
assertThat(delegatingProvider.getCollectionResourceRelFor(String.class)).isEqualTo(LinkRelation.of("stringList"));
}
@Relation(value = "foo", collectionRelation = "bar")

View File

@@ -21,10 +21,11 @@ import java.util.Collection;
import java.util.Collections;
import org.junit.Test;
import org.springframework.hateoas.LinkRelation;
/**
* Unit tests for {@link EmbeddedWrappers}.
*
*
* @author Oliver Gierke
*/
public class EmbeddedWrappersUnitTest {
@@ -35,13 +36,12 @@ public class EmbeddedWrappersUnitTest {
* @see #286
*/
@Test
@SuppressWarnings("rawtypes")
public void createsWrapperForEmptyCollection() {
EmbeddedWrapper wrapper = wrappers.emptyCollectionOf(String.class);
assertEmptyCollectionValue(wrapper);
assertThat(wrapper.getRel()).isNull();
assertThat(wrapper.getRel()).isEmpty();
assertThat(wrapper.getRelTargetType()).isEqualTo(String.class);
}
@@ -51,10 +51,10 @@ public class EmbeddedWrappersUnitTest {
@Test
public void createsWrapperForEmptyCollectionAndExplicitRel() {
EmbeddedWrapper wrapper = wrappers.wrap(Collections.emptySet(), "rel");
EmbeddedWrapper wrapper = wrappers.wrap(Collections.emptySet(), LinkRelation.of("rel"));
assertEmptyCollectionValue(wrapper);
assertThat(wrapper.getRel()).isEqualTo("rel");
assertThat(wrapper.getRel()).hasValue(LinkRelation.of("rel"));
assertThat(wrapper.getRelTargetType()).isNull();
}
@@ -68,6 +68,8 @@ public class EmbeddedWrappersUnitTest {
@SuppressWarnings("unchecked")
private static void assertEmptyCollectionValue(EmbeddedWrapper wrapper) {
assertThat(wrapper.getValue()).isInstanceOfSatisfying(Collection.class, it -> assertThat(it).isEmpty());
assertThat(wrapper.getValue()) //
.isInstanceOfSatisfying(Collection.class, it -> assertThat(it).isEmpty());
}
}

View File

@@ -18,11 +18,12 @@ package org.springframework.hateoas.core;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.hateoas.LinkRelation;
import org.springframework.hateoas.RelProvider;
/**
* Unit tests for {@link EvoInflectorRelProvider}.
*
*
* @author Oliver Gierke
*/
public class EvoInflectorRelProviderUnitTest {
@@ -36,8 +37,9 @@ public class EvoInflectorRelProviderUnitTest {
}
private void assertRels(Class<?> type, String singleRel, String collectionRel) {
assertThat(provider.getItemResourceRelFor(type)).isEqualTo(singleRel);
assertThat(provider.getCollectionResourceRelFor(type)).isEqualTo(collectionRel);
assertThat(provider.getItemResourceRelFor(type)).isEqualTo(LinkRelation.of(singleRel));
assertThat(provider.getCollectionResourceRelFor(type)).isEqualTo(LinkRelation.of(collectionRel));
}
static class Person {

View File

@@ -22,7 +22,9 @@ import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkRelation;
import org.springframework.hateoas.Links;
import org.springframework.hateoas.UriTemplate;
import org.springframework.hateoas.hal.DefaultCurieProvider.Curie;
@@ -32,7 +34,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
/**
* Unit tests for {@link DefaultCurieProvider}.
*
*
* @author Oliver Gierke
* @author Greg Turnquist
*/
@@ -69,17 +71,23 @@ public class DefaultCurieProviderUnitTest {
@Test
public void doesNotPrefixIanaRels() {
assertThat(provider.getNamespacedRelFrom(new Link("http://amazon.com"))).isEqualTo("self");
assertThat(provider.getNamespacedRelFrom(new Link("http://amazon.com"))) //
.isEqualTo(HalLinkRelation.of(IanaLinkRelations.SELF));
}
@Test
public void prefixesNormalRels() {
assertThat(provider.getNamespacedRelFrom(new Link("http://amazon.com", "book"))).isEqualTo("acme:book");
assertThat(provider.getNamespacedRelFrom(new Link("http://amazon.com", "book"))) //
.isEqualTo(HalLinkRelation.curied("acme", "book"));
}
@Test
public void doesNotPrefixQualifiedRels() {
assertThat(provider.getNamespacedRelFrom(new Link("http://amazon.com", "custom:rel"))).isEqualTo("custom:rel");
assertThat(provider.getNamespacedRelFrom(new Link("http://amazon.com", "custom:rel")))
.isEqualTo(HalLinkRelation.curied("custom", "rel"));
}
/**
@@ -95,7 +103,8 @@ public class DefaultCurieProviderUnitTest {
.withType("the type") //
.withDeprecation("http://example.com/custom/deprecated");
assertThat(provider.getNamespacedRelFrom(link)).isEqualTo("custom:rel");
assertThat(provider.getNamespacedRelFrom(link)) //
.isEqualTo(HalLinkRelation.curied("custom", "rel"));
}
/**
@@ -103,7 +112,9 @@ public class DefaultCurieProviderUnitTest {
*/
@Test
public void doesNotPrefixIanaRelsForRelAsString() {
assertThat(provider.getNamespacedRelFor("self")).isEqualTo("self");
assertThat(provider.getNamespacedRelFor(IanaLinkRelations.SELF)) //
.isEqualTo(HalLinkRelation.uncuried("self"));
}
/**
@@ -111,7 +122,9 @@ public class DefaultCurieProviderUnitTest {
*/
@Test
public void prefixesNormalRelsForRelAsString() {
assertThat(provider.getNamespacedRelFor("book")).isEqualTo("acme:book");
assertThat(provider.getNamespacedRelFor(LinkRelation.of("book"))) //
.isEqualTo(HalLinkRelation.curied("acme", "book"));
}
/**
@@ -119,7 +132,9 @@ public class DefaultCurieProviderUnitTest {
*/
@Test
public void doesNotPrefixQualifiedRelsForRelAsString() {
assertThat(provider.getNamespacedRelFor("custom:rel")).isEqualTo("custom:rel");
assertThat(provider.getNamespacedRelFor(HalLinkRelation.curied("custom", "rel")))
.isEqualTo(HalLinkRelation.curied("custom", "rel"));
}
/**
@@ -130,8 +145,8 @@ public class DefaultCurieProviderUnitTest {
DefaultCurieProvider provider = new DefaultCurieProvider(getCuries());
assertThat(provider.getCurieInformation(new Links())).hasSize(2);
assertThat(provider.getNamespacedRelFor("some")).isEqualTo("some");
assertThat(provider.getCurieInformation(Links.of())).hasSize(2);
assertThat(provider.getNamespacedRelFor(LinkRelation.of("some"))).isEqualTo(HalLinkRelation.uncuried("some"));
}
/**
@@ -142,8 +157,9 @@ public class DefaultCurieProviderUnitTest {
DefaultCurieProvider provider = new DefaultCurieProvider(getCuries(), "foo");
assertThat(provider.getCurieInformation(new Links())).hasSize(2);
assertThat(provider.getNamespacedRelFor("some")).isEqualTo("foo:some");
assertThat(provider.getCurieInformation(Links.of())).hasSize(2);
assertThat(provider.getNamespacedRelFor(LinkRelation.of("some"))) //
.isEqualTo(HalLinkRelation.curied("foo", "some"));
}
/**
@@ -158,7 +174,7 @@ public class DefaultCurieProviderUnitTest {
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
Links links = new Links(new Link("http://localhost", "name:foo"));
Links links = Links.of(new Link("http://localhost", "name:foo"));
Collection<? extends Object> curies = provider.getCurieInformation(links);
assertThat(curies).hasSize(1);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,12 +17,14 @@ package org.springframework.hateoas.hal;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.hateoas.hal.HalLinkRelation.*;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.hateoas.LinkRelation;
import org.springframework.hateoas.RelProvider;
import org.springframework.hateoas.UriTemplate;
import org.springframework.hateoas.core.EmbeddedWrapper;
@@ -49,20 +51,20 @@ public class HalEmbeddedBuilderUnitTest {
@Test
public void rendersSingleElementsWithSingleEntityRel() {
Map<String, Object> map = setUpBuilder(null, "foo", 1L);
Map<HalLinkRelation, Object> map = setUpBuilder(null, "foo", 1L);
assertThat(map.get("string")).isEqualTo("foo");
assertThat(map.get("long")).isEqualTo(1L);
assertThat(map.get(uncuried("string"))).isEqualTo("foo");
assertThat(map.get(uncuried("long"))).isEqualTo(1L);
}
@Test
public void rendersMultipleElementsWithCollectionResourceRel() {
Map<String, Object> map = setUpBuilder(null, "foo", "bar", 1L);
Map<HalLinkRelation, Object> map = setUpBuilder(null, "foo", "bar", 1L);
assertThat(map.containsKey("string")).isFalse();
assertThat(map.get("long")).isEqualTo(1L);
assertHasValues(map, "strings", "foo", "bar");
assertThat(map.containsKey(uncuried("string"))).isFalse();
assertThat(map.get(uncuried("long"))).isEqualTo(1L);
assertHasValues(map, uncuried("strings"), "foo", "bar");
}
/**
@@ -71,11 +73,11 @@ public class HalEmbeddedBuilderUnitTest {
@Test
public void correctlyPilesUpResourcesInCollectionRel() {
Map<String, Object> map = setUpBuilder(null, "foo", "bar", "foobar", 1L);
Map<HalLinkRelation, Object> map = setUpBuilder(null, "foo", "bar", "foobar", 1L);
assertThat(map.containsKey("string")).isFalse();
assertHasValues(map, "strings", "foo", "bar", "foobar");
assertThat(map.get("long")).isEqualTo(1L);
assertThat(map.containsKey(uncuried("string"))).isFalse();
assertHasValues(map, uncuried("strings"), "foo", "bar", "foobar");
assertThat(map.get(uncuried("long"))).isEqualTo(1L);
}
/**
@@ -87,8 +89,8 @@ public class HalEmbeddedBuilderUnitTest {
HalEmbeddedBuilder builder = new HalEmbeddedBuilder(provider, null, true);
builder.add("Sample");
assertThat(builder.asMap().get("string")).isNull();
assertHasValues(builder.asMap(), "strings", "Sample");
assertThat(builder.asMap().get(uncuried("string"))).isNull();
assertHasValues(builder.asMap(), uncuried("strings"), "Sample");
}
/**
@@ -100,9 +102,9 @@ public class HalEmbeddedBuilderUnitTest {
EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
HalEmbeddedBuilder builder = new HalEmbeddedBuilder(provider, null, true);
builder.add(wrappers.wrap("MyValue", "foo"));
builder.add(wrappers.wrap("MyValue", LinkRelation.of("foo")));
assertThat(builder.asMap().get("foo")).isInstanceOf(String.class);
assertThat(builder.asMap().get(uncuried("foo"))).isInstanceOf(String.class);
}
/**
@@ -119,10 +121,10 @@ public class HalEmbeddedBuilderUnitTest {
@Test
public void rendersSingleElementsWithSingleEntityRelWithCurieProvider() {
Map<String, Object> map = setUpBuilder(curieProvider, "foo", 1L);
Map<HalLinkRelation, Object> map = setUpBuilder(curieProvider, "foo", 1L);
assertThat(map.get("curie:string")).isEqualTo("foo");
assertThat(map.get("curie:long")).isEqualTo(1L);
assertThat(map.get(curied("curie", "string"))).isEqualTo("foo");
assertThat(map.get(curied("curie", "long"))).isEqualTo(1L);
}
/**
@@ -131,11 +133,11 @@ public class HalEmbeddedBuilderUnitTest {
@Test
public void rendersMultipleElementsWithCollectionResourceRelWithCurieProvider() {
Map<String, Object> map = setUpBuilder(curieProvider, "foo", "bar", 1L);
Map<HalLinkRelation, Object> map = setUpBuilder(curieProvider, "foo", "bar", 1L);
assertThat(map.containsKey("curie:string")).isFalse();
assertThat(map.get("curie:long")).isEqualTo(1L);
assertHasValues(map, "curie:strings", "foo", "bar");
assertThat(map.containsKey(curied("curie", "string"))).isFalse();
assertThat(map.get(curied("curie", "long"))).isEqualTo(1L);
assertHasValues(map, curied("curie", "strings"), "foo", "bar");
}
/**
@@ -144,11 +146,11 @@ public class HalEmbeddedBuilderUnitTest {
@Test
public void correctlyPilesUpResourcesInCollectionRelWithCurieprovider() {
Map<String, Object> map = setUpBuilder(curieProvider, "foo", "bar", "foobar", 1L);
Map<HalLinkRelation, Object> map = setUpBuilder(curieProvider, "foo", "bar", "foobar", 1L);
assertThat(map.containsKey("curie:string")).isFalse();
assertHasValues(map, "curie:strings", "foo", "bar", "foobar");
assertThat(map.get("curie:long")).isEqualTo(1L);
assertThat(map.containsKey(curied("curie", "string"))).isFalse();
assertHasValues(map, curied("curie", "strings"), "foo", "bar", "foobar");
assertThat(map.get(curied("curie", "long"))).isEqualTo(1L);
}
/**
@@ -160,8 +162,8 @@ public class HalEmbeddedBuilderUnitTest {
HalEmbeddedBuilder builder = new HalEmbeddedBuilder(provider, curieProvider, true);
builder.add("Sample");
assertThat(builder.asMap().get("curie:string")).isNull();
assertHasValues(builder.asMap(), "curie:strings", "Sample");
assertThat(builder.asMap().get(curied("curie", "string"))).isNull();
assertHasValues(builder.asMap(), curied("curie", "strings"), "Sample");
}
/**
@@ -173,7 +175,7 @@ public class HalEmbeddedBuilderUnitTest {
}
@SuppressWarnings("unchecked")
private static void assertHasValues(Map<String, Object> source, String rel, Object... values) {
private static void assertHasValues(Map<HalLinkRelation, Object> source, HalLinkRelation rel, Object... values) {
Object value = source.get(rel);
@@ -183,7 +185,7 @@ public class HalEmbeddedBuilderUnitTest {
});
}
private Map<String, Object> setUpBuilder(CurieProvider curieProvider, Object... values) {
private Map<HalLinkRelation, Object> setUpBuilder(CurieProvider curieProvider, Object... values) {
HalEmbeddedBuilder builder = new HalEmbeddedBuilder(provider, curieProvider, false);

View File

@@ -16,22 +16,21 @@
package org.springframework.hateoas.hal;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.hateoas.support.MappingUtils.read;
import static org.springframework.hateoas.support.MappingUtils.*;
import java.io.IOException;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkDiscoverer;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.core.AbstractLinkDiscovererUnitTest;
import org.springframework.hateoas.support.MappingUtils;
/**
* Unit tests for {@link HalLinkDiscoverer}.
*
*
* @author Oliver Gierke
* @author Greg Turnquist
*/
@@ -45,10 +44,9 @@ public class HalLinkDiscovererUnitTest extends AbstractLinkDiscovererUnitTest {
@Test
public void discoversFullyQualifiedRel() {
Link link = getDiscoverer().findLinkWithRel("http://foo.com/bar", getInputString());
assertThat(link).isNotNull();
assertThat(link.getHref()).isEqualTo("fullRelHref");
assertThat(getDiscoverer().findLinkWithRel("http://foo.com/bar", getInputString())) //
.map(Link::getHref) //
.hasValue("fullRelHref");
}
/**
@@ -59,19 +57,18 @@ public class HalLinkDiscovererUnitTest extends AbstractLinkDiscovererUnitTest {
String linkText = read(new ClassPathResource("hal-link.json", getClass()));
Link actual = getDiscoverer().findLinkWithRel(IanaLinkRelation.SELF.value(), linkText);
Link expected = Link.valueOf("</customer/1>;" //
+ "rel=\"self\";" //
+ "hreflang=\"en\";" //
+ "media=\"pdf\";" //
+ "title=\"pdf customer copy\";" //
+ "type=\"portable document\";" //
+ "deprecation=\"http://example.com/customers/deprecated\";" //
+ "profile=\"my-profile\"" //
+ "name=\"my-name\"");
assertThat(actual).isEqualTo(expected);
+ "rel=\"self\";" //
+ "hreflang=\"en\";" //
+ "media=\"pdf\";" //
+ "title=\"pdf customer copy\";" //
+ "type=\"portable document\";" //
+ "deprecation=\"http://example.com/customers/deprecated\";" //
+ "profile=\"my-profile\"" //
+ "name=\"my-name\"");
assertThat(getDiscoverer().findLinkWithRel(IanaLinkRelations.SELF.value(), linkText)) //
.hasValue(expected);
}
/**

View File

@@ -32,7 +32,7 @@ import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.context.support.StaticMessageSource;
import org.springframework.hateoas.AbstractJackson2MarshallingIntegrationTest;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Links;
import org.springframework.hateoas.PagedResources;
@@ -70,7 +70,7 @@ public class Jackson2HalIntegrationTest extends AbstractJackson2MarshallingInteg
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 = new Links(new Link("foo", IanaLinkRelation.NEXT.value()), new Link("bar", IanaLinkRelation.PREV.value()));
static final Links PAGINATION_LINKS = Links.of(new Link("foo", IanaLinkRelations.NEXT.value()), new Link("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\"}]}}";

View File

@@ -15,22 +15,21 @@
*/
package org.springframework.hateoas.hal.forms;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.hateoas.support.MappingUtils.read;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.hateoas.support.MappingUtils.*;
import java.io.IOException;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkDiscoverer;
import org.springframework.hateoas.core.AbstractLinkDiscovererUnitTest;
/**
* Unit tests for {@link HalFormsLinkDiscoverer}.
*
*
* @author Greg Turnquist
*/
public class HalFormsLinkDiscovererUnitTest extends AbstractLinkDiscovererUnitTest {
@@ -53,19 +52,18 @@ public class HalFormsLinkDiscovererUnitTest extends AbstractLinkDiscovererUnitTe
String linkText = read(new ClassPathResource("hal-forms-link.json", getClass()));
Link actual = getDiscoverer().findLinkWithRel(IanaLinkRelation.SELF.value(), linkText);
Link expected = Link.valueOf("</customer/1>;" //
+ "rel=\"self\";" //
+ "hreflang=\"en\";" //
+ "media=\"pdf\";" //
+ "title=\"pdf customer copy\";" //
+ "type=\"portable document\";" //
+ "deprecation=\"http://example.com/customers/deprecated\";" //
+ "profile=\"my-profile\"" //
+ "name=\"my-name\"");
+ "rel=\"self\";" //
+ "hreflang=\"en\";" //
+ "media=\"pdf\";" //
+ "title=\"pdf customer copy\";" //
+ "type=\"portable document\";" //
+ "deprecation=\"http://example.com/customers/deprecated\";" //
+ "profile=\"my-profile\"" //
+ "name=\"my-name\"");
assertThat(actual).isEqualTo(expected);
assertThat(getDiscoverer().findLinkWithRel(IanaLinkRelations.SELF, linkText)) //
.hasValue(expected);
}
@Override

View File

@@ -15,10 +15,11 @@
*/
package org.springframework.hateoas.hal.forms;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.*;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -83,9 +84,8 @@ public class HalFormsMessageConverterUnitTest {
HalFormsDocument<?> halFormsDocument = (HalFormsDocument<?>) convertedMessage;
assertThat(halFormsDocument.getLinks().size(), is(2));
assertThat(halFormsDocument.getLinks().get(0).getHref(), is("/employees"));
assertThat(halFormsDocument.getLinks().get(1).getHref(), is("/employees/1"));
assertThat(halFormsDocument.getLinks()).hasSize(2);
assertThat(halFormsDocument.getLinks()).extracting(Link::getHref).containsExactly("/employees", "/employees/1");
assertThat(halFormsDocument.getTemplates().size(), is(1));
assertThat(halFormsDocument.getTemplates().keySet(), hasItems("default"));

View File

@@ -35,7 +35,7 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.Resource;
@@ -156,7 +156,7 @@ public class HalFormsValidationIntegrationTest {
EMPLOYEES.put(newEmployeeId, employee);
try {
return ResponseEntity.noContent().location(new URI(findOne(newEmployeeId).getLink(IanaLinkRelation.SELF.value())
return ResponseEntity.noContent().location(new URI(findOne(newEmployeeId).getLink(IanaLinkRelations.SELF.value())
.map(link -> link.expand().getHref()).orElse(""))).build();
} catch (URISyntaxException e) {
return ResponseEntity.badRequest().body(e.getMessage());
@@ -172,7 +172,7 @@ public class HalFormsValidationIntegrationTest {
return ResponseEntity //
.noContent() //
.location( //
new URI(findOne(id).getLink(IanaLinkRelation.SELF.value()) //
new URI(findOne(id).getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse("")) //
).build();
@@ -201,7 +201,7 @@ public class HalFormsValidationIntegrationTest {
.noContent() //
.location( //
new URI(findOne(id) //
.getLink(IanaLinkRelation.SELF.value()) //
.getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse(""))) //
.build();

View File

@@ -36,7 +36,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.Resource;
@@ -233,7 +233,7 @@ public class HalFormsWebMvcIntegrationTest {
private URI toUri(Integer id) throws URISyntaxException {
String uri = findOne(id).getLink(IanaLinkRelation.SELF.value()) //
String uri = findOne(id).getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse("");

View File

@@ -33,7 +33,7 @@ import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.context.support.StaticMessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.AbstractJackson2MarshallingIntegrationTest;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Links;
import org.springframework.hateoas.PagedResources;
@@ -59,9 +59,9 @@ import com.fasterxml.jackson.databind.SerializationFeature;
*/
public class Jackson2HalFormsIntegrationTest extends AbstractJackson2MarshallingIntegrationTest {
static final Links PAGINATION_LINKS = new Links( //
new Link("foo", IanaLinkRelation.NEXT.value()), //
new Link("bar", IanaLinkRelation.PREV.value()) //
static final Links PAGINATION_LINKS = Links.of( //
new Link("foo", IanaLinkRelations.NEXT), //
new Link("bar", IanaLinkRelations.PREV) //
);
@Before

View File

@@ -29,7 +29,7 @@ import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.TestUtils;
import org.springframework.hateoas.mvc.ControllerLinkBuilderUnitTest.ControllerWithMethods;
@@ -45,7 +45,7 @@ import org.springframework.web.util.UriComponentsBuilder;
/**
* Unit tests for {@link ControllerLinkBuilderFactory}.
*
*
* @author Ricardo Gladwell
* @author Oliver Gierke
* @author Kamill Sokol
@@ -61,7 +61,7 @@ public class ControllerLinkBuilderFactoryUnitTest extends TestUtils {
Link link = factory.linkTo(PersonControllerImpl.class).withSelfRel();
assertPointsToMockServer(link);
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/people");
}
@@ -71,7 +71,7 @@ public class ControllerLinkBuilderFactoryUnitTest extends TestUtils {
Link link = factory.linkTo(PersonsAddressesController.class, 15).withSelfRel();
assertPointsToMockServer(link);
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/people/15/addresses");
}
@@ -109,7 +109,7 @@ public class ControllerLinkBuilderFactoryUnitTest extends TestUtils {
public void linksToMethodWithPathVariableContainingBlank() {
Link link = linkTo(methodOn(ControllerWithMethods.class).methodWithPathVariable("with blank")).withSelfRel();
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/something/with%20blank/foo");
}
@@ -122,7 +122,7 @@ public class ControllerLinkBuilderFactoryUnitTest extends TestUtils {
Link link = factory.linkTo(PersonsAddressesController.class, "with blank").withSelfRel();
assertPointsToMockServer(link);
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/people/with%20blank/addresses");
}
@@ -139,7 +139,7 @@ public class ControllerLinkBuilderFactoryUnitTest extends TestUtils {
Link link = factory.linkTo(methodOn(SampleController.class).sampleMethodWithMap(queryParams)).withSelfRel();
assertPointsToMockServer(link);
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/sample/mapsupport?firstKey=firstValue&secondKey=secondValue");
}
@@ -156,7 +156,7 @@ public class ControllerLinkBuilderFactoryUnitTest extends TestUtils {
Link link = factory.linkTo(methodOn(SampleController.class).sampleMethodWithMap(queryParams)).withSelfRel();
assertPointsToMockServer(link);
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()) //
.endsWith("/sample/multivaluemapsupport?key1=value1a&key1=value1b&key2=value2a&key2=value2b");
}
@@ -170,7 +170,7 @@ public class ControllerLinkBuilderFactoryUnitTest extends TestUtils {
Link link = factory.linkTo(PersonsAddressesController.class, Collections.singletonMap("id", "17")).withSelfRel();
assertPointsToMockServer(link);
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/people/17/addresses");
}

View File

@@ -20,19 +20,16 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import javax.servlet.ServletException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Identifiable;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.TemplateVariable;
@@ -49,7 +46,7 @@ import org.springframework.web.util.UriComponentsBuilder;
/**
* Unit tests for {@link ControllerLinkBuilder}.
*
*
* @author Oliver Gierke
* @author Dietrich Schulten
* @author Kamill Sokol
@@ -67,7 +64,7 @@ public class ControllerLinkBuilderUnitTest extends TestUtils {
public void createsLinkToControllerRoot() {
Link link = linkTo(PersonControllerImpl.class).withSelfRel();
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/people");
}
@@ -75,7 +72,8 @@ public class ControllerLinkBuilderUnitTest extends TestUtils {
public void createsLinkToParameterizedControllerRoot() {
Link link = linkTo(PersonsAddressesController.class, 15).withSelfRel();
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/people/15/addresses");
}
@@ -86,7 +84,7 @@ public class ControllerLinkBuilderUnitTest extends TestUtils {
public void createsLinkToMethodOnParameterizedControllerRoot() {
Link link = linkTo(methodOn(PersonsAddressesController.class, 15).getAddressesForCountry("DE")).withSelfRel();
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/people/15/addresses/DE");
}
@@ -94,15 +92,16 @@ public class ControllerLinkBuilderUnitTest extends TestUtils {
public void createsLinkToSubResource() {
Link link = linkTo(PersonControllerImpl.class).slash("something").withSelfRel();
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/people/something");
}
@Test
public void createsLinkWithCustomRel() {
Link link = linkTo(PersonControllerImpl.class).withRel(IanaLinkRelation.NEXT.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.NEXT.value());
Link link = linkTo(PersonControllerImpl.class).withRel(IanaLinkRelations.NEXT);
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.NEXT);
assertThat(link.getHref()).endsWith("/people");
}
@@ -400,7 +399,8 @@ public class ControllerLinkBuilderUnitTest extends TestUtils {
public void linksToMethodWithPathVariableContainingBlank() {
Link link = linkTo(methodOn(ControllerWithMethods.class).methodWithPathVariable("with blank")).withSelfRel();
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/something/with%20blank/foo");
}
@@ -410,7 +410,10 @@ public class ControllerLinkBuilderUnitTest extends TestUtils {
@Test
public void usesRootMappingOfTargetClassForMethodsOfParentClass() {
Link link = linkTo(methodOn(ChildControllerWithRootMapping.class).someEmptyMappedMethod()).withSelfRel();
Link link = linkTo(methodOn(ChildControllerWithRootMapping.class) //
.someEmptyMappedMethod()) //
.withSelfRel();
assertThat(link.getHref()).endsWith("/root");
}
@@ -496,7 +499,7 @@ public class ControllerLinkBuilderUnitTest extends TestUtils {
Link link = linkTo(methodOn(ControllerWithMethods.class).methodWithRequestParam("Spring#\n")).withSelfRel();
assertThat(link.getRel()).isEqualTo(IanaLinkRelation.SELF.value());
assertThat(link.getRel()).isEqualTo(IanaLinkRelations.SELF);
assertThat(link.getHref()).endsWith("/something/foo?id=Spring%23%0A");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014 the original author or authors.
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,9 +21,10 @@ import org.junit.Test;
/**
* Unit tests for {@link ForwardedHeader}.
*
*
* @author Oliver Gierke
*/
@SuppressWarnings("deprecation")
public class ForwardedHeaderUnitTest {
/**

View File

@@ -24,7 +24,7 @@ import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Identifiable;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkBuilder;
@@ -57,7 +57,7 @@ public class IdentifiableResourceAssemblerSupportUnitTest extends TestUtils {
public void createsInstanceWithSelfLinkToController() {
PersonResource resource = assembler.createResource(person);
Link link = resource.getRequiredLink(IanaLinkRelation.SELF.value());
Link link = resource.getRequiredLink(IanaLinkRelations.SELF.value());
assertThat(link).isNotNull();
assertThat(resource.getLinks()).hasSize(1);

View File

@@ -37,7 +37,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.Resource;
@@ -549,7 +549,7 @@ public class MultiMediaTypeWebMvcIntegrationTest {
private URI toUri(Integer id) throws URISyntaxException {
String uri = findOne(id) //
.getLink(IanaLinkRelation.SELF.value()) //
.getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse("");

View File

@@ -1,88 +0,0 @@
/*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.hateoas.mvc;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
import org.junit.Test;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.hateoas.AffordanceModel;
import org.springframework.hateoas.AffordanceModelFactory;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.QueryParameter;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.plugin.core.OrderAwarePluginRegistry;
import org.springframework.plugin.core.PluginRegistry;
/**
* @author Greg Turnquist
* @author Oliver Gierke
*/
public class SpringMvcAffordanceBuilderUnitTest {
@Test
public void favorsCustomLinkDiscovererOverDefault() {
AffordanceModelFactory low = new LowPriorityModelFactory();
AffordanceModelFactory high = new HighPriorityModelFactory();
PluginRegistry<AffordanceModelFactory, MediaType> registry = OrderAwarePluginRegistry.of(low, high);
assertThat(registry.getPluginFor(MediaType.APPLICATION_JSON).get()).isEqualTo(high);
}
static class LowPriorityModelFactory implements AffordanceModelFactory, Ordered {
@Override
public int getOrder() {
return 20;
}
@Override
public AffordanceModel getAffordanceModel(String name, Link link, HttpMethod httpMethod, ResolvableType inputType,
List<QueryParameter> queryMethodParameters, ResolvableType outputType) {
return null;
}
@Override
public boolean supports(MediaType delimiter) {
return true;
}
}
static class HighPriorityModelFactory implements AffordanceModelFactory, Ordered {
@Override
public int getOrder() {
return 10;
}
@Override
public AffordanceModel getAffordanceModel(String name, Link link, HttpMethod httpMethod, ResolvableType inputType,
List<QueryParameter> queryMethodParameters, ResolvableType outputType) {
return null;
}
@Override
public boolean supports(MediaType delimiter) {
return true;
}
}
}

View File

@@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.io.IOException;
@@ -30,7 +31,7 @@ import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.AbstractJackson2MarshallingIntegrationTest;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Links;
import org.springframework.hateoas.PagedResources;
@@ -38,7 +39,6 @@ import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.support.MappingUtils;
import org.springframework.hateoas.uber.Jackson2UberModule.UberHandlerInstantiator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializationFeature;
@@ -49,17 +49,16 @@ import com.fasterxml.jackson.databind.SerializationFeature;
*/
public class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingIntegrationTest {
static final Links PAGINATION_LINKS = new Links( //
new Link("localhost", IanaLinkRelation.SELF.value()), //
new Link("foo", IanaLinkRelation.NEXT.value()), //
new Link("bar", IanaLinkRelation.PREV.value())//
static final Links PAGINATION_LINKS = Links.of( //
new Link("localhost", IanaLinkRelations.SELF), //
new Link("foo", IanaLinkRelations.NEXT), //
new Link("bar", IanaLinkRelations.PREV) //
);
@Before
public void setUpModule() {
this.mapper.registerModule(new Jackson2UberModule());
this.mapper.setHandlerInstantiator(new UberHandlerInstantiator());
this.mapper.enable(SerializationFeature.INDENT_OUTPUT);
}
@@ -233,7 +232,7 @@ public class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingInte
JavaType resourceStringType = mapper.getTypeFactory().constructParametricType(Resource.class, String.class);
Resource expected = new Resource<>("first", new Link("localhost"));
Resource<?> expected = new Resource<>("first", new Link("localhost"));
Resource<String> actual = mapper.readValue(MappingUtils.read(new ClassPathResource("resource.json", getClass())),
resourceStringType);
@@ -289,7 +288,7 @@ public class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingInte
data.add(new Resource<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new Resource<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
Resources expected = new Resources<>(data);
Resources<?> expected = new Resources<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
@@ -311,7 +310,7 @@ public class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingInte
data.add(new Resource<>("", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new Resource<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
Resources expected = new Resources<>(data);
Resources<?> expected = new Resources<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
@@ -333,12 +332,12 @@ public class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingInte
data.add(new Resource<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new Resource<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
Resources source = new Resources<>(data);
Resources<?> source = new Resources<>(data);
source.add(new Link("localhost"));
source.add(new Link("/page/2").withRel("next"));
assertThat(write(source))
.isEqualTo(MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())));
.isEqualTo(MappingUtils.read(new ClassPathResource("resources-with-resource-objects.json", getClass())));
}
/**
@@ -351,7 +350,7 @@ public class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingInte
data.add(new Resource<>("first", new Link("localhost"), new Link("orders").withRel("orders")));
data.add(new Resource<>("second", new Link("remotehost"), new Link("order").withRel("orders")));
Resources expected = new Resources<>(data);
Resources<?> expected = new Resources<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
@@ -375,7 +374,7 @@ public class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingInte
data.add("first");
data.add("second");
Resources expected = new Resources<>(data);
Resources<?> expected = new Resources<>(data);
expected.add(new Link("localhost"));
expected.add(new Link("/page/2").withRel("next"));
@@ -515,7 +514,7 @@ public class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingInte
mapper.getTypeFactory().constructParametricType(PagedResources.class,
mapper.getTypeFactory().constructParametricType(Resource.class, Employee.class)));
assertThat(result).isEqualTo(setupAnnotatedPagedResources(0,0));
assertThat(result).isEqualTo(setupAnnotatedPagedResources(0, 0));
}
/**
@@ -566,6 +565,7 @@ public class Jackson2UberIntegrationTest extends AbstractJackson2MarshallingInte
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
static class EmployeeResource extends ResourceSupport {
private String name;

View File

@@ -38,7 +38,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.IanaLinkRelation;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.Resource;
@@ -344,7 +344,7 @@ public class UberWebMvcIntegrationTest {
try {
return ResponseEntity.created( //
new URI(findOne(newEmployeeId) //
.getLink(IanaLinkRelation.SELF.value()) //
.getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse("") //
) //
@@ -364,7 +364,7 @@ public class UberWebMvcIntegrationTest {
.noContent() //
.location( //
new URI(findOne(id) //
.getLink(IanaLinkRelation.SELF.value()) //
.getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse("") //
) //
@@ -396,7 +396,7 @@ public class UberWebMvcIntegrationTest {
.noContent() //
.location( //
new URI(findOne(id) //
.getLink(IanaLinkRelation.SELF.value()) //
.getLink(IanaLinkRelations.SELF.value()) //
.map(link -> link.expand().getHref()) //
.orElse("") //
) //

View File

@@ -50,13 +50,13 @@ class AffordanceBuilderDslUnitTest : TestUtils() {
fun `creates link to controller method with affordances`() {
val id = "15"
val self = linkTo<CustomerController> { findById(id) } withRel IanaLinkRelation.SELF.value()
val self = linkTo<CustomerController> { findById(id) } withRel IanaLinkRelations.SELF
val selfWithAffordances = self andAffordances {
afford<CustomerController> { update(id, CustomerDTO("John Doe")) }
afford<CustomerController> { delete(id) }
}
assertThat(selfWithAffordances.rel).isEqualTo(IanaLinkRelation.SELF.value())
assertThat(selfWithAffordances.rel).isEqualTo(IanaLinkRelations.SELF)
assertThat(selfWithAffordances.href).isEqualTo("http://localhost/customers/15")
assertThat(selfWithAffordances.affordances).hasSize(3)

View File

@@ -36,10 +36,10 @@ class LinkBuilderDslUnitTest : TestUtils() {
@Test
fun `creates link to controller method`() {
val self = linkTo<CustomerController> { findById("15") } withRel IanaLinkRelation.SELF.value()
val self = linkTo<CustomerController> { findById("15") } withRel IanaLinkRelations.SELF
assertPointsToMockServer(self)
assertThat(self.rel).isEqualTo(IanaLinkRelation.SELF.value())
assertThat(self.rel).isEqualTo(IanaLinkRelations.SELF)
assertThat(self.href).endsWith("/customers/15")
}
@@ -52,12 +52,12 @@ class LinkBuilderDslUnitTest : TestUtils() {
val customer = Resource(Customer("15", "John Doe"))
customer.add(CustomerController::class) {
linkTo { findById(it.content.id) } withRel IanaLinkRelation.SELF.value()
linkTo { findById(it.content.id) } withRel IanaLinkRelations.SELF
linkTo { findProductsById(it.content.id) } withRel REL_PRODUCTS
}
customer.links.forEach { assertPointsToMockServer(it) }
assertThat(customer.hasLink(IanaLinkRelation.SELF.value())).isTrue()
assertThat(customer.hasLink(IanaLinkRelations.SELF)).isTrue()
assertThat(customer.hasLink(REL_PRODUCTS)).isTrue()
}
@@ -70,12 +70,12 @@ class LinkBuilderDslUnitTest : TestUtils() {
val customer = CustomerResource("15", "John Doe")
customer.add(CustomerController::class) {
linkTo { findById(it.id) } withRel IanaLinkRelation.SELF.value()
linkTo { findById(it.id) } withRel IanaLinkRelations.SELF
linkTo { findProductsById(it.id) } withRel REL_PRODUCTS
}
customer.links.forEach { assertPointsToMockServer(it) }
assertThat(customer.hasLink(IanaLinkRelation.SELF.value())).isTrue()
assertThat(customer.hasLink(IanaLinkRelations.SELF)).isTrue()
assertThat(customer.hasLink(REL_PRODUCTS)).isTrue()
}

View File

@@ -1,20 +0,0 @@
{
"collection" : {
"version" : "1.0",
"href" : "localhost",
"links" : [ {
"rel" : "self",
"href" : "localhost"
} ],
"items" : [ {
"href" : null,
"data" : [ "first" ],
"links" : null
} ],
"template" : {
"data" : [
"firstName" :
]
}
}
}