Initial commit.

This commit is contained in:
Oliver Gierke
2012-05-10 20:25:31 +02:00
commit 21b1a4ec8c
16 changed files with 1472 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2012 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 java.io.Serializable;
/**
* Interface to mark objects that are identifiable by an ID of any type.
*
* @author Oliver Gierke
*/
public interface Identifiable<ID extends Serializable> {
/**
* Returns the id identifying the object.
*
* @return the identifier or {@literal null} if not available.
*/
ID getId();
}

View File

@@ -0,0 +1,138 @@
/*
* Copyright 2012 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 java.io.Serializable;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import org.springframework.util.Assert;
/**
* Value object for links.
*
* @author Oliver Gierke
*/
@XmlType(name = "link", namespace = Link.ATOM_NAMESPACE)
public class Link implements Serializable {
private static final long serialVersionUID = -9037755944661782121L;
public static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
public static final String REL_SELF = "self";
public static final String REL_FIRST = "first";
public static final String REL_PREVIOUS = "previous";
public static final String REL_NEXT = "next";
public static final String REL_LAST = "last";
@XmlAttribute
private String rel;
@XmlAttribute
private String href;
/**
* Creates a new link to the given URI with the self rel.
*
* @see #REL_SELF
* @param href must not be {@literal null} or empty.
*/
public Link(String href) {
this(href, REL_SELF);
}
/**
* Creates a new {@link Link} to the given URI with the given rel.
*
* @param href must not be {@literal null} or empty.
* @param rel must not be {@literal null} or empty.
*/
public Link(String href, String rel) {
Assert.hasText(href, "Href must not be null or empty!");
Assert.hasText(rel, "Rel must not be null or empty!");
this.href = href;
this.rel = rel;
}
/**
* Empty constructor required by the marshalling framework.
*/
protected Link() {
}
/**
* Returns the actual URI the link is pointing to.
*
* @return
*/
public String getHref() {
return href;
}
/**
* Returns the rel of the link.
*
* @return
*/
public String getRel() {
return rel;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Link)) {
return false;
}
Link that = (Link) obj;
return this.href.equals(that.href) && this.rel.equals(that.rel);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int result = 17;
result += 31 * href.hashCode();
result += 31 * rel.hashCode();
return result;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("{ rel : %s, href : %s }", rel, href);
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2012 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;
/**
* Interface for components that convert a domain type into an {@link ResourceSupport}.
*
* @author Oliver Gierke
*/
public interface ResourceAssembler<T, D extends ResourceSupport> {
/**
* Converts the given entity into an {@link ResourceSupport}.
*
* @param entity
* @return
*/
D toResource(T entity);
}

View File

@@ -0,0 +1,130 @@
/*
* Copyright 2012 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 java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import org.springframework.util.Assert;
/**
* Base class for DTOs to collect links.
*
* @author Oliver Gierke
*/
public class ResourceSupport implements Identifiable<Link> {
@XmlElement(name = "link", namespace = Link.ATOM_NAMESPACE)
private List<Link> links;
public ResourceSupport() {
this.links = new ArrayList<Link>();
}
/**
* Returns the {@link Link} with a rel of {@link Link#REL_SELF}.
*/
public Link getId() {
return getLink(Link.REL_SELF);
}
/**
* Adds the given link to the resource.
*
* @param link
*/
public void add(Link link) {
Assert.notNull(link, "Link must not be null!");
this.links.add(link);
}
public void add(Iterable<Link> links) {
Assert.notNull(links, "Given links must not be null!");
for (Link candidate : links) {
add(candidate);
}
}
public boolean hasLinks() {
return !this.links.isEmpty();
}
public boolean hasLink(String rel) {
return getLink(rel) != null;
}
public List<Link> getLinks() {
return Collections.unmodifiableList(links);
}
/**
* Returns the link with the given rel.
*
* @param rel
* @return the link with the given rel or {@literal null} if none found.
*/
public Link getLink(String rel) {
for (Link link : links) {
if (link.getRel().equals(rel)) {
return link;
}
}
return null;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!obj.getClass().equals(this.getClass())) {
return false;
}
ResourceSupport that = (ResourceSupport) obj;
return this.links.equals(that.links);
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.links.hashCode();
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.links.toString();
}
}

View File

