diff --git a/src/main/java/org/springframework/hateoas/Link.java b/src/main/java/org/springframework/hateoas/Link.java index 88b59725..fd18bd20 100755 --- a/src/main/java/org/springframework/hateoas/Link.java +++ b/src/main/java/org/springframework/hateoas/Link.java @@ -1,449 +1,449 @@ -/* - * Copyright 2012-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 lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.experimental.Wither; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.springframework.core.ResolvableType; -import org.springframework.http.HttpMethod; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; - -/** - * Value object for links. - * - * @author Oliver Gierke - * @author Greg Turnquist - * @author Jens Schauder - */ -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(value = "templated", ignoreUnknown = true) -@AllArgsConstructor(access = AccessLevel.PACKAGE) -@Getter -@EqualsAndHashCode(of = { "rel", "href", "hreflang", "media", "title", "deprecation", "affordances" }) -public class Link implements Serializable { - - private static final long serialVersionUID = -9037755944661782121L; - private static final String URI_PATTERN = "(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; - - private static final Pattern URI_AND_ATTRIBUTES_PATTERN = Pattern.compile("<(.*)>;(.*)"); - private static final Pattern KEY_AND_VALUE_PATTERN = Pattern - .compile("(\\w+)=\"(\\p{Lower}[\\p{Lower}\\p{Digit}\\.\\-\\s]*|" + URI_PATTERN + ")\""); - - public static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom"; - - /** - * @deprecated Use {@link IanaLinkRelation#SELF} instead. - */ - @Deprecated - public static final String REL_SELF = IanaLinkRelation.SELF.value(); - - /** - * @deprecated Use {@link IanaLinkRelation#FIRST} instead. - */ - @Deprecated - public static final String REL_FIRST = IanaLinkRelation.FIRST.value(); - - /** - * @deprecated Use {@link IanaLinkRelation#PREV} instead. - */ - @Deprecated - public static final String REL_PREVIOUS = IanaLinkRelation.PREV.value(); - - /** - * @deprecated Use {@link IanaLinkRelation#NEXT} instead. - */ - @Deprecated - public static final String REL_NEXT = IanaLinkRelation.NEXT.value(); - - /** - * @deprecated Use {@link IanaLinkRelation#LAST} instead. - */ - @Deprecated - public static final String REL_LAST = IanaLinkRelation.LAST.value(); - - private @Wither String rel; - private @Wither String href; - private @Wither String hreflang; - private @Wither String media; - private @Wither String title; - private @Wither String type; - private @Wither String deprecation; - private @Wither String profile; - private @JsonIgnore UriTemplate template; - private @JsonIgnore List affordances; - - /** - * 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) { - this(new UriTemplate(href), rel); - } - - /** - * Creates a new Link from the given {@link UriTemplate} and rel. - * - * @param template must not be {@literal null}. - * @param rel must not be {@literal null} or empty. - */ - public Link(UriTemplate template, String rel) { - - Assert.notNull(template, "UriTemplate must not be null!"); - Assert.hasText(rel, "Rel must not be null or empty!"); - - this.template = template; - this.href = template.toString(); - this.rel = rel; - this.affordances = new ArrayList(); - } - - public Link(String href, String rel, List affordances) { - - this(href, rel); - - Assert.notNull(affordances, "affordances must not be null!"); - - this.affordances = affordances; - } - - /** - * Empty constructor required by the marshalling framework. - */ - protected Link() { - this.affordances = new ArrayList(); - } - - /** - * Returns safe copy of {@link Affordance}s. - * - * @return - */ - public List getAffordances() { - return Collections.unmodifiableList(this.affordances); - } - - /** - * Returns a {@link Link} pointing to the same URI but with the {@code self} relation. - * - * @return - */ - public Link withSelfRel() { - return withRel(Link.REL_SELF); - } - - /** - * Create new {@link Link} with an additional {@link Affordance}. - * - * @param affordance must not be {@literal null}. - * @return - */ - public Link andAffordance(Affordance affordance) { - - Assert.notNull(affordance, "Affordance must not be null!"); - - List newAffordances = new ArrayList(); - newAffordances.addAll(this.affordances); - newAffordances.add(affordance); - - return withAffordances(newAffordances); - } - - /** - * Convenience method when chaining an existing {@link Link}. - * - * @param name - * @param httpMethod - * @param inputType - * @param queryMethodParameters - * @param outputType - * @return - */ - public Link andAffordance(String name, HttpMethod httpMethod, ResolvableType inputType, List queryMethodParameters, ResolvableType outputType) { - return andAffordance(new Affordance(name, this, httpMethod, inputType, queryMethodParameters, outputType)); - } - - /** - * Convenience method when chaining an existing {@link Link}. Defaults the name of the affordance to verb + classname, e.g. - * {@literal } produces {@literal }. - * - * @param httpMethod - * @param inputType - * @param queryMethodParameters - * @param outputType - * @return - */ - public Link andAffordance(HttpMethod httpMethod, ResolvableType inputType, List queryMethodParameters, ResolvableType outputType) { - return andAffordance(httpMethod.toString().toLowerCase() + inputType.resolve().getSimpleName(), httpMethod, inputType, queryMethodParameters, outputType); - } - - /** - * Convenience method when chaining an existing {@link Link}. Defaults the name of the affordance to verb + classname, e.g. - * {@literal } produces {@literal }. - * - * @param httpMethod - * @param inputType - * @param queryMethodParameters - * @param outputType - * @return - */ - public Link andAffordance(HttpMethod httpMethod, Class inputType, List queryMethodParameters, Class outputType) { - return andAffordance(httpMethod, ResolvableType.forClass(inputType), queryMethodParameters, ResolvableType.forClass(outputType)); - } - - /** - * Create new {@link Link} with additional {@link Affordance}s. - * - * @param affordances must not be {@literal null}. - * @return - */ - public Link andAffordances(List affordances) { - - List newAffordances = new ArrayList(); - newAffordances.addAll(this.affordances); - newAffordances.addAll(affordances); - - return withAffordances(newAffordances); - } - - /** - * Creats a new {@link Link} with the given {@link Affordance}s. - * - * @param affordances must not be {@literal null}. - * @return - */ - public Link withAffordances(List affordances) { - - return new Link(this.rel, this.href, this.hreflang, this.media, this.title, this.type, this.deprecation, - this.profile, this.template, affordances); - } - - /** - * Returns the variable names contained in the template. - * - * @return - */ - @JsonIgnore - public List getVariableNames() { - return getUriTemplate().getVariableNames(); - } - - /** - * Returns all {@link TemplateVariables} contained in the {@link Link}. - * - * @return - */ - @JsonIgnore - public List getVariables() { - return getUriTemplate().getVariables(); - } - - /** - * Returns whether or not the link is templated. - * - * @return - */ - public boolean isTemplated() { - return !getUriTemplate().getVariables().isEmpty(); - } - - /** - * Turns the current template into a {@link Link} by expanding it using the given parameters. - * - * @param arguments - * @return - */ - public Link expand(Object... arguments) { - return new Link(getUriTemplate().expand(arguments).toString(), getRel()); - } - - /** - * Turns the current template into a {@link Link} by expanding it using the given parameters. - * - * @param arguments must not be {@literal null}. - * @return - */ - public Link expand(Map arguments) { - return new Link(getUriTemplate().expand(arguments).toString(), getRel()); - } - - /** - * Returns whether the current {@link Link} has the given link relation. - * - * @param rel must not be {@literal null} or empty. - * @return - */ - public boolean hasRel(String rel) { - - Assert.hasText(rel, "Link relation must not be null or empty!"); - - return this.rel.equals(rel); - } - - private UriTemplate getUriTemplate() { - - if (template == null) { - this.template = new UriTemplate(href); - } - - return template; - } - - /* - * (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - - String linkString = String.format("<%s>;rel=\"%s\"", href, rel); - - if (hreflang != null) { - linkString += ";hreflang=\"" + hreflang + "\""; - } - - if (media != null) { - linkString += ";media=\"" + media + "\""; - } - - if (title != null) { - linkString += ";title=\"" + title + "\""; - } - - if (type != null) { - linkString += ";type=\"" + type + "\""; - } - - if (deprecation != null) { - linkString += ";deprecation=\"" + deprecation + "\""; - } - - if (profile != null) { - linkString += ";profile=\"" + profile + "\""; - } - - return linkString; - } - - /** - * Factory method to easily create {@link Link} instances from RFC-5988 compatible {@link String} representations of a - * link. Will return {@literal null} if input {@link String} is either empty or {@literal null}. - * - * @param element an RFC-5899 compatible representation of a link. - * @throws IllegalArgumentException if a non-empty {@link String} was given that does not adhere to RFC-5899. - * @throws IllegalArgumentException if no {@code rel} attribute could be found. - * @return - */ - public static Link valueOf(String element) { - - if (!StringUtils.hasText(element)) { - return null; - } - - Matcher matcher = URI_AND_ATTRIBUTES_PATTERN.matcher(element); - - if (matcher.find()) { - - Map attributes = getAttributeMap(matcher.group(2)); - - if (!attributes.containsKey("rel")) { - throw new IllegalArgumentException("Link does not provide a rel attribute!"); - } - - Link link = new Link(matcher.group(1), attributes.get("rel")); - - if (attributes.containsKey("hreflang")) { - link = link.withHreflang(attributes.get("hreflang")); - } - - if (attributes.containsKey("media")) { - link = link.withMedia(attributes.get("media")); - } - - if (attributes.containsKey("title")) { - link = link.withTitle(attributes.get("title")); - } - - if (attributes.containsKey("type")) { - link = link.withType(attributes.get("type")); - } - - if (attributes.containsKey("deprecation")) { - link = link.withDeprecation(attributes.get("deprecation")); - } - - if (attributes.containsKey("profile")) { - link = link.withProfile(attributes.get("profile")); - } - - return link; - - } else { - throw new IllegalArgumentException(String.format("Given link header %s is not RFC5988 compliant!", element)); - } - } - - /** - * Parses the links attributes from the given source {@link String}. - * - * @param source - * @return - */ - private static Map getAttributeMap(String source) { - - if (!StringUtils.hasText(source)) { - return Collections.emptyMap(); - } - - Map attributes = new HashMap(); - Matcher matcher = KEY_AND_VALUE_PATTERN.matcher(source); - - while (matcher.find()) { - attributes.put(matcher.group(1), matcher.group(2)); - } - - return attributes; - } -} +/* + * Copyright 2012-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 lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.experimental.Wither; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.springframework.core.ResolvableType; +import org.springframework.http.HttpMethod; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; + +/** + * Value object for links. + * + * @author Oliver Gierke + * @author Greg Turnquist + * @author Jens Schauder + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(value = "templated", ignoreUnknown = true) +@AllArgsConstructor(access = AccessLevel.PACKAGE) +@Getter +@EqualsAndHashCode(of = { "rel", "href", "hreflang", "media", "title", "deprecation", "affordances" }) +public class Link implements Serializable { + + private static final long serialVersionUID = -9037755944661782121L; + private static final String URI_PATTERN = "(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; + + private static final Pattern URI_AND_ATTRIBUTES_PATTERN = Pattern.compile("<(.*)>;(.*)"); + private static final Pattern KEY_AND_VALUE_PATTERN = Pattern + .compile("(\\w+)=\"(\\p{Lower}[\\p{Lower}\\p{Digit}\\.\\-\\s]*|" + URI_PATTERN + ")\""); + + public static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom"; + + /** + * @deprecated Use {@link IanaLinkRelation#SELF} instead. + */ + @Deprecated + public static final String REL_SELF = IanaLinkRelation.SELF.value(); + + /** + * @deprecated Use {@link IanaLinkRelation#FIRST} instead. + */ + @Deprecated + public static final String REL_FIRST = IanaLinkRelation.FIRST.value(); + + /** + * @deprecated Use {@link IanaLinkRelation#PREV} instead. + */ + @Deprecated + public static final String REL_PREVIOUS = IanaLinkRelation.PREV.value(); + + /** + * @deprecated Use {@link IanaLinkRelation#NEXT} instead. + */ + @Deprecated + public static final String REL_NEXT = IanaLinkRelation.NEXT.value(); + + /** + * @deprecated Use {@link IanaLinkRelation#LAST} instead. + */ + @Deprecated + public static final String REL_LAST = IanaLinkRelation.LAST.value(); + + private @Wither String rel; + private @Wither String href; + private @Wither String hreflang; + private @Wither String media; + private @Wither String title; + private @Wither String type; + private @Wither String deprecation; + private @Wither String profile; + private @JsonIgnore UriTemplate template; + private @JsonIgnore List affordances; + + /** + * 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) { + this(new UriTemplate(href), rel); + } + + /** + * Creates a new Link from the given {@link UriTemplate} and rel. + * + * @param template must not be {@literal null}. + * @param rel must not be {@literal null} or empty. + */ + public Link(UriTemplate template, String rel) { + + Assert.notNull(template, "UriTemplate must not be null!"); + Assert.hasText(rel, "Rel must not be null or empty!"); + + this.template = template; + this.href = template.toString(); + this.rel = rel; + this.affordances = new ArrayList(); + } + + public Link(String href, String rel, List affordances) { + + this(href, rel); + + Assert.notNull(affordances, "affordances must not be null!"); + + this.affordances = affordances; + } + + /** + * Empty constructor required by the marshalling framework. + */ + protected Link() { + this.affordances = new ArrayList(); + } + + /** + * Returns safe copy of {@link Affordance}s. + * + * @return + */ + public List getAffordances() { + return Collections.unmodifiableList(this.affordances); + } + + /** + * Returns a {@link Link} pointing to the same URI but with the {@code self} relation. + * + * @return + */ + public Link withSelfRel() { + return withRel(Link.REL_SELF); + } + + /** + * Create new {@link Link} with an additional {@link Affordance}. + * + * @param affordance must not be {@literal null}. + * @return + */ + public Link andAffordance(Affordance affordance) { + + Assert.notNull(affordance, "Affordance must not be null!"); + + List newAffordances = new ArrayList(); + newAffordances.addAll(this.affordances); + newAffordances.add(affordance); + + return withAffordances(newAffordances); + } + + /** + * Convenience method when chaining an existing {@link Link}. + * + * @param name + * @param httpMethod + * @param inputType + * @param queryMethodParameters + * @param outputType + * @return + */ + public Link andAffordance(String name, HttpMethod httpMethod, ResolvableType inputType, List queryMethodParameters, ResolvableType outputType) { + return andAffordance(new Affordance(name, this, httpMethod, inputType, queryMethodParameters, outputType)); + } + + /** + * Convenience method when chaining an existing {@link Link}. Defaults the name of the affordance to verb + classname, e.g. + * {@literal } produces {@literal }. + * + * @param httpMethod + * @param inputType + * @param queryMethodParameters + * @param outputType + * @return + */ + public Link andAffordance(HttpMethod httpMethod, ResolvableType inputType, List queryMethodParameters, ResolvableType outputType) { + return andAffordance(httpMethod.toString().toLowerCase() + inputType.resolve().getSimpleName(), httpMethod, inputType, queryMethodParameters, outputType); + } + + /** + * Convenience method when chaining an existing {@link Link}. Defaults the name of the affordance to verb + classname, e.g. + * {@literal } produces {@literal }. + * + * @param httpMethod + * @param inputType + * @param queryMethodParameters + * @param outputType + * @return + */ + public Link andAffordance(HttpMethod httpMethod, Class inputType, List queryMethodParameters, Class outputType) { + return andAffordance(httpMethod, ResolvableType.forClass(inputType), queryMethodParameters, ResolvableType.forClass(outputType)); + } + + /** + * Create new {@link Link} with additional {@link Affordance}s. + * + * @param affordances must not be {@literal null}. + * @return + */ + public Link andAffordances(List affordances) { + + List newAffordances = new ArrayList(); + newAffordances.addAll(this.affordances); + newAffordances.addAll(affordances); + + return withAffordances(newAffordances); + } + + /** + * Creats a new {@link Link} with the given {@link Affordance}s. + * + * @param affordances must not be {@literal null}. + * @return + */ + public Link withAffordances(List affordances) { + + return new Link(this.rel, this.href, this.hreflang, this.media, this.title, this.type, this.deprecation, + this.profile, this.template, affordances); + } + + /** + * Returns the variable names contained in the template. + * + * @return + */ + @JsonIgnore + public List getVariableNames() { + return getUriTemplate().getVariableNames(); + } + + /** + * Returns all {@link TemplateVariables} contained in the {@link Link}. + * + * @return + */ + @JsonIgnore + public List getVariables() { + return getUriTemplate().getVariables(); + } + + /** + * Returns whether or not the link is templated. + * + * @return + */ + public boolean isTemplated() { + return !getUriTemplate().getVariables().isEmpty(); + } + + /** + * Turns the current template into a {@link Link} by expanding it using the given parameters. + * + * @param arguments + * @return + */ + public Link expand(Object... arguments) { + return new Link(getUriTemplate().expand(arguments).toString(), getRel()); + } + + /** + * Turns the current template into a {@link Link} by expanding it using the given parameters. + * + * @param arguments must not be {@literal null}. + * @return + */ + public Link expand(Map arguments) { + return new Link(getUriTemplate().expand(arguments).toString(), getRel()); + } + + /** + * Returns whether the current {@link Link} has the given link relation. + * + * @param rel must not be {@literal null} or empty. + * @return + */ + public boolean hasRel(String rel) { + + Assert.hasText(rel, "Link relation must not be null or empty!"); + + return this.rel.equals(rel); + } + + private UriTemplate getUriTemplate() { + + if (template == null) { + this.template = new UriTemplate(href); + } + + return template; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + String linkString = String.format("<%s>;rel=\"%s\"", href, rel); + + if (hreflang != null) { + linkString += ";hreflang=\"" + hreflang + "\""; + } + + if (media != null) { + linkString += ";media=\"" + media + "\""; + } + + if (title != null) { + linkString += ";title=\"" + title + "\""; + } + + if (type != null) { + linkString += ";type=\"" + type + "\""; + } + + if (deprecation != null) { + linkString += ";deprecation=\"" + deprecation + "\""; + } + + if (profile != null) { + linkString += ";profile=\"" + profile + "\""; + } + + return linkString; + } + + /** + * Factory method to easily create {@link Link} instances from RFC-5988 compatible {@link String} representations of a + * link. Will return {@literal null} if input {@link String} is either empty or {@literal null}. + * + * @param element an RFC-5899 compatible representation of a link. + * @throws IllegalArgumentException if a non-empty {@link String} was given that does not adhere to RFC-5899. + * @throws IllegalArgumentException if no {@code rel} attribute could be found. + * @return + */ + public static Link valueOf(String element) { + + if (!StringUtils.hasText(element)) { + return null; + } + + Matcher matcher = URI_AND_ATTRIBUTES_PATTERN.matcher(element); + + if (matcher.find()) { + + Map attributes = getAttributeMap(matcher.group(2)); + + if (!attributes.containsKey("rel")) { + throw new IllegalArgumentException("Link does not provide a rel attribute!"); + } + + Link link = new Link(matcher.group(1), attributes.get("rel")); + + if (attributes.containsKey("hreflang")) { + link = link.withHreflang(attributes.get("hreflang")); + } + + if (attributes.containsKey("media")) { + link = link.withMedia(attributes.get("media")); + } + + if (attributes.containsKey("title")) { + link = link.withTitle(attributes.get("title")); + } + + if (attributes.containsKey("type")) { + link = link.withType(attributes.get("type")); + } + + if (attributes.containsKey("deprecation")) { + link = link.withDeprecation(attributes.get("deprecation")); + } + + if (attributes.containsKey("profile")) { + link = link.withProfile(attributes.get("profile")); + } + + return link; + + } else { + throw new IllegalArgumentException(String.format("Given link header %s is not RFC5988 compliant!", element)); + } + } + + /** + * Parses the links attributes from the given source {@link String}. + * + * @param source + * @return + */ + private static Map getAttributeMap(String source) { + + if (!StringUtils.hasText(source)) { + return Collections.emptyMap(); + } + + Map attributes = new HashMap(); + Matcher matcher = KEY_AND_VALUE_PATTERN.matcher(source); + + while (matcher.find()) { + attributes.put(matcher.group(1), matcher.group(2)); + } + + return attributes; + } +} diff --git a/src/main/java/org/springframework/hateoas/ResourceAssembler.java b/src/main/java/org/springframework/hateoas/ResourceAssembler.java index 2b57a84c..60dfbd61 100755 --- a/src/main/java/org/springframework/hateoas/ResourceAssembler.java +++ b/src/main/java/org/springframework/hateoas/ResourceAssembler.java @@ -1,52 +1,52 @@ -/* - * Copyright 2012-2018 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.List; - -/** - * Interface for components that convert a domain type into a {@link ResourceSupport}. - * - * @author Oliver Gierke - * @author Greg Turnquist - */ -public interface ResourceAssembler { - - /** - * Converts the given entity into a {@code D}, which extends {@link ResourceSupport}. - * - * @param entity - * @return - */ - D toResource(T entity); - - /** - * Converts an {@link Iterable} or {@code T}s into an {@link Iterable} of {@link ResourceSupport} and wraps - * them in a {@link Resources} instance. - * - * @param entities must not be {@literal null}. - * @return {@link Resources} containing {@code D}. - */ - default Resources toResources(Iterable entities) { - - List resources = new ArrayList<>(); - for (T entity : entities) { - resources.add(toResource(entity)); - } - return new Resources<>(resources); - } -} +/* + * Copyright 2012-2018 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.List; + +/** + * Interface for components that convert a domain type into a {@link ResourceSupport}. + * + * @author Oliver Gierke + * @author Greg Turnquist + */ +public interface ResourceAssembler { + + /** + * Converts the given entity into a {@code D}, which extends {@link ResourceSupport}. + * + * @param entity + * @return + */ + D toResource(T entity); + + /** + * Converts an {@link Iterable} or {@code T}s into an {@link Iterable} of {@link ResourceSupport} and wraps + * them in a {@link Resources} instance. + * + * @param entities must not be {@literal null}. + * @return {@link Resources} containing {@code D}. + */ + default Resources toResources(Iterable entities) { + + List resources = new ArrayList<>(); + for (T entity : entities) { + resources.add(toResource(entity)); + } + return new Resources<>(resources); + } +} diff --git a/src/main/java/org/springframework/hateoas/ResourceSupport.java b/src/main/java/org/springframework/hateoas/ResourceSupport.java index 83e1a98c..c81b1430 100755 --- a/src/main/java/org/springframework/hateoas/ResourceSupport.java +++ b/src/main/java/org/springframework/hateoas/ResourceSupport.java @@ -1,199 +1,199 @@ -/* - * Copyright 2012-2018 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.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.springframework.util.Assert; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Base class for DTOs to collect links. - * - * @author Oliver Gierke - * @author Johhny Lim - * @author Greg Turnquist - */ -public class ResourceSupport implements Identifiable { - - private final List links; - - public ResourceSupport() { - this.links = new ArrayList<>(); - } - - /** - * Returns the {@link Link} with a rel of {@link Link#REL_SELF}. - */ - @JsonIgnore - public Optional 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); - } - - /** - * Adds all given {@link Link}s to the resource. - * - * @param links - */ - public void add(Iterable links) { - - Assert.notNull(links, "Given links must not be null!"); - - links.forEach(this::add); - } - - /** - * Adds all given {@link Link}s to the resource. - * - * @param links must not be {@literal null}. - */ - public void add(Link... links) { - - Assert.notNull(links, "Given links must not be null!"); - - add(Arrays.asList(links)); - } - - /** - * Returns whether the resource contains {@link Link}s at all. - * - * @return - */ - public boolean hasLinks() { - return !this.links.isEmpty(); - } - - /** - * Returns whether the resource contains a {@link Link} with the given rel. - * - * @param rel - * @return - */ - public boolean hasLink(String rel) { - return getLink(rel).isPresent(); - } - - /** - * Returns all {@link Link}s contained in this resource. - * - * @return - */ - @JsonProperty("links") - public List getLinks() { - return links; - } - - /** - * Removes all {@link Link}s added to the resource so far. - */ - public void removeLinks() { - this.links.clear(); - } - - /** - * Returns the link with the given rel. - * - * @param rel - * @return the link with the given rel or {@link Optional#empty()} if none found. - */ - public Optional getLink(String rel) { - - return links.stream() // - .filter(link -> link.hasRel(rel)) // - .findFirst(); - } - - /** - * Returns the link with the given rel. - * - * @param rel - * @return the link with the given rel. - * @throws IllegalArgumentException in case no link with the given rel can be found. - */ - public Link getRequiredLink(String rel) { - - return getLink(rel) // - .orElseThrow(() -> new IllegalArgumentException(String.format("No link with rel %s found!", rel))); - } - - /** - * Returns all {@link Link}s with the given relation type. - * - * @return the links in a {@link List} - */ - public List getLinks(String rel) { - - return links.stream() // - .filter(link -> link.hasRel(rel)) // - .collect(Collectors.toList()); - } - - /* - * (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return String.format("links: %s", links.toString()); - } - - /* - * (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (obj == null || !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(); - } -} +/* + * Copyright 2012-2018 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.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.springframework.util.Assert; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Base class for DTOs to collect links. + * + * @author Oliver Gierke + * @author Johhny Lim + * @author Greg Turnquist + */ +public class ResourceSupport implements Identifiable { + + private final List links; + + public ResourceSupport() { + this.links = new ArrayList<>(); + } + + /** + * Returns the {@link Link} with a rel of {@link Link#REL_SELF}. + */ + @JsonIgnore + public Optional 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); + } + + /** + * Adds all given {@link Link}s to the resource. + * + * @param links + */ + public void add(Iterable links) { + + Assert.notNull(links, "Given links must not be null!"); + + links.forEach(this::add); + } + + /** + * Adds all given {@link Link}s to the resource. + * + * @param links must not be {@literal null}. + */ + public void add(Link... links) { + + Assert.notNull(links, "Given links must not be null!"); + + add(Arrays.asList(links)); + } + + /** + * Returns whether the resource contains {@link Link}s at all. + * + * @return + */ + public boolean hasLinks() { + return !this.links.isEmpty(); + } + + /** + * Returns whether the resource contains a {@link Link} with the given rel. + * + * @param rel + * @return + */ + public boolean hasLink(String rel) { + return getLink(rel).isPresent(); + } + + /** + * Returns all {@link Link}s contained in this resource. + * + * @return + */ + @JsonProperty("links") + public List getLinks() { + return links; + } + + /** + * Removes all {@link Link}s added to the resource so far. + */ + public void removeLinks() { + this.links.clear(); + } + + /** + * Returns the link with the given rel. + * + * @param rel + * @return the link with the given rel or {@link Optional#empty()} if none found. + */ + public Optional getLink(String rel) { + + return links.stream() // + .filter(link -> link.hasRel(rel)) // + .findFirst(); + } + + /** + * Returns the link with the given rel. + * + * @param rel + * @return the link with the given rel. + * @throws IllegalArgumentException in case no link with the given rel can be found. + */ + public Link getRequiredLink(String rel) { + + return getLink(rel) // + .orElseThrow(() -> new IllegalArgumentException(String.format("No link with rel %s found!", rel))); + } + + /** + * Returns all {@link Link}s with the given relation type. + * + * @return the links in a {@link List} + */ + public List getLinks(String rel) { + + return links.stream() // + .filter(link -> link.hasRel(rel)) // + .collect(Collectors.toList()); + } + + /* + * (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return String.format("links: %s", links.toString()); + } + + /* + * (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + + if (this == obj) { + return true; + } + + if (obj == null || !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(); + } +} diff --git a/src/main/java/org/springframework/hateoas/collectionjson/CollectionJsonDocument.java b/src/main/java/org/springframework/hateoas/collectionjson/CollectionJsonDocument.java index f345db30..7a6a5e47 100644 --- a/src/main/java/org/springframework/hateoas/collectionjson/CollectionJsonDocument.java +++ b/src/main/java/org/springframework/hateoas/collectionjson/CollectionJsonDocument.java @@ -45,6 +45,6 @@ class CollectionJsonDocument { @JsonProperty("queries") List queries, @JsonProperty("template") CollectionJsonTemplate template, @JsonProperty("error") CollectionJsonError error) { - this.collection = new CollectionJson(version, href, links, items, queries, template, error); + this.collection = new CollectionJson<>(version, href, links, items, queries, template, error); } } diff --git a/src/main/java/org/springframework/hateoas/mvc/ControllerLinkBuilder.java b/src/main/java/org/springframework/hateoas/mvc/ControllerLinkBuilder.java index 79bfe744..1eefca0f 100755 --- a/src/main/java/org/springframework/hateoas/mvc/ControllerLinkBuilder.java +++ b/src/main/java/org/springframework/hateoas/mvc/ControllerLinkBuilder.java @@ -1,405 +1,405 @@ -/* - * Copyright 2012-2018 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.springframework.hateoas.mvc.ForwardedHeader.*; - -import lombok.RequiredArgsConstructor; -import lombok.experimental.Delegate; - -import java.lang.reflect.Method; -import java.net.URI; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.context.ApplicationContext; -import org.springframework.core.io.support.SpringFactoriesLoader; -import org.springframework.hateoas.Affordance; -import org.springframework.hateoas.Link; -import org.springframework.hateoas.TemplateVariables; -import org.springframework.hateoas.core.AffordanceModelFactory; -import org.springframework.hateoas.core.AnnotationMappingDiscoverer; -import org.springframework.hateoas.core.DummyInvocationUtils; -import org.springframework.hateoas.core.DummyInvocationUtils.MethodInvocation; -import org.springframework.hateoas.core.LinkBuilderSupport; -import org.springframework.hateoas.core.MappingDiscoverer; -import org.springframework.http.MediaType; -import org.springframework.plugin.core.OrderAwarePluginRegistry; -import org.springframework.plugin.core.PluginRegistry; -import org.springframework.util.Assert; -import org.springframework.util.ConcurrentReferenceHashMap; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import org.springframework.web.util.DefaultUriTemplateHandler; -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 - * @author Kamill Sokol - * @author Greg Turnquist - * @author Kevin Conaway - * @author Andrew Naydyonock - * @author Oliver Trosien - * @author Greg Turnquist - */ -public class ControllerLinkBuilder extends LinkBuilderSupport { - - private static final String REQUEST_ATTRIBUTES_MISSING = "Could not find current request via RequestContextHolder. Is this being called from a Spring MVC handler?"; - private static final CachingAnnotationMappingDiscoverer DISCOVERER = new CachingAnnotationMappingDiscoverer( - new AnnotationMappingDiscoverer(RequestMapping.class)); - private static final ControllerLinkBuilderFactory FACTORY = new ControllerLinkBuilderFactory(); - private static final CustomUriTemplateHandler HANDLER = new CustomUriTemplateHandler(); - - static { - - List factories = SpringFactoriesLoader.loadFactories(AffordanceModelFactory.class, - ControllerLinkBuilder.class.getClassLoader()); - - PluginRegistry MODEL_FACTORIES = OrderAwarePluginRegistry - .create(factories); - } - - private final TemplateVariables variables; - - /** - * Creates a new {@link ControllerLinkBuilder} using the given {@link UriComponentsBuilder}. - * - * @param builder must not be {@literal null}. - */ - ControllerLinkBuilder(UriComponentsBuilder builder) { - - super(builder); - - this.variables = TemplateVariables.NONE; - } - - /** - * Creates a new {@link ControllerLinkBuilder} using the given {@link UriComponents}. - * - * @param uriComponents must not be {@literal null}. - */ - ControllerLinkBuilder(UriComponents uriComponents) { - this(uriComponents, TemplateVariables.NONE, null); - } - - ControllerLinkBuilder(UriComponents uriComponents, TemplateVariables variables, MethodInvocation invocation) { - - super(uriComponents); - - this.variables = variables; - this.addAffordances(findAffordances(invocation, uriComponents)); - } - - /** - * Creates a new {@link ControllerLinkBuilder} with a base of the mapping annotated to the given controller class. - * - * @param controller the class to discover the annotation on, must not be {@literal null}. - * @return - */ - public static ControllerLinkBuilder linkTo(Class controller) { - return linkTo(controller, new Object[0]); - } - - /** - * Creates a new {@link ControllerLinkBuilder} with a base of the mapping annotated to the given controller class. The - * additional parameters are used to fill up potentially available path variables in the class scop request mapping. - * - * @param controller the class to discover the annotation on, must not be {@literal null}. - * @param parameters additional parameters to bind to the URI template declared in the annotation, must not be - * {@literal null}. - * @return - */ - public static ControllerLinkBuilder linkTo(Class controller, Object... parameters) { - - Assert.notNull(controller, "Controller must not be null!"); - Assert.notNull(parameters, "Parameters must not be null!"); - - String mapping = DISCOVERER.getMapping(controller); - - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(mapping == null ? "/" : mapping); - UriComponents uriComponents = HANDLER.expandAndEncode(builder, parameters); - - return new ControllerLinkBuilder(getBuilder()).slash(uriComponents, true); - } - - /** - * Creates a new {@link ControllerLinkBuilder} with a base of the mapping annotated to the given controller class. - * Parameter map is used to fill up potentially available path variables in the class scope request mapping. - * - * @param controller the class to discover the annotation on, must not be {@literal null}. - * @param parameters additional parameters to bind to the URI template declared in the annotation, must not be - * {@literal null}. - * @return - */ - public static ControllerLinkBuilder linkTo(Class controller, Map parameters) { - - Assert.notNull(controller, "Controller must not be null!"); - Assert.notNull(parameters, "Parameters must not be null!"); - - String mapping = DISCOVERER.getMapping(controller); - - UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(mapping == null ? "/" : mapping); - UriComponents uriComponents = HANDLER.expandAndEncode(builder, parameters); - - return new ControllerLinkBuilder(getBuilder()).slash(uriComponents, true); - } - - /* - * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(Method, Object...) - */ - public static ControllerLinkBuilder linkTo(Method method, Object... parameters) { - return linkTo(method.getDeclaringClass(), method, parameters); - } - - /* - * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(Class, Method, Object...) - */ - public static ControllerLinkBuilder linkTo(Class controller, Method method, Object... parameters) { - - Assert.notNull(controller, "Controller type must not be null!"); - Assert.notNull(method, "Method must not be null!"); - - UriTemplate template = DISCOVERER.getMappingAsUriTemplate(controller, method); - URI uri = template.expand(parameters); - - return new ControllerLinkBuilder(getBuilder()).slash(uri); - } - - /** - * Creates a {@link ControllerLinkBuilder} pointing to a controller method. Hand in a dummy method invocation result - * you can create via {@link #methodOn(Class, Object...)} or {@link DummyInvocationUtils#methodOn(Class, Object...)}. - * - *
-	 * @RequestMapping("/customers")
-	 * class CustomerController {
-	 * 
-	 *   @RequestMapping("/{id}/addresses")
-	 *   HttpEntity<Addresses> showAddresses(@PathVariable Long id) { … } 
-	 * }
-	 * 
-	 * Link link = linkTo(methodOn(CustomerController.class).showAddresses(2L)).withRel("addresses");
-	 * 
- * - * The resulting {@link Link} instance will point to {@code /customers/2/addresses} and have a rel of - * {@code addresses}. For more details on the method invocation constraints, see - * {@link DummyInvocationUtils#methodOn(Class, Object...)}. - * - * @param invocationValue - * @return - */ - public static ControllerLinkBuilder linkTo(Object invocationValue) { - return FACTORY.linkTo(invocationValue); - } - - /** - * Extract a {@link Link} from the {@link ControllerLinkBuilder} and look up the related {@link Affordance}. Should - * only be one. - * - *
-	 * Link findOneLink = linkTo(methodOn(EmployeeController.class).findOne(id)).withSelfRel()
-	 * 		.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, id)));
-	 * 
- * - * This takes a link and adds an {@link Affordance} based on another Spring MVC handler method. - * - * @param invocationValue - * @return - */ - public static Affordance afford(Object invocationValue) { - - ControllerLinkBuilder linkBuilder = linkTo(invocationValue); - - Assert.isTrue(linkBuilder.getAffordances().size() == 1, "A base can only have one affordance, itself"); - - return linkBuilder.getAffordances().get(0); - } - - /** - * Wrapper for {@link DummyInvocationUtils#methodOn(Class, Object...)} to be available in case you work with static - * imports of {@link ControllerLinkBuilder}. - * - * @param controller must not be {@literal null}. - * @param parameters parameters to extend template variables in the type level mapping. - * @return - */ - public static T methodOn(Class controller, Object... parameters) { - return DummyInvocationUtils.methodOn(controller, parameters); - } - - /* - * (non-Javadoc) - * @see org.springframework.hateoas.UriComponentsLinkBuilder#getThis() - */ - @Override - protected ControllerLinkBuilder getThis() { - return this; - } - - /* - * (non-Javadoc) - * @see org.springframework.hateoas.UriComponentsLinkBuilder#createNewInstance(org.springframework.web.util.UriComponentsBuilder) - */ - @Override - protected ControllerLinkBuilder createNewInstance(UriComponentsBuilder builder) { - return new ControllerLinkBuilder(builder); - } - - /** - * Returns a {@link UriComponentsBuilder} to continue to build the already built URI in a more fine grained way. - * - * @return - */ - public UriComponentsBuilder toUriComponentsBuilder() { - return UriComponentsBuilder.fromUri(toUri()); - } - - /* - * (non-Javadoc) - * @see org.springframework.hateoas.core.LinkBuilderSupport#toString() - */ - @Override - public String toString() { - - String result = super.toString(); - - if (variables == TemplateVariables.NONE) { - return result; - } - - if (!result.contains("#")) { - return result.concat(variables.toString()); - } - - String[] parts = result.split("#"); - return parts[0].concat(variables.toString()).concat("#").concat(parts[0]); - } - - /** - * Returns a {@link UriComponentsBuilder} obtained from the current servlet mapping with scheme tweaked in case the - * request contains an {@code X-Forwarded-Ssl} header, which is not (yet) supported by the underlying - * {@link UriComponentsBuilder}. If no {@link RequestContextHolder} exists (you're outside a Spring Web call), fall - * back to relative URIs. - * - * @return - */ - public static UriComponentsBuilder getBuilder() { - - if (RequestContextHolder.getRequestAttributes() == null) { - return UriComponentsBuilder.fromPath("/"); - } - - HttpServletRequest request = getCurrentRequest(); - ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromServletMapping(request); - - // Spring 5.1 can handle X-Forwarded-Ssl headers... - if (isSpringAtLeast5_1()) { - return builder; - } else { - return handleXForwardedSslHeader(request, builder); - } - } - - /** - * Check if the current version of Spring Framework is 5.1 or higher. - * - * @return - */ - private static boolean isSpringAtLeast5_1() { - - String versionOfSpringFramework = ApplicationContext.class.getPackage().getImplementationVersion(); - - String[] parts = versionOfSpringFramework.split("\\."); - int majorVersion = Integer.parseInt(parts[0]); - int minorVersion = Integer.parseInt(parts[1]); - - return (majorVersion >= 5 && minorVersion >= 1) || (majorVersion > 5); - } - - /** - * Copy of {@link ServletUriComponentsBuilder#getCurrentRequest()} until SPR-10110 gets fixed. - * - * @return - */ - @SuppressWarnings("null") - private static HttpServletRequest getCurrentRequest() { - - RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - Assert.state(requestAttributes != null, REQUEST_ATTRIBUTES_MISSING); - Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes); - HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest(); - Assert.state(servletRequest != null, "Could not find current HttpServletRequest"); - return servletRequest; - } - - /** - * Look up {@link Affordance}s based on the {@link MethodInvocation} and {@link UriComponents}. - * - * @param invocation - * @param components - * @return - */ - private static Collection findAffordances(MethodInvocation invocation, UriComponents components) { - return SpringMvcAffordanceBuilder.create(invocation, DISCOVERER, components); - } - - @RequiredArgsConstructor - private static class CachingAnnotationMappingDiscoverer implements MappingDiscoverer { - - private final @Delegate AnnotationMappingDiscoverer delegate; - private final Map templates = new ConcurrentReferenceHashMap<>(); - - public UriTemplate getMappingAsUriTemplate(Class type, Method method) { - - String mapping = delegate.getMapping(type, method); - return templates.computeIfAbsent(mapping, UriTemplate::new); - } - } - - private static class CustomUriTemplateHandler extends DefaultUriTemplateHandler { - - public CustomUriTemplateHandler() { - setStrictEncoding(true); - } - - /* - * (non-Javadoc) - * @see org.springframework.web.util.DefaultUriTemplateHandler#expandAndEncode(org.springframework.web.util.UriComponentsBuilder, java.util.Map) - */ - @Override - public UriComponents expandAndEncode(UriComponentsBuilder builder, Map uriVariables) { - return super.expandAndEncode(builder, uriVariables); - } - - /* - * (non-Javadoc) - * @see org.springframework.web.util.DefaultUriTemplateHandler#expandAndEncode(org.springframework.web.util.UriComponentsBuilder, java.lang.Object[]) - */ - @Override - public UriComponents expandAndEncode(UriComponentsBuilder builder, Object[] uriVariables) { - return super.expandAndEncode(builder, uriVariables); - } - } -} +/* + * Copyright 2012-2018 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.springframework.hateoas.mvc.ForwardedHeader.*; + +import lombok.RequiredArgsConstructor; +import lombok.experimental.Delegate; + +import java.lang.reflect.Method; +import java.net.URI; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.support.SpringFactoriesLoader; +import org.springframework.hateoas.Affordance; +import org.springframework.hateoas.Link; +import org.springframework.hateoas.TemplateVariables; +import org.springframework.hateoas.core.AffordanceModelFactory; +import org.springframework.hateoas.core.AnnotationMappingDiscoverer; +import org.springframework.hateoas.core.DummyInvocationUtils; +import org.springframework.hateoas.core.DummyInvocationUtils.MethodInvocation; +import org.springframework.hateoas.core.LinkBuilderSupport; +import org.springframework.hateoas.core.MappingDiscoverer; +import org.springframework.http.MediaType; +import org.springframework.plugin.core.OrderAwarePluginRegistry; +import org.springframework.plugin.core.PluginRegistry; +import org.springframework.util.Assert; +import org.springframework.util.ConcurrentReferenceHashMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import org.springframework.web.util.DefaultUriTemplateHandler; +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 + * @author Kamill Sokol + * @author Greg Turnquist + * @author Kevin Conaway + * @author Andrew Naydyonock + * @author Oliver Trosien + * @author Greg Turnquist + */ +public class ControllerLinkBuilder extends LinkBuilderSupport { + + private static final String REQUEST_ATTRIBUTES_MISSING = "Could not find current request via RequestContextHolder. Is this being called from a Spring MVC handler?"; + private static final CachingAnnotationMappingDiscoverer DISCOVERER = new CachingAnnotationMappingDiscoverer( + new AnnotationMappingDiscoverer(RequestMapping.class)); + private static final ControllerLinkBuilderFactory FACTORY = new ControllerLinkBuilderFactory(); + private static final CustomUriTemplateHandler HANDLER = new CustomUriTemplateHandler(); + + static { + + List factories = SpringFactoriesLoader.loadFactories(AffordanceModelFactory.class, + ControllerLinkBuilder.class.getClassLoader()); + + PluginRegistry MODEL_FACTORIES = OrderAwarePluginRegistry + .create(factories); + } + + private final TemplateVariables variables; + + /** + * Creates a new {@link ControllerLinkBuilder} using the given {@link UriComponentsBuilder}. + * + * @param builder must not be {@literal null}. + */ + ControllerLinkBuilder(UriComponentsBuilder builder) { + + super(builder); + + this.variables = TemplateVariables.NONE; + } + + /** + * Creates a new {@link ControllerLinkBuilder} using the given {@link UriComponents}. + * + * @param uriComponents must not be {@literal null}. + */ + ControllerLinkBuilder(UriComponents uriComponents) { + this(uriComponents, TemplateVariables.NONE, null); + } + + ControllerLinkBuilder(UriComponents uriComponents, TemplateVariables variables, MethodInvocation invocation) { + + super(uriComponents); + + this.variables = variables; + this.addAffordances(findAffordances(invocation, uriComponents)); + } + + /** + * Creates a new {@link ControllerLinkBuilder} with a base of the mapping annotated to the given controller class. + * + * @param controller the class to discover the annotation on, must not be {@literal null}. + * @return + */ + public static ControllerLinkBuilder linkTo(Class controller) { + return linkTo(controller, new Object[0]); + } + + /** + * Creates a new {@link ControllerLinkBuilder} with a base of the mapping annotated to the given controller class. The + * additional parameters are used to fill up potentially available path variables in the class scop request mapping. + * + * @param controller the class to discover the annotation on, must not be {@literal null}. + * @param parameters additional parameters to bind to the URI template declared in the annotation, must not be + * {@literal null}. + * @return + */ + public static ControllerLinkBuilder linkTo(Class controller, Object... parameters) { + + Assert.notNull(controller, "Controller must not be null!"); + Assert.notNull(parameters, "Parameters must not be null!"); + + String mapping = DISCOVERER.getMapping(controller); + + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(mapping == null ? "/" : mapping); + UriComponents uriComponents = HANDLER.expandAndEncode(builder, parameters); + + return new ControllerLinkBuilder(getBuilder()).slash(uriComponents, true); + } + + /** + * Creates a new {@link ControllerLinkBuilder} with a base of the mapping annotated to the given controller class. + * Parameter map is used to fill up potentially available path variables in the class scope request mapping. + * + * @param controller the class to discover the annotation on, must not be {@literal null}. + * @param parameters additional parameters to bind to the URI template declared in the annotation, must not be + * {@literal null}. + * @return + */ + public static ControllerLinkBuilder linkTo(Class controller, Map parameters) { + + Assert.notNull(controller, "Controller must not be null!"); + Assert.notNull(parameters, "Parameters must not be null!"); + + String mapping = DISCOVERER.getMapping(controller); + + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(mapping == null ? "/" : mapping); + UriComponents uriComponents = HANDLER.expandAndEncode(builder, parameters); + + return new ControllerLinkBuilder(getBuilder()).slash(uriComponents, true); + } + + /* + * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(Method, Object...) + */ + public static ControllerLinkBuilder linkTo(Method method, Object... parameters) { + return linkTo(method.getDeclaringClass(), method, parameters); + } + + /* + * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(Class, Method, Object...) + */ + public static ControllerLinkBuilder linkTo(Class controller, Method method, Object... parameters) { + + Assert.notNull(controller, "Controller type must not be null!"); + Assert.notNull(method, "Method must not be null!"); + + UriTemplate template = DISCOVERER.getMappingAsUriTemplate(controller, method); + URI uri = template.expand(parameters); + + return new ControllerLinkBuilder(getBuilder()).slash(uri); + } + + /** + * Creates a {@link ControllerLinkBuilder} pointing to a controller method. Hand in a dummy method invocation result + * you can create via {@link #methodOn(Class, Object...)} or {@link DummyInvocationUtils#methodOn(Class, Object...)}. + * + *
+	 * @RequestMapping("/customers")
+	 * class CustomerController {
+	 * 
+	 *   @RequestMapping("/{id}/addresses")
+	 *   HttpEntity<Addresses> showAddresses(@PathVariable Long id) { … } 
+	 * }
+	 * 
+	 * Link link = linkTo(methodOn(CustomerController.class).showAddresses(2L)).withRel("addresses");
+	 * 
+ * + * The resulting {@link Link} instance will point to {@code /customers/2/addresses} and have a rel of + * {@code addresses}. For more details on the method invocation constraints, see + * {@link DummyInvocationUtils#methodOn(Class, Object...)}. + * + * @param invocationValue + * @return + */ + public static ControllerLinkBuilder linkTo(Object invocationValue) { + return FACTORY.linkTo(invocationValue); + } + + /** + * Extract a {@link Link} from the {@link ControllerLinkBuilder} and look up the related {@link Affordance}. Should + * only be one. + * + *
+	 * Link findOneLink = linkTo(methodOn(EmployeeController.class).findOne(id)).withSelfRel()
+	 * 		.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, id)));
+	 * 
+ * + * This takes a link and adds an {@link Affordance} based on another Spring MVC handler method. + * + * @param invocationValue + * @return + */ + public static Affordance afford(Object invocationValue) { + + ControllerLinkBuilder linkBuilder = linkTo(invocationValue); + + Assert.isTrue(linkBuilder.getAffordances().size() == 1, "A base can only have one affordance, itself"); + + return linkBuilder.getAffordances().get(0); + } + + /** + * Wrapper for {@link DummyInvocationUtils#methodOn(Class, Object...)} to be available in case you work with static + * imports of {@link ControllerLinkBuilder}. + * + * @param controller must not be {@literal null}. + * @param parameters parameters to extend template variables in the type level mapping. + * @return + */ + public static T methodOn(Class controller, Object... parameters) { + return DummyInvocationUtils.methodOn(controller, parameters); + } + + /* + * (non-Javadoc) + * @see org.springframework.hateoas.UriComponentsLinkBuilder#getThis() + */ + @Override + protected ControllerLinkBuilder getThis() { + return this; + } + + /* + * (non-Javadoc) + * @see org.springframework.hateoas.UriComponentsLinkBuilder#createNewInstance(org.springframework.web.util.UriComponentsBuilder) + */ + @Override + protected ControllerLinkBuilder createNewInstance(UriComponentsBuilder builder) { + return new ControllerLinkBuilder(builder); + } + + /** + * Returns a {@link UriComponentsBuilder} to continue to build the already built URI in a more fine grained way. + * + * @return + */ + public UriComponentsBuilder toUriComponentsBuilder() { + return UriComponentsBuilder.fromUri(toUri()); + } + + /* + * (non-Javadoc) + * @see org.springframework.hateoas.core.LinkBuilderSupport#toString() + */ + @Override + public String toString() { + + String result = super.toString(); + + if (variables == TemplateVariables.NONE) { + return result; + } + + if (!result.contains("#")) { + return result.concat(variables.toString()); + } + + String[] parts = result.split("#"); + return parts[0].concat(variables.toString()).concat("#").concat(parts[0]); + } + + /** + * Returns a {@link UriComponentsBuilder} obtained from the current servlet mapping with scheme tweaked in case the + * request contains an {@code X-Forwarded-Ssl} header, which is not (yet) supported by the underlying + * {@link UriComponentsBuilder}. If no {@link RequestContextHolder} exists (you're outside a Spring Web call), fall + * back to relative URIs. + * + * @return + */ + public static UriComponentsBuilder getBuilder() { + + if (RequestContextHolder.getRequestAttributes() == null) { + return UriComponentsBuilder.fromPath("/"); + } + + HttpServletRequest request = getCurrentRequest(); + ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromServletMapping(request); + + // Spring 5.1 can handle X-Forwarded-Ssl headers... + if (isSpringAtLeast5_1()) { + return builder; + } else { + return handleXForwardedSslHeader(request, builder); + } + } + + /** + * Check if the current version of Spring Framework is 5.1 or higher. + * + * @return + */ + private static boolean isSpringAtLeast5_1() { + + String versionOfSpringFramework = ApplicationContext.class.getPackage().getImplementationVersion(); + + String[] parts = versionOfSpringFramework.split("\\."); + int majorVersion = Integer.parseInt(parts[0]); + int minorVersion = Integer.parseInt(parts[1]); + + return (majorVersion >= 5 && minorVersion >= 1) || (majorVersion > 5); + } + + /** + * Copy of {@link ServletUriComponentsBuilder#getCurrentRequest()} until SPR-10110 gets fixed. + * + * @return + */ + @SuppressWarnings("null") + private static HttpServletRequest getCurrentRequest() { + + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + Assert.state(requestAttributes != null, REQUEST_ATTRIBUTES_MISSING); + Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes); + HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest(); + Assert.state(servletRequest != null, "Could not find current HttpServletRequest"); + return servletRequest; + } + + /** + * Look up {@link Affordance}s based on the {@link MethodInvocation} and {@link UriComponents}. + * + * @param invocation + * @param components + * @return + */ + private static Collection findAffordances(MethodInvocation invocation, UriComponents components) { + return SpringMvcAffordanceBuilder.create(invocation, DISCOVERER, components); + } + + @RequiredArgsConstructor + private static class CachingAnnotationMappingDiscoverer implements MappingDiscoverer { + + private final @Delegate AnnotationMappingDiscoverer delegate; + private final Map templates = new ConcurrentReferenceHashMap<>(); + + public UriTemplate getMappingAsUriTemplate(Class type, Method method) { + + String mapping = delegate.getMapping(type, method); + return templates.computeIfAbsent(mapping, UriTemplate::new); + } + } + + private static class CustomUriTemplateHandler extends DefaultUriTemplateHandler { + + public CustomUriTemplateHandler() { + setStrictEncoding(true); + } + + /* + * (non-Javadoc) + * @see org.springframework.web.util.DefaultUriTemplateHandler#expandAndEncode(org.springframework.web.util.UriComponentsBuilder, java.util.Map) + */ + @Override + public UriComponents expandAndEncode(UriComponentsBuilder builder, Map uriVariables) { + return super.expandAndEncode(builder, uriVariables); + } + + /* + * (non-Javadoc) + * @see org.springframework.web.util.DefaultUriTemplateHandler#expandAndEncode(org.springframework.web.util.UriComponentsBuilder, java.lang.Object[]) + */ + @Override + public UriComponents expandAndEncode(UriComponentsBuilder builder, Object[] uriVariables) { + return super.expandAndEncode(builder, uriVariables); + } + } +} diff --git a/src/main/java/org/springframework/hateoas/mvc/ResourceAssemblerSupport.java b/src/main/java/org/springframework/hateoas/mvc/ResourceAssemblerSupport.java index b75e3fd6..6331722a 100755 --- a/src/main/java/org/springframework/hateoas/mvc/ResourceAssemblerSupport.java +++ b/src/main/java/org/springframework/hateoas/mvc/ResourceAssemblerSupport.java @@ -1,137 +1,137 @@ -/* - * Copyright 2012-2018 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.springframework.hateoas.mvc.ControllerLinkBuilder.*; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.beans.BeanUtils; -import org.springframework.hateoas.ResourceAssembler; -import org.springframework.hateoas.ResourceSupport; -import org.springframework.hateoas.Resources; -import org.springframework.hateoas.core.Objects; - -/** - * 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 - * @author Greg Turnquist - */ -public abstract class ResourceAssemblerSupport implements ResourceAssembler { - - private final Class controllerClass; - private final Class 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 resourceType) { - - Objects.requireNonNull(controllerClass, "ControllerClass must not be null!"); - Objects.requireNonNull(resourceType, "ResourceType must not be null!"); - - this.controllerClass = controllerClass; - this.resourceType = resourceType; - } - - @Override - public Resources toResources(Iterable entities) { - return this.map(entities).toResources(); - } - - public Builder map(Iterable entities) { - return new Builder<>(entities, this); - } - - /** - * Creates a new resource with a self link to the given id. - * - * @param entity must not be {@literal null}. - * @param id must not be {@literal null}. - * @return - */ - protected D createResourceWithId(Object id, T entity) { - return createResourceWithId(id, entity, new Object[0]); - } - - protected D createResourceWithId(Object id, T entity, Object... parameters) { - - Objects.requireNonNull(entity, "Entity must not be null!"); - Objects.requireNonNull(id, "Id must not be null!"); - - D instance = instantiateResource(entity); - instance.add(linkTo(this.controllerClass, parameters).slash(id).withSelfRel()); - return instance; - } - - /** - * 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(this.resourceType); - } - - static class Builder { - - private final Iterable entities; - private final ResourceAssemblerSupport resourceAssembler; - - Builder(Iterable entities, ResourceAssemblerSupport resourceAssembler) { - - this.entities = Objects.requireNonNull(entities, "entities must not null!"); - this.resourceAssembler = resourceAssembler; - } - - /** - * Transform a list of {@code T}s into a list of {@link ResourceSupport}s. - * - * @see {@link #toListOfResources()} if you need this transformed list rendered as hypermedia - * - * @return - */ - public List toListOfResources() { - - List result = new ArrayList<>(); - - for (T entity : this.entities) { - result.add(this.resourceAssembler.toResource(entity)); - } - - return result; - } - - /** - * Converts all given entities into resources and wraps the result in a {@link Resources} instance. - * - * @see {@link #toListOfResources()}} and {@link ResourceAssembler#toResource(Object)} - * @return - */ - public Resources toResources() { - return new Resources<>(toListOfResources()); - } - } -} +/* + * Copyright 2012-2018 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.springframework.hateoas.mvc.ControllerLinkBuilder.*; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.BeanUtils; +import org.springframework.hateoas.ResourceAssembler; +import org.springframework.hateoas.ResourceSupport; +import org.springframework.hateoas.Resources; +import org.springframework.hateoas.core.Objects; + +/** + * 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 + * @author Greg Turnquist + */ +public abstract class ResourceAssemblerSupport implements ResourceAssembler { + + private final Class controllerClass; + private final Class 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 resourceType) { + + Objects.requireNonNull(controllerClass, "ControllerClass must not be null!"); + Objects.requireNonNull(resourceType, "ResourceType must not be null!"); + + this.controllerClass = controllerClass; + this.resourceType = resourceType; + } + + @Override + public Resources toResources(Iterable entities) { + return this.map(entities).toResources(); + } + + public Builder map(Iterable entities) { + return new Builder<>(entities, this); + } + + /** + * Creates a new resource with a self link to the given id. + * + * @param entity must not be {@literal null}. + * @param id must not be {@literal null}. + * @return + */ + protected D createResourceWithId(Object id, T entity) { + return createResourceWithId(id, entity, new Object[0]); + } + + protected D createResourceWithId(Object id, T entity, Object... parameters) { + + Objects.requireNonNull(entity, "Entity must not be null!"); + Objects.requireNonNull(id, "Id must not be null!"); + + D instance = instantiateResource(entity); + instance.add(linkTo(this.controllerClass, parameters).slash(id).withSelfRel()); + return instance; + } + + /** + * 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(this.resourceType); + } + + static class Builder { + + private final Iterable entities; + private final ResourceAssemblerSupport resourceAssembler; + + Builder(Iterable entities, ResourceAssemblerSupport resourceAssembler) { + + this.entities = Objects.requireNonNull(entities, "entities must not null!"); + this.resourceAssembler = resourceAssembler; + } + + /** + * Transform a list of {@code T}s into a list of {@link ResourceSupport}s. + * + * @see {@link #toListOfResources()} if you need this transformed list rendered as hypermedia + * + * @return + */ + public List toListOfResources() { + + List result = new ArrayList<>(); + + for (T entity : this.entities) { + result.add(this.resourceAssembler.toResource(entity)); + } + + return result; + } + + /** + * Converts all given entities into resources and wraps the result in a {@link Resources} instance. + * + * @see {@link #toListOfResources()}} and {@link ResourceAssembler#toResource(Object)} + * @return + */ + public Resources toResources() { + return new Resources<>(toListOfResources()); + } + } +}