### Custom Media Type Configuration Example Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Example of configuring a custom media type by implementing HypermediaMappingInformation. This involves Jackson ObjectMapper customization and LinkDiscoverer implementation. ```java @Configuration public class MyMediaTypeConfiguration implements HypermediaMappingInformation { @Override public List getMediaTypes() { ``` -------------------------------- ### Spring MVC Controller Example Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Example Spring MVC controller with collection and individual resource mappings. ```java @Controller class PersonController { @GetMapping("/people") HttpEntity showAll() { … } @GetMapping("/{person}") HttpEntity show(@PathVariable Long person) { … } } ``` -------------------------------- ### Sample HAL Document with Link Titles Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Example HAL document demonstrating the use of internationalized link titles. ```javascript { "_links" : { "cancel" : { "href" : "…" "title" : "Cancel order" }, "payment" : { "href" : "…" "title" : "Proceed to checkout" } } } ``` -------------------------------- ### Obtaining a Link to an Item Resource Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc A concise example showing how to obtain a link to a specific item resource using its entity and identifier. ```java entityLinks.linkToItemResource(order, order.getId()); ``` -------------------------------- ### Sample HAL-FORMS Document Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc This is an example of a HAL-FORMS document structure. Clients sending an 'Accept' header with 'application/prs.hal-forms+json' can expect this format. ```json { "_templates": { "default": { "method": "POST", "target": "/orders", "properties": { "productId": { "type": "string", "title": "Product id", "required": true }, "quantity": { "type": "number", "title": "Quantity", "required": true, "minimum": 1 } } } } } ``` -------------------------------- ### EntityLinks Capable Controller Example Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Shows an example of a Spring MVC controller annotated to expose resource information for a specific entity type. ```java @Controller @ExposesResourceFor(Order.class) <1> @RequestMapping("/orders") <2> class OrderController { @GetMapping <3> ResponseEntity orders(…) { … } @GetMapping("{id}") <4> ResponseEntity order(@PathVariable("id") … ) { … } } ``` -------------------------------- ### HTML Link Example Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc An example of a link in an HTML document, showing its reference and relation. ```html ``` -------------------------------- ### Order with Payment Link JSON Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Example JSON response for an Order entity model including a 'payments' link. ```json { "_links": { "self": { "href": "/orders/1" }, "payments": { "href": "/orders/1/payments" } } } ``` -------------------------------- ### HAL Document with Curies Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Example HAL document showing the use of curies for link relation types. ```javascript { "_links": { "curies": [ { "name": "ex", "href": "https://www.example.com/rels/{rel}", "templated": true } ], "ex:orders": { "href": "/orders" } } } ``` -------------------------------- ### Configure HAL-FORMS Options for Property Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Define HAL-FORMS options for a property using HalFormsConfiguration. This example sets inline options for the 'shippingMethod' property of the Order class. ```java @Configuration class CustomConfiguration { @Bean HalFormsConfiguration halFormsConfiguration() { HalFormsConfiguration configuration = new HalFormsConfiguration(); configuration.withOptions(Order.class, "shippingMethod" metadata -> HalFormsOptions.inline("FedEx", "DHL")); } } ``` -------------------------------- ### Build HAL Representation Model with API Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Use HalModelBuilder to create RepresentationModel instances with HAL-idiomatic API. This example shows how to embed previews, specify links, and include additional embedded objects. ```java var order = new Order(…); var customer = customer.findById(order.getCustomerId()); var customerLink = Link.of("/orders/{id}/customer") .expand(order.getId()) .withRel("customer"); var additional = … var model = HalModelBuilder.halModelOf(order) .preview(new CustomerSummary(customer)) .forLink(customerLink) .embed(additional) .link(Link.of(…, IanaLinkRelations.SELF)); .build(); ``` -------------------------------- ### Define HAL-FORMS Property Prompts Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Examples of defining HAL-FORMS property prompts using resource bundle keys. Covers global, local, and fully-qualified type name definitions for the 'firstName' property. ```properties firstName._prompt=Firstname <1> Employee.firstName._prompt=Firstname <2> com.acme.Employee.firstName._prompt=Firstname <3> ``` -------------------------------- ### Build ALPS Profile Record Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Example of building an ALPS (Application-Level Profile Semantics) record in Java for use with Spring MVC or Spring WebFlux. ALPS provides profile-based metadata about resources. ```java include::{test-dir}/support/WebMvcEmployeeController.java[tag=alps-profile] ``` -------------------------------- ### Define HAL-FORMS Template Titles Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Examples of defining HAL-FORMS template titles using resource bundle keys. Covers global, affordance-specific, local, and fully-qualified type name definitions. ```properties _templates.default.title=Some title <1> _templates.putEmployee.title=Create employee <2> Employee._templates.default.title=Create employee <3> com.acme.Employee._templates.default.title=Create employee <4> ``` -------------------------------- ### Collection+JSON Single Item Example Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Illustrates the structure of a single item response conforming to the Collection+JSON specification. Note how Spring HATEOAS maps EntityModel properties and links. ```javascript include::{resource-dir}/docs/mediatype/collectionjson/spec-part3.json[] ``` -------------------------------- ### Request with X-Forwarded Headers Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc This bash command shows an example of making a curl request to a Spring HATEOAS application, including X-Forwarded headers. These headers are used to inform the application about the original request's protocol, host, and port when it's behind a proxy or load balancer. ```bash curl -v localhost:8080/employees \ -H 'X-Forwarded-Proto: https' \ -H 'X-Forwarded-Host: example.com' \ -H 'X-Forwarded-Port: 9001' ``` -------------------------------- ### HAL Document with Multiple Links for One Relation Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Example of a HAL document that includes multiple links associated with a single link relation, as per the HAL specification. ```json { "_links": { "self": [ { "href": "/users/1" }, { "href": "/users/1?version=2" } ] } } ``` -------------------------------- ### Control Request Parameter Rendering with @NonComposite Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Use the @NonComposite annotation to render collection-valued request parameters with comma-separated values instead of the default composite style. This example demonstrates its usage in a Spring MVC controller and how to verify the output. ```java @Controller class PersonController { @GetMapping("/people") HttpEntity showAll( @NonComposite @RequestParam Collection names) { … } <1> } var values = List.of("Matthews", "Beauford"); var link = linkTo(methodOn(PersonController.class).showAll(values)).withSelfRel(); <2> assertThat(link.getHref()).endsWith("/people?names=Matthews,Beauford"); <3> ``` -------------------------------- ### Working with URI Templates Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc Illustrates manual construction of URI templates and adding template variables. ```java UriTemplate template = UriTemplate.of("/{segment}/something") .with(new TemplateVariable("parameter", VariableType.REQUEST_PARAM); assertThat(template.toString()).isEqualTo("/{segment}/something{?parameter}"); ``` -------------------------------- ### Sample Application of Migration Script Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/migrate-to-1.0.adoc Demonstrates the execution of the migration script from the command line. This script helps update import statements and static method references for Spring HATEOAS types. ```bash $ ./migrate-to-1.0.sh Migrating Spring HATEOAS references to 1.0 for files : *.java Adapting ./src/main/java/… … Done! ``` -------------------------------- ### Configure WebClient for Hypermedia Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Demonstrates configuring a WebClient instance to speak hypermedia by using HypermediaWebClientConfigurer. ```java include::{base-dir}/src/docs/java/org/springframework/hateoas/client/HypermediaConfiguration.java[tag=web-client] ``` -------------------------------- ### Prepare for Release with Maven Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc Use the Maven release plugin to prepare for a new release. Specify the release and development versions, commit messages, and the tag name. ```bash $ mvn release:prepare \ -DreleaseVersion="1.2.3" \ -DdevelopmentVersion="1.2.4-SNAPSHOT" \ -DscmReleaseCommitComment="GH-4711 - Release version 1.2.3." \ -DscmDevelopmentCommitComment="GH-4711 - Prepare next development iteration." \ -Dtag="1.2.3" ``` -------------------------------- ### Manually Build Affordances with Affordances API Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Demonstrates how to manually construct affordances using the Affordances API. This allows for explicit definition of HTTP methods, payload types, and affordance names when the automatic linking is insufficient. ```java include::{code-dir}/AffordancesSample.java[tag=affordances] ``` -------------------------------- ### Using Links in Java Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc Demonstrates the creation and usage of immutable Link objects in Spring HATEOAS. ```java include::{code-dir}/FundamentalsTest.java[tags=links] ``` -------------------------------- ### Using EntityLinks API Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Demonstrates basic usage of EntityLinks to create link builders and item resource links. ```java EntityLinks links = …; LinkBuilder builder = links.linkFor(Customer.class); Link link = links.linkToItemResource(Customer.class, 1L); ``` -------------------------------- ### Building Link via Dummy Method Invocation Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Generate a link to a controller method using a dummy invocation on a proxy. This is a more fluent and less cumbersome approach than using Method instances directly. ```java Link link = linkTo(methodOn(PersonController.class).show(2L)).withSelfRel(); assertThat(link.getHref()).endsWith("/people/2"); ``` -------------------------------- ### Building Link via Method Instance Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Create a link to a controller method by providing a Method instance. This approach requires explicit Method object retrieval. ```java Method method = PersonController.class.getMethod("show", Long.class); Link link = linkTo(method, 2L).withSelfRel(); assertThat(link.getHref()).endsWith("/people/2")); ``` -------------------------------- ### Run Maven Release Plugin (Tyinator Shortcut) Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc A Typinator shortcut to run the Maven release plugin for preparing a release. It uses placeholders for release version, development version, and ticket ID. ```bash mvn release:prepare \ -DreleaseVersion="{{version=?Release version}}{{version}}" \ -DdevelopmentVersion="{{devVersion=?Development version}}{{devVersion}}" \ -DscmReleaseCommitComment="GH-{{ticketId=?Ticket}}{{ticketId}} - Release version {{version}}. " \ -DscmDevelopmentCommitComment="GH-{{ticketId}} - Prepare next development iteration." \ -Dtag="{{version}}" ``` -------------------------------- ### Traverson Traversal with Map Parameters Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Illustrates loading an entire Map of parameters into Traverson using .withParameters(Map) for URI template expansion. ```java include::{base-dir}/src/test/java/org/springframework/hateoas/client/TraversonTest.java[tag=hop-put] ``` -------------------------------- ### Return Supported Media Type Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc The configuration class returns the media type it supports. This applies to both server-side and client-side scenarios. ```java return Collections.singletonList(MediaType.parseMediaType("application/vnd-acme-media-type")); ``` -------------------------------- ### Configure WebClient with Spring Boot Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Use WebClientCustomizer to register hypermedia types with Spring Boot's autoconfigured WebClient.Builder. ```java @Bean WebClientCustomizer hypermediaWebClientCustomizer(HypermediaWebClientConfigurer configurer) { return webClientBuilder -> { configurer.registerHypermediaTypes(webClientBuilder); }; } ``` -------------------------------- ### Configure WebTestClient with Spring Boot Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Configure WebTestClient using Spring Boot's test annotations and HypermediaWebTestClientConfigurer for hypermedia support. ```java @SpringBootTest @AutoConfigureWebTestClient class WebClientBasedTests { @Test void exampleTest(@Autowired WebTestClient.Builder builder, @Autowired HypermediaWebTestClientConfigurer configurer) { client = builder.apply(configurer).build(); client.get().uri("/") .exchange() .expectBody(new TypeReferences.EntityModelType() {}) // <4> .consumeWith(result -> { // assert against this EntityModel! }); } } ``` -------------------------------- ### Configure WebTestClient with Spring HATEOAS Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Configure WebTestClient instances for testing hypermedia-enabled representations by applying HypermediaWebTestClientConfigurer. ```java include::{base-dir}/src/test/java/org/springframework/hateoas/config/HypermediaWebTestClientConfigurerTest.java[tag=web-test-client] ``` -------------------------------- ### Customer Controller for Creating Customers Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc A Spring controller demonstrating how to handle POST requests to create customers using the CustomerRepresentation payload. ```java @Controller class CustomerController { @PostMapping("/customers") EntityModel createCustomer(@RequestBody CustomerRepresentation payload) { <1> // … } @GetMapping("/customers") CollectionModel getCustomers() { CollectionModel model = …; CustomerController controller = methodOn(CustomerController.class); ``` -------------------------------- ### Configure RestTemplate with Spring HATEOAS Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Manually configure a RestTemplate instance to speak hypermedia by using HypermediaRestTemplateConfigurer. ```java include::{base-dir}/src/docs/java/org/springframework/hateoas/client/HypermediaConfiguration.java[tag=rest-template] ``` -------------------------------- ### Traverson Basic Traversal Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Demonstrates basic service traversal using Traverson by following relation names and expanding template parameters to retrieve an object's property. ```java Map parameters = new HashMap<>(); parameters.put("user", 27); Traverson traverson = new Traverson(URI.create("http://localhost:8080/api/"), MediaTypes.HAL_JSON); String name = traverson .follow("movies", "movie", "actor").withTemplateParameters(parameters) .toObject("$.name"); ``` -------------------------------- ### Pattern-Based HAL Single-Link Rendering Policy Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Configure HAL single-link rendering using Ant-style path patterns for link relations. ```java @Configuration @EnableWebMvc @EnableHypermediaSupport(type = {HypermediaType.HAL}) public class SampleAppConfiguration { @Bean public HalConfigurationCustomizer halConfigurationCustomizer() { return (halConfiguration) -> halConfiguration.useBinderForPattern("http*", (binder) -> binder.toArrayBinder()); } } ``` -------------------------------- ### UBER+JSON Sample Document Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc A sample JSON document demonstrating the UBER (Uniform Basis for Exchanging Representations) media type structure. ```javascript include::{resource-dir}/docs/mediatype/uber/uber-sample.json[] ``` -------------------------------- ### Using IANA Link Relations Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc Demonstrates how to use predefined IANA link relations with Spring HATEOAS Links and check if a relation is an IANA relation. ```java Link link = Link.of("/some-resource"), IanaLinkRelations.NEXT); assertThat(link.getRel()).isEqualTo(LinkRelation.of("next")); assertThat(IanaLinkRelation.isIanaRel(link.getRel())).isTrue(); ``` -------------------------------- ### Traverson Traversal with Hop Parameters Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Shows how to customize template parameters at each hop during traversal using the static rel(...) function and .withParameter() for URI template variables. ```java include::{base-dir}/src/test/java/org/springframework/hateoas/client/TraversonTest.java[tag=hop-with-param] ``` -------------------------------- ### Enable HAL-FORMS Media Type Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Include this configuration to enable the HAL-FORMS media type. This is typically done in your application's main configuration class. ```java import org.springframework.context.annotation.Configuration; import org.springframework.hateoas.mediatype.hal.forms.HalFormsConfiguration; import org.springframework.context.annotation.Bean; @Configuration public class HalFormsApplication { @Bean HalFormsConfiguration halFormsConfiguration() { return new HalFormsConfiguration(); } } ``` -------------------------------- ### Sample rest-messages.properties for Link Titles Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Defines internationalized titles for HAL link objects using a resource bundle. ```properties _links.cancel.title=Cancel order _links.payment.title=Proceed to checkout ``` -------------------------------- ### Using a Custom Representation Model Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc Instantiate and populate a custom representation model, then add links to it. This model can be returned from controllers to generate HAL+JSON responses. ```java PersonModel model = new PersonModel(); model.firstname = "Dave"; model.lastname = "Matthews"; model.add(Link.of("https://myhost/people/42")); ``` -------------------------------- ### Create Dependency Upgrade Ticket Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc Create a GitHub issue for a dependency upgrade. Assign labels, the assignee, and the milestone based on the current project version. ```bash gh issue create \ --title "Upgrade to Library 1.2.3" \ --body "" \ --label "in: infrastructure,type: dependency-upgrade" \ --assignee "@me" \ --milestone "$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout | sed -e "s/-SNAPSHOT//")" ``` -------------------------------- ### Enable Hypermedia Support for WebMVC Stack Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/configuration.adoc Explicitly activate hypermedia support for a specific web stack, such as Spring WebMVC. This is useful when you want to restrict HATEOAS functionality to a particular stack. ```java @EnableHypermediaSupport(…, stacks = WebStack.WEBMVC) class MyHypermediaConfiguration { … } ``` -------------------------------- ### Using TypedEntityLinks Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Shows how to obtain a TypedEntityLinks instance to centralize identifier extraction logic for a specific entity type. ```java class OrderController { private final TypedEntityLinks links; OrderController(EntityLinks entityLinks) { <1> this.links = entityLinks.forType(Order::getId); <2> } @GetMapping ResponseEntity someMethod(…) { Order order = … // lookup order ``` -------------------------------- ### Create Dependency Upgrade Ticket (Tyinator Shortcut) Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc A Typinator shortcut to create a GitHub issue for a dependency upgrade. It uses placeholders for title, labels, and milestone. ```bash gh issue create \ --title "{{?Title}}" \ --body "" \ --label "{{?Lables}}" \ --assignee "@me" \ --milestone "{{?Version<$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout | sed -e "s/-SNAPSHOT//")>}}" ``` -------------------------------- ### Response with Links Considering Forwarded Headers Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc This JSON response illustrates how Spring HATEOAS generates links that reflect the information provided in the X-Forwarded headers from the request. The links correctly use the 'https' protocol, 'example.com' host, and '9001' port as specified in the request headers. ```javascript { "_embedded": { "employees": [ { "id": 1, "name": "Bilbo Baggins", "role": "burglar", "_links": { "self": { "href": "https://example.com:9001/employees/1" }, "employees": { "href": "https://example.com:9001/employees" } } } ] }, "_links": { "self": { "href": "https://example.com:9001/employees" }, "root": { "href": "https://example.com:9001" } } } ``` -------------------------------- ### CurieProvider Configuration for HAL Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Configures a default CurieProvider to manage compact URIs for link relation types in HAL. ```java @Configuration @EnableWebMvc @EnableHypermediaSupport(type= {HypermediaType.HAL}) public class Config { @Bean public CurieProvider curieProvider() { return new DefaultCurieProvider("ex", new UriTemplate("https://www.example.com/rels/{rel}")); } } ``` -------------------------------- ### Reset Release Branch to Tag (Preview Releases) Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc After a preview release, reset the release branch to the tag created by the Maven release plugin. This is for preview releases. ```bash $ git checkout release/milestone $ git reset --hard 1.3.0-M1 $ git push --force-with-lease ``` -------------------------------- ### Link Relation-Based HAL Single-Link Rendering Policy Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Customize HAL single-link rendering based on specific link relation names. ```java @Configuration @EnableWebMvc @EnableHypermediaSupport(type = {HypermediaType.HAL}) public class SampleAppConfiguration { @Bean public HalConfigurationCustomizer halConfigurationCustomizer() { return (halConfiguration) -> halConfiguration.useBinderForLinkRelation("item", (binder) -> binder.toArrayBinder()) .useBinderForLinkRelation("prev", (binder) -> binder.toObjectBinder()); } } ``` -------------------------------- ### Generate Changelog Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc Generate a changelog file using the Spring IO changelog generator. Provide the release version and the output file name. ```bash $ java -jar $pathToChangelogGenerator 1.2.3 changelog.txt ``` -------------------------------- ### Links with Templated URIs Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc Shows how to use URI templates with Spring HATEOAS Links, including indicating templated status, exposing parameters, and expanding them. ```java include::{code-dir}/FundamentalsTest.java[tags=templatedLinks] ``` -------------------------------- ### Assemble CollectionModel with PersonModel instances Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Use a RepresentationModelAssembler to create a CollectionModel of PersonModel objects. ```java Person person = new Person(…); Iterable people = Collections.singletonList(person); PersonModelAssembler assembler = new PersonModelAssembler(); PersonModel model = assembler.toModel(person); CollectionModel model = assembler.toCollectionModel(people); ``` -------------------------------- ### HAL Representation for Top Collections Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Demonstrates the HAL JSON structure for representing top-level collections, where items are grouped under a link relation derived from their type. ```javascript { "_embedded" : { "order : [ … ] } } ``` -------------------------------- ### Create Custom RepresentationModelAssemblerSupport Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Extend RepresentationModelAssemblerSupport to simplify the creation of resource models with self-links. ```java class PersonModelAssembler extends RepresentationModelAssemblerSupport { public PersonModelAssembler() { super(PersonController.class, PersonModel.class); } @Override public PersonModel toModel(Person person) { PersonModel resource = createResource(person); // … do further mapping return resource; } } ``` -------------------------------- ### Customer Representation Model with HAL-FORMS Annotations Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc A Java class representing a customer, designed to capture input for HAL-FORMS. Includes annotations for regex validation, email format, and date type. ```java class CustomerRepresentation extends RepresentationModel { String name; LocalDate birthdate; <1> @Pattern(regex = "[0-9]{16}") String ccn; <2> @Email String email; <3> } ``` -------------------------------- ### HAL Document with Single Link Rendered as Object Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Default rendering for a single link relation in HAL documents. ```javascript { "_links": { "self": { "href": "/orders/1" } } } ``` -------------------------------- ### Push Git Tags Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc Push all generated Git tags to the remote repository after a release. ```bash $ git push --tags ``` -------------------------------- ### Provide Custom Jackson Module Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Overrides `getJacksonModule()` to provide custom serializers for creating media type-specific representations. ```java return new Jackson2MyMediaTypeModule(); ``` -------------------------------- ### List Property Updates (Tyinator Shortcut) Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc A Typinator shortcut to list Maven dependency property updates, disallowing minor version updates. ```bash mvn versions:display-property-updates -DallowMinorUpdates=false ``` -------------------------------- ### Reset Release Branch to Tag (GA/Service Releases) Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc After a release, reset the release branch to the tag created by the Maven release plugin. This is for General Availability (GA) and service releases. ```bash $ git checkout release/release $ git reset --hard 1.2.3 $ git push --force-with-lease ``` -------------------------------- ### Setting Response Header Location Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Use the link builder to create a URI for a response header, such as the Location header for a created resource. ```java HttpHeaders headers = new HttpHeaders(); headers.setLocation(linkTo(PersonController.class).slash(person).toUri()); return new ResponseEntity(headers, HttpStatus.CREATED); ``` -------------------------------- ### HAL Representation JSON Structure Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Illustrates the JSON structure of a HAL representation built using HalModelBuilder. It shows how links and embedded resources are organized. ```javascript { "_links" : { "self" : { "href" : "…" }, "customer" : { "href" : "/orders/4711/customer" } }, "_embedded" : { "customer" : { … }, "additional" : { … } } } ``` -------------------------------- ### Global HAL Single-Link Rendering Policy Configuration Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Configure Spring HATEOAS to render all single-link relations as arrays globally. ```java @Configuration @EnableWebMvc @EnableHypermediaSupport(type = {HypermediaType.HAL}) public class SampleAppConfiguration { @Bean public HalConfigurationCustomizer halConfigurationCustomizer() { return (halConfiguration) -> halConfiguration.useArrayBinder(); } } ``` -------------------------------- ### Employee Controller PATCH Method for Partial Update Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc This is the implementation of the 'partiallyUpdateEmployee' method, which responds to PATCH requests for partially updating an employee. It's used to define an affordance for the 'self' link. ```java include::{code-dir}/EmployeeController.java[tag=patch] ``` -------------------------------- ### Injecting and Using EntityLinks in a Controller Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Illustrates how to inject EntityLinks into a Spring MVC controller and use it to generate links to item resources. ```java @Controller class PaymentController { private final EntityLinks entityLinks; PaymentController(EntityLinks entityLinks) { <1> this.entityLinks = entityLinks; } @PutMapping(…) ResponseEntity payment(@PathVariable Long orderId) { Link link = entityLinks.linkToItemResource(Order.class, orderId); <2> … } } ``` -------------------------------- ### Employee Controller PUT Method for Update Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc This is the implementation of the 'updateEmployee' method, which responds to PUT requests for updating an employee. It's used to define an affordance for the 'self' link. ```java include::{code-dir}/EmployeeController.java[tag=put] ``` -------------------------------- ### Enable Collection+JSON Media Type Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Configure your Spring application to respond to Collection+JSON requests. This involves setting up the necessary components to handle the 'application/vnd.collection+json' media type. ```java include::{code-dir}/CollectionJsonApplication.java[tag=code] ``` -------------------------------- ### JSON:API Gradle Coordinates Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Add the JSON:API dependency to your Gradle project. ```gradle implementation 'com.toedter:spring-hateoas-jsonapi:{see project page for current version}' ``` -------------------------------- ### Wrap Existing Objects with EntityModel Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc Use EntityModel.of() to wrap an existing object, providing a convenient way to represent a single resource backed by a singular object. ```java Person person = new Person("Dave", "Matthews"); EntityModel model = EntityModel.of(person); ``` -------------------------------- ### Process Hypermedia Representations with PaymentProcessor Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Implement RepresentationModelProcessor to add or modify hypermedia representations after assembly, like adding payment links to order resources. ```java include::{code-dir}/PaymentProcessor.java[tag=code] ``` -------------------------------- ### Siren Gradle Coordinates Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Add the Siren dependency to your Gradle project. ```gradle implementation 'de.ingogriebsch.hateoas:spring-hateoas-siren:{see project page for current version}' ``` -------------------------------- ### HAL Document with Single Link Rendered as Array Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Alternative rendering for a single link relation in HAL documents, presented as an array. ```javascript { "_links": { "self": [ { "href": "/orders/1" } ] } } ``` -------------------------------- ### Using Identifier Extractor Function Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Demonstrates externalizing identifier extraction into a reusable Function for cleaner link generation. ```java Function idExtractor = Order::getId; <1> entityLinks.linkToItemResource(order, idExtractor); <2> ``` -------------------------------- ### Reporting Problem Details with Spring HATEOAS Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc This Java code demonstrates how to report problem details using Spring HATEOAS' `Problem` type in a Spring MVC Controller. It shows creating a `Problem` instance and setting default and custom properties. ```java include::{code-dir}/mediatype/problem/PaymentController.java[tags=header;method;footer] ``` -------------------------------- ### Building Link to Collection Resource Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Create a link to a collection resource using WebMvcLinkBuilder by referencing the controller class. ```java import static org.sfw.hateoas.server.mvc.WebMvcLinkBuilder.*; Link link = linkTo(PersonController.class).withRel("people"); assertThat(link.getRel()).isEqualTo(LinkRelation.of("people")); assertThat(link.getHref()).endsWith("/people"); ``` -------------------------------- ### Wrap Collections with CollectionModel Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc Use CollectionModel.of() to wrap a collection of objects, suitable for representing resources that are conceptually collections. ```java Collection people = Collections.singleton(new Person("Dave", "Matthews")); CollectionModel model = CollectionModel.of(people); ``` -------------------------------- ### Commit Dependency Update and Close Ticket Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc Commit the dependency update, push the changes, and close the corresponding GitHub issue. ```bash git add . \ && git commit -m "GH-4711 - Upgrade to Library 1.2.3." \ && git push \ && gh issue close 4711 ``` -------------------------------- ### Traverson Deserializing CollectionModel Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Demonstrates how to deserialize a HAL collection into a CollectionModel using Traverson by specifying a CollectionModelType. ```java CollectionModelType collectionModelType = new TypeReferences.CollectionModelType() {}; CollectionModel itemResource = traverson.// follow(rel("items")).// toObject(collectionModelType); ``` -------------------------------- ### Display Maven Dependency Updates (Bugfix Branches) Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc On bugfix branches, display potential dependency updates, disallowing minor version updates. ```bash $ mvn versions:display-property-updates -DallowMinorUpdates=false ``` -------------------------------- ### Register Payment Processor Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Register a RepresentationModelProcessor to add links to Order entities. This processor is applied to EntityModel objects. ```java package com.example.payment; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.server.RepresentationModelProcessor; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; @Configuration public class PaymentProcessingApp { @Bean RepresentationModelProcessor> orderLinksAssembler() { return assembler -> { //<1> Manipulate the existing EntityModel object by adding an unconditional link. assembler.add(Link.of("/orders/1/payments").withRel("payments")); //<2> Return the EntityModel so it can be serialized into the requested media type. }; } } ``` -------------------------------- ### Building Nested Link with ID Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Construct a nested link to a specific resource by appending its ID to the base URI derived from the controller. ```java Person person = new Person(1L, "Dave", "Matthews"); // /person / 1 Link link = linkTo(PersonController.class).slash(person.getId()).withSelfRel(); assertThat(link.getRel(), is(IanaLinkRelation.SELF.value())); assertThat(link.getHref(), endsWith("/people/1")); ``` -------------------------------- ### HAL-FORMS Template Definition Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc This JSON snippet shows a HAL-FORMS template, including a title, method, and properties with their types, requirements, and constraints. It's generated when a client requests HAL-FORMS media type. ```json { ..., "_templates" : { "default" : { "title" : "Create customer", "method" : "post", "properties" : [ { "name" : "name", "required" : true, "type" : "text" } , { "name" : "birthdate", "required" : true, "type" : "date" } , { "name" : "ccn", "prompt" : "Credit card number", "placeholder" : "1234123412341234" "required" : true, "regex" : "[0-9]{16}", "type" : "text" } , { "name" : "email", "prompt" : "Email", "required" : true, "type" : "email" } ] } } } ``` -------------------------------- ### JSON:API Maven Coordinates Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Add the JSON:API dependency to your Maven project. ```xml com.toedter spring-hateoas-jsonapi {see project page for current version} ``` -------------------------------- ### LinkDiscoverer HAL Link Finding Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Shows how to use a HalLinkDiscoverer to find a link with a specific relation type within a JSON string. ```java String content = "{'_links' : { 'foo' : { 'href' : '/foo/bar' }}}"; LinkDiscoverer discoverer = new HalLinkDiscoverer(); Link link = discoverer.findLinkWithRel("foo", content); assertThat(link.getRel(), is("foo")); assertThat(link.getHref(), is("/foo/bar")); ``` -------------------------------- ### Declare Custom LinkDiscoverer Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Declares a custom `LinkDiscoverer` implementation for further client-side support. ```java return new MyLinkDiscoverer(); ``` -------------------------------- ### Register Hypermedia Types with RestTemplateCustomizer Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/client.adoc Defines a Spring bean that customizes RestTemplate to register hypermedia types. This is useful when you need a RestTemplate instance that can interact using hypermedia. ```java @Bean // <4> RestTemplateCustomizer hypermediaRestTemplateCustomizer(HypermediaRestTemplateConfigurer configurer) { // <1> return restTemplate -> { // <2> configurer.registerHypermediaTypes(restTemplate); // <3> }; } ``` -------------------------------- ### Display Maven Dependency Updates (Main Branch) Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc On the main branch, display potential dependency updates, disallowing major version updates. Skip the trailing property if a major version update is being considered. ```bash $ mvn versions:display-property-updates -DallowMajorUpdates=false ``` -------------------------------- ### Declare Custom EntityLinks Implementation Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc Register a custom EntityLinks implementation as a Spring bean to extend hypermedia support. ```java @Configuration class CustomEntityLinksConfiguration { @Bean MyEntityLinks myEntityLinks(…) { return new MyEntityLinks(…); } } ``` -------------------------------- ### Register Custom Pattern for HAL-FORMS Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Customizes HAL-FORMS metadata by registering a specific regex pattern for a given class. This is useful for types that cannot be annotated directly. ```java @Configuration class CustomConfiguration { @Bean HalFormsConfiguration halFormsConfiguration() { HalFormsConfiguration configuration = new HalFormsConfiguration(); configuration.registerPatternFor(CreditCardNumber.class, "[0-9]{16}"); } } ``` -------------------------------- ### Siren Maven Coordinates Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Add the Siren dependency to your Maven project. ```xml de.ingogriebsch.hateoas spring-hateoas-siren {see project page for current version} compile ``` -------------------------------- ### Enable UBER+JSON Media Type Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Configure your Spring application to respond to UBER+JSON requests. This involves setting up the necessary components to handle the 'application/vnd.amundsen-uber+json' media type. ```java include::{code-dir}/UberApplication.java[tag=code] ``` -------------------------------- ### Configure Git Comment Character Source: https://github.com/spring-projects/spring-hateoas/blob/main/README.adoc Configure your Git clone to use '/' as the comment character. This is necessary to prevent Git from treating commits with GitHub issue references as comments. ```git git config core.commentchar "/" ``` -------------------------------- ### Commit Dependency Update and Close Ticket (Tyinator Shortcut) Source: https://github.com/spring-projects/spring-hateoas/blob/main/etc/release.adoc A Typinator shortcut to commit a dependency update, push changes, and close a GitHub issue. It uses placeholders for ticket ID and title. ```bash git add . \ && git commit -m "GH-{{ticketId=?Ticket ID<>}}{{ticketId}} - {{?Title}}. " \ && git push \ && gh issue close {{ticketId}} ``` -------------------------------- ### HAL Representation of Person Model Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc The resulting HAL+JSON representation for the PersonModel, including links and properties, when an appropriate Accept header is provided. ```javascript { "_links" : { "self" : { "href" : "https://myhost/people/42" } }, "firstname" : "Dave", "lastname" : "Matthews" } ``` -------------------------------- ### Explicitly Embed Empty Collection with Type Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Shows how to explicitly communicate an empty collection in HAL by providing a type to the embed method. This ensures the `_embedded` field is rendered with its link relation, even if the collection is empty. ```java HalModelBuilder.emptyHalModel() .embed(Collections.emptyList(), Order.class); // or .embed(Collections.emptyList(), LinkRelation.of("orders")); ``` -------------------------------- ### Define a Custom Representation Model Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc Define a custom representation model by extending RepresentationModel and adding properties. This allows for self-typing with RepresentationModel.add(). ```java class PersonModel extends RepresentationModel { String firstname, lastname; } ``` -------------------------------- ### Embed Collection into HAL Document Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc Programmatically embed a collection of objects into a HAL document using HalModelBuilder. If the collection is empty, the document will remain empty unless a type is explicitly provided. ```java Collection orders = …; HalModelBuilder.emptyHalDocument() .embed(orders); ``` -------------------------------- ### Associate Affordances with a Self Link Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc This snippet shows how to attach affordances for 'update' and 'partially update' operations to a 'self' link. It uses the Link Builder API to point to controller methods that handle these operations. ```java include::{code-dir}/EmployeeController.java[tag=get] ``` -------------------------------- ### Using Dedicated Type for Extended Problem Properties Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc This Java code snippet illustrates using a dedicated type to capture extended problem properties when creating a `Problem` instance in Spring HATEOAS. It shows declaring a type and populating an instance. ```java using a dedicated type to capture extended problem properties [source, java, indent=0] ---- ``` -------------------------------- ### Registering ForwardedHeaderTransformer for Spring WebFlux Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc This Java code snippet demonstrates registering Spring's ForwardedHeaderTransformer as a Spring bean for Spring WebFlux applications. This component transforms reactive web requests to process X-Forwarded headers, enabling proper link generation in cloud or proxied environments. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.client.ExchangeFilterFunction; @Configuration public class ForwardedEnabledConfig { @Bean public ExchangeFilterFunction forwardedHeaderTransformer() { return (request, next) -> next.exchange(request); } } ``` -------------------------------- ### Explicit Empty Collection HAL JSON Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/mediatypes.adoc The resulting HAL JSON when an empty collection is explicitly embedded with a type, showing the `_embedded` field with an empty array. ```javascript { "_embedded" : { "orders" : [] } } ``` -------------------------------- ### CollectionModel with Fallback Type Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/fundamentals.adoc Add a fallback type to a CollectionModel, especially useful when the underlying collection might be empty, to preserve type information due to Java's type erasure. ```java Iterable people = repository.findAll(); var model = CollectionModel.of(people).withFallbackType(Person.class); ``` -------------------------------- ### Registering ForwardedHeaderFilter for Spring MVC Source: https://github.com/spring-projects/spring-hateoas/blob/main/src/main/asciidoc/server.adoc This Java code snippet shows how to register Spring's ForwardedHeaderFilter as a Spring bean to enable forwarded header handling for Spring MVC applications. This filter processes X-Forwarded headers to correctly generate base URIs. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.ForwardedHeaderFilter; @Configuration public class ForwardedEnabledConfig { @Bean public ForwardedHeaderFilter forwardedHeaderFilter() { return new ForwardedHeaderFilter(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.