@@ -0,0 +1,136 @@
/*
* Copyright 2012 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 java.net.URI;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.hateoas.Identifiable;
import org.springframework.hateoas.Link;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriTemplate;
/**
* Builder to ease building {@link Link} instances pointing to Spring MVC controllers.
*
* @author Oliver Gierke
*/
public class ControllerLinkBuilder {
private final UriComponents builder;
/**
* Creates a new {@link ControllerLinkBuilder}.
*
* @param builder must not be {@literal null}.
*/
private ControllerLinkBuilder(UriComponentsBuilder builder) {
Assert.notNull(builder);
this.builder = builder.build();
}
/**
* Creates a new {@link ControllerLinkBuilder} with a base of the mapping annotated to the given controller class.
*
* @param controller
* @return
*/
public static ControllerLinkBuilder linkTo(Class<?> controller) {
return linkTo(controller, new Object[0]);
}
public static ControllerLinkBuilder linkTo(Class<?> controller, Object... parameters) {
RequestMapping annotation = controller.getAnnotation(RequestMapping.class);
String[] mapping = annotation == null ? new String[0] : (String[]) AnnotationUtils.getValue(annotation);
if (mapping.length > 1) {
throw new IllegalStateException("Multiple controller mappings defined! Unable to build URI!");
}
ControllerLinkBuilder builder = new ControllerLinkBuilder(ServletUriComponentsBuilder.fromCurrentServletMapping());
if (mapping.length == 0) {
return builder;
}
UriTemplate template = new UriTemplate(mapping[0]);
return builder.slash(template.expand(parameters));
}
/**
* Adds the given object's {@link String} representation as sub-resource to the current URI.
*
* @param object
* @return
*/
public ControllerLinkBuilder slash(Object object) {
if (object == null) {
return this;
}
String[] segments = StringUtils.tokenizeToStringArray(object.toString(), "/");
return new ControllerLinkBuilder(UriComponentsBuilder.fromUri(builder.toUri()).pathSegment(segments));
}
/**
* Adds the given {@link AbstractEntity}'s id as sub-resource. Will simply return the current builder if the given
* entity is {@literal null}.
*
* @param identifyable
* @return
*/
public ControllerLinkBuilder slash(Identifiable<?> identifyable) {
if (identifyable == null) {
return this;
}
return slash(identifyable.getId());
}
/**
* Returns a URI resulting from the builder.
*
* @return
*/
public URI toUri() {
return builder.encode().toUri();
}
public Link withRel(String rel) {
return new Link(this.toString(), rel);
}
public Link withSelfRel() {
return new Link(this.toString());
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return toUri().normalize().toASCIIString();
}
}

View File

@@ -0,0 +1,157 @@
/*
* Copyright 2012 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 coimport javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema;
eed 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.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.hateoas.Identifiable;
import org.springframework.hateoas.ResourceAssembler;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.util.Assert;
/**
* Base class to implement {@link ResourceAssembler}s. Will automate {@link ResourceSupport} instance creation and make
* sure a self-link is always added.
*
* @author Oliver Gierke
*/
public abstract class ResourceAssemblerSupport<T extends Identifiable<?>, D extends ResourceSupport> implements
ResourceAssembler<T, D> {
public static class EntityId {
private final Object id;
public EntityId(Object id) {
Assert.notNull(id);
this.id = id;
}
public static EntityId id(Object object) {
return new EntityId(object);
}
@Override
public String toString() {
return this.id.toString();
}
}
private final Class<?> controllerClass;
private final Class<D> resourceType;
/**
* Creates a new {@link ResourceAssemblerSupport} using the given controller class and resource type.
*
* @param controllerClass must not be {@literal null}.
* @param resourceType must not be {@literal null}.
*/
public ResourceAssemblerSupport(Class<?> controllerClass, Class<D> resourceType) {
Assert.notNull(controllerClass);
Assert.notNull(resourceType);
this.controllerClass = controllerClass;
this.resourceType = resourceType;
}
/**
* Converts all given entities into resources.
*
* @see #toResource(Object)
* @param entities
* @return
*/
public List<D> toResources(Iterable<? extends T> entities) {
List<D> result = new ArrayList<D>();
for (T entity : entities) {
result.add(toResource(entity));
}
return result;
}
/**
* Creates a new resource and adds a self link to it consisting using the {@link Identifiable}'s id.
*
* @param entity must not be {@literal null}.
* @return
*/
protected D createResource(T entity) {
return createResource(entity, new Object[0]);
}
protected D createResource(T entity, Object... parameters) {
return createResource(entity, EntityId.id(entity.getId()), parameters);
}
/**
* Creates a new resource with a self link to the given id.
*
* @param entity
* @param id
* @return
*/
protected D createResource(T entity, EntityId id) {
return createResource(entity, id, new Object[0]);
}
protected D createResource(T entity, EntityId id, Object... parameters) {
Assert.notNull(entity);
Assert.notNull(id);
D instance = instantiateResource(entity);
instance.add(linkTo(controllerClass, unwrapIdentifyables(parameters)).slash(id).withSelfRel());
return instance;
}
/**
* Extracts the ids of the given values in case they're {@link Identifiable}s. Returns all other objects as they are.
*
* @param values must not be {@literal null}.
* @return
*/
private Object[] unwrapIdentifyables(Object[] values) {
List<Object> result = new ArrayList<Object>(values.length);
for (Object element : Arrays.asList(values)) {
result.add((element instanceof Identifiable) ? ((Identifiable<?>) element).getId() : element);
}
return result.toArray();
}
/**
* Instantiates the resource object. Default implementation will assume a no-arg constructor and use reflection but
* can be overridden to manually set up the object instance initially (e.g. to improve performance if this becomes an
* issue).
*
* @param entity
* @return
*/
protected D instantiateResource(T entity) {
return BeanUtils.instantiateClass(resourceType);
}
}

View File

@@ -0,0 +1,6 @@
/**
* Spring MVC helper classes to build {@link org.springframework.hateoas.Link}s and assemble
* {@link org.springframework.hateoas.ResourceSupport} types.
*/
package org.springframework.hateoas.mvc;

View File

@@ -0,0 +1,9 @@
/**
* Value objects to ease creating {@link org.springframework.hateoas.Link}s and link driven representations for REST webservices.
*/
@XmlSchema(xmlns = { @XmlNs(prefix = "atom", namespaceURI = org.springframework.hateoas.Link.ATOM_NAMESPACE) }, elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.springframework.hateoas;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema;

View File

@@ -0,0 +1,94 @@
/*
* Copyright 2012 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.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Unit tests for {@link Link}.
*
* @author Oliver Gierke
*/
public class LinkUnitTest {
@Test
public void linkWithHrefOnlyBecomesSelfLink() {
Link link = new Link("foo");
assertThat(link.getRel(), is(Link.REL_SELF));
}
@Test
public void createsLinkFromRelAndHref() {
Link link = new Link("foo", Link.REL_SELF);
assertThat(link.getHref(), is("foo"));
assertThat(link.getRel(), is(Link.REL_SELF));
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullHref() {
new Link(null);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullRel() {
new Link("foo", null);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsEmptyHref() {
new Link("");
}
@Test(expected = IllegalArgumentException.class)
public void rejectsEmptyRel() {
new Link("foo", "");
}
@Test
public void sameRelAndHrefMakeSameLink() {
Link left = new Link("foo", Link.REL_SELF);
Link right = new Link("foo", Link.REL_SELF);
TestUtils.assertEqualAndSameHashCode(left, right);
}
@Test
public void differentRelMakesDifferentLink() {
Link left = new Link("foo", Link.REL_PREVIOUS);
Link right = new Link("foo", Link.REL_NEXT);
TestUtils.assertNotEqualAndDifferentHashCode(left, right);
}
@Test
public void differentHrefMakesDifferentLink() {
Link left = new Link("foo", Link.REL_SELF);
Link right = new Link("bar", Link.REL_SELF);
TestUtils.assertNotEqualAndDifferentHashCode(left, right);
}
@Test
public void differentTypeDoesNotEqual() {
assertThat(new Link("foo"), is(not((Object) new ResourceSupport())));
}
}

View File

@@ -0,0 +1,137 @@
/*
* Copyright 2012 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.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
/**
* Unit tests for {@link ResourceSupport}.
*
* @author Oliver Gierke
*/
public class ResourceSupportUnitTest {
@Test
public void setsUpWithEmptyLinkList() {
ResourceSupport support = new ResourceSupport();
assertThat(support.hasLinks(), is(false));
assertThat(support.hasLink(Link.REL_SELF), is(false));
assertThat(support.getLinks().isEmpty(), is(true));
}
@Test
public void addsLinkCorrectly() {
Link link = new Link("foo", Link.REL_NEXT);
ResourceSupport support = new ResourceSupport();
support.add(link);
assertThat(support.getId(), is(nullValue()));
assertThat(support.hasLinks(), is(true));
assertThat(support.hasLink(link.getRel()), is(true));
assertThat(support.getLink(link.getRel()), is(link));
}
@Test
public void addsLinksCorrectly() {
Link first = new Link("foo", Link.REL_PREVIOUS);
Link second = new Link("bar", Link.REL_NEXT);
ResourceSupport support = new ResourceSupport();
support.add(Arrays.asList(first, second));
assertThat(support.getId(), is(nullValue()));
assertThat(support.hasLinks(), is(true));
assertThat(support.getLinks(), hasItems(first, second));
assertThat(support.getLinks().size(), is(2));
}
@Test
public void selfLinkBecomesId() {
Link link = new Link("foo");
ResourceSupport support = new ResourceSupport();
support.add(link);
assertThat(support.getId(), is(link));
}
@Test(expected = IllegalArgumentException.class)
public void preventsNullLinkBeingAdded() {
ResourceSupport support = new ResourceSupport();
support.add((Link) null);
}
@Test(expected = IllegalArgumentException.class)
public void preventsNullLinksBeingAdded() {
ResourceSupport support = new ResourceSupport();
support.add((Iterable<Link>) null);
}
@Test
public void sameLinkListMeansSameResource() {
ResourceSupport first = new ResourceSupport();
ResourceSupport second = new ResourceSupport();
TestUtils.assertEqualAndSameHashCode(first, second);
Link link = new Link("foo");
first.add(link);
second.add(link);
TestUtils.assertEqualAndSameHashCode(first, second);
}
@Test
public void differentLinkListsNotEqual() {
ResourceSupport first = new ResourceSupport();
ResourceSupport second = new ResourceSupport();
second.add(new Link("foo"));
TestUtils.assertNotEqualAndDifferentHashCode(first, second);
}
@Test
public void subclassNotEquals() {
ResourceSupport left = new ResourceSupport();
ResourceSupport right = new ResourceSupport() {
@Override
public int hashCode() {
return super.hashCode() + 1;
}
@Override
public String toString() {
return super.toString() + "1";
}
};
TestUtils.assertNotEqualAndDifferentHashCode(left, right);
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2012 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.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import javax.servlet.http.HttpServletRequest;
import org.junit.Before;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
*
* @author Oliver Gierke
*/
public class TestUtils {
@Before
public void setUp() {
HttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
}
public static void assertEqualAndSameHashCode(Object left, Object right) {
assertThat(left, is(right));
assertThat(right, is(left));
assertThat(left, is(left));
assertThat(left.hashCode(), is(right.hashCode()));
assertThat(left.toString(), is(right.toString()));
}
public static void assertNotEqualAndDifferentHashCode(Object left, Object right) {
assertThat(left, is(not(right)));
assertThat(right, is(not(left)));
assertThat(left.hashCode(), is(not(right.hashCode())));
assertThat(left.toString(), is(not(right.toString())));
}
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright 2012 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.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.hateoas.Identifiable;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.TestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @author Oliver Gierke
*/
public class ControllerLinkBuilderUnitTest extends TestUtils {
@Test
public void createsLinkToControllerRoot() {
Link link = linkTo(PersonController.class).withSelfRel();
assertThat(link.getRel(), is(Link.REL_SELF));
assertThat(link.getHref(), Matchers.endsWith("/people"));
}
@Test
public void createsLinkToParameterizedControllerRoot() {
Link link = linkTo(PersonsAddressesController.class, 15).withSelfRel();
assertThat(link.getRel(), is(Link.REL_SELF));
assertThat(link.getHref(), Matchers.endsWith("/people/15/addresses"));
}
@Test
public void createsLinkToSubResource() {
Link link = linkTo(PersonController.class).slash("something").withSelfRel();
assertThat(link.getRel(), is(Link.REL_SELF));
assertThat(link.getHref(), Matchers.endsWith("/people/something"));
}
@Test
public void createsLinkWithCustomRel() {
Link link = linkTo(PersonController.class).withRel(Link.REL_NEXT);
assertThat(link.getRel(), is(Link.REL_NEXT));
assertThat(link.getHref(), Matchers.endsWith("/people"));
}
@Test(expected = IllegalStateException.class)
public void rejectsControllerWithMultipleMappings() {
linkTo(InvalidController.class);
}
@Test
public void createsLinkToUnmappedController() {
linkTo(UnmappedController.class);
}
@Test
@SuppressWarnings("unchecked")
public void usesIdOfIdentifyableForPathSegment() {
Identifiable<Long> identifyable = mock(Identifiable.class);
when(identifyable.getId()).thenReturn(10L);
Link link = linkTo(PersonController.class).slash(identifyable).withSelfRel();
assertThat(link.getHref(), Matchers.endsWith("/people/10"));
}
@Test
public void appendingNullIsANoOp() {
Link link = linkTo(PersonController.class).slash(null).withSelfRel();
assertThat(link.getHref(), Matchers.endsWith("/people"));
link = linkTo(PersonController.class).slash((Object) null).withSelfRel();
assertThat(link.getHref(), Matchers.endsWith("/people"));
}
class Person implements Identifiable<Long> {
Long id;
@Override
public Long getId() {
return id;
}
}
@RequestMapping("/people")
class PersonController {
}
@RequestMapping("/people/{id}/addresses")
class PersonsAddressesController {
}
@RequestMapping({ "/persons", "/people" })
class InvalidController {
}
class UnmappedController {
}
}

View File

@@ -0,0 +1,141 @@
/*
* Copyright 2012 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.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import static org.springframework.hateoas.mvc.ResourceAssemblerSupport.EntityId.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.hateoas.Identifiable;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.hateoas.TestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @author Oliver Gierke
*/
public class ResourceAssemblerSupportUnitTest extends TestUtils {
PersonResourceAssembler assembler = new PersonResourceAssembler();
Person person;
@Override
@Before
public void setUp() {
super.setUp();
this.person = new Person();
this.person.id = 10L;
this.person.alternateId = "id";
}
@Test
public void createsInstanceWithSelfLinkToController() {
PersonResource resource = assembler.createResource(person);
Link link = resource.getLink(Link.REL_SELF);
assertThat(link, is(notNullValue()));
assertThat(resource.getLinks().size(), is(1));
}
@Test
public void usesAlternateIdIfGivenExplicitly() {
PersonResource resource = assembler.createResource(person, id(person.alternateId));
Link selfLink = resource.getId();
assertThat(selfLink.getHref(), endsWith("/people/id"));
}
@Test
public void unwrapsIdentifyablesForParameters() {
PersonResource resource = new PersonResourceAssembler(ParameterizedController.class).createResource(person, person,
"bar");
Link selfLink = resource.getId();
assertThat(selfLink.getHref(), endsWith("/people/10/bar/addresses/10"));
}
@Test
public void convertsEntitiesToResources() {
Person first = new Person();
first.id = 1L;
Person second = new Person();
second.id = 2L;
List<PersonResource> result = assembler.toResources(Arrays.asList(first, second));
ControllerLinkBuilder builder = linkTo(PersonController.class);
PersonResource firstResource = new PersonResource();
firstResource.add(builder.slash(1L).withSelfRel());
PersonResource secondResource = new PersonResource();
secondResource.add(builder.slash(1L).withSelfRel());
assertThat(result.size(), is(2));
assertThat(result, hasItems(firstResource, secondResource));
}
@RequestMapping("/people")
static class PersonController {
}
@RequestMapping("/people/{id}/{foo}/addresses")
static class ParameterizedController {
}
static class Person implements Identifiable<Long> {
Long id;
String alternateId;
@Override
public Long getId() {
return id;
}
}
static class PersonResource extends ResourceSupport {
}
class PersonResourceAssembler extends ResourceAssemblerSupport<Person, PersonResource> {
public PersonResourceAssembler() {
this(PersonController.class);
}
public PersonResourceAssembler(Class<?> controllerType) {
super(controllerType, PersonResource.class);
}
@Override
public PersonResource toResource(Person entity) {
return createResource(entity);
}
}
}