Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#1074 - Add option to register additional media types for HAL and HAL-FORMS. #1077

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,15 @@
import lombok.Getter;
import lombok.experimental.Wither;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkRelation;
import org.springframework.http.MediaType;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
Expand All @@ -47,6 +50,7 @@ public class HalConfiguration {
*/
private final @Wither @Getter RenderSingleLinks renderSingleLinks;
private final @Wither(AccessLevel.PRIVATE) Map<String, RenderSingleLinks> singleLinksPerPattern;
private final @Getter List<MediaType> additionalMediaTypes = new ArrayList<>();

/**
* Creates a new default {@link HalConfiguration} rendering single links as immediate sub-document.
Expand Down Expand Up @@ -122,4 +126,16 @@ public enum RenderSingleLinks {
*/
AS_ARRAY
}

/**
* Register other {@link MediaType}s this one should response to.
*
* @param mediatype
* @return HalFormsConfiguration with new {@link MediaType} added
*/
public HalConfiguration withAdditionalMediatype(MediaType mediatype) {

this.additionalMediaTypes.add(mediatype);
return this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package org.springframework.hateoas.mediatype.hal;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.ObjectProvider;
Expand Down Expand Up @@ -71,7 +72,10 @@ LinkDiscoverer halLinkDisocoverer() {
*/
@Override
public List<MediaType> getMediaTypes() {
return HypermediaType.HAL.getMediaTypes();

List<MediaType> mediaTypes = new ArrayList<>(HypermediaType.HAL.getMediaTypes());
this.halConfiguration.ifAvailable(halConfig -> mediaTypes.addAll(halConfig.getAdditionalMediaTypes()));
return mediaTypes;
}

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.springframework.core.ResolvableType;
import org.springframework.hateoas.mediatype.hal.HalConfiguration;
import org.springframework.http.MediaType;

/**
* HAL-FORMS specific configuration extension of {@link HalConfiguration}.
Expand Down Expand Up @@ -60,4 +62,20 @@ public HalFormsConfiguration registerPattern(Class<?> type, String pattern) {
Optional<String> getTypePatternFor(ResolvableType type) {
return Optional.ofNullable(patterns.get(type.resolve(Object.class)));
}

/**
* Register other {@link MediaType}s this one should response to.
*
* @param mediatype
* @return HalFormsConfiguration
*/
public HalFormsConfiguration withAdditionalMediatype(MediaType mediatype) {

this.halConfiguration.getAdditionalMediaTypes().add(mediatype);
return this;
}

public Collection<? extends MediaType> getAdditionalMediaTypes() {
return this.halConfiguration.getAdditionalMediaTypes();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.ObjectProvider;
Expand Down Expand Up @@ -61,7 +62,10 @@ LinkDiscoverer halFormsLinkDiscoverer() {
*/
@Override
public List<MediaType> getMediaTypes() {
return HypermediaType.HAL_FORMS.getMediaTypes();

List<MediaType> mediaTypes = new ArrayList<>(HypermediaType.HAL_FORMS.getMediaTypes());
this.halFormsConfiguration.ifAvailable(halFormsConfig -> mediaTypes.addAll(halFormsConfig.getAdditionalMediaTypes()));
return mediaTypes;
}

/*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* Copyright 2017 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
*
* https://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.mediatype.hal;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsCollectionWithSize.*;
import static org.springframework.hateoas.support.JsonPathUtils.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.config.EnableHypermediaSupport;
import org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType;
import org.springframework.hateoas.config.WebClientConfigurer;
import org.springframework.hateoas.support.MappingUtils;
import org.springframework.hateoas.support.WebFluxEmployeeController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.config.EnableWebFlux;

/**
* @author Greg Turnquist
*/
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration
class HalHandleApplicationJsonWebFluxIntegrationTest {

@Autowired WebTestClient testClient;

@BeforeEach
void setUp() {
WebFluxEmployeeController.reset();
}

/**
* @see #728
*/
@Test
void singleEmployee() {

this.testClient.get().uri("http://localhost/employees/0").accept(MediaType.APPLICATION_JSON).exchange()

.expectStatus().isOk() //
.expectHeader().contentType(MediaType.APPLICATION_JSON) //
.expectBody(String.class)//

.value(jsonPath("$.name", is("Frodo Baggins"))) //
.value(jsonPath("$.role", is("ring bearer"))) //

.value(jsonPath("$._links.*", hasSize(2))) //
.value(jsonPath("$._links['self'].href", is("http://localhost/employees/0"))) //
.value(jsonPath("$._links['employees'].href", is("http://localhost/employees")));
}

/**
* @see #728
*/
@Test
void collectionOfEmployees() {

this.testClient.get().uri("http://localhost/employees").accept(MediaType.APPLICATION_JSON).exchange().expectStatus()
.isOk().expectHeader().contentType(MediaType.APPLICATION_JSON).expectBody(String.class)
.value(jsonPath("$._embedded.employees[0].name", is("Frodo Baggins")))
.value(jsonPath("$._embedded.employees[0].role", is("ring bearer")))
.value(jsonPath("$._embedded.employees[0]._links['self'].href", is("http://localhost/employees/0")))
.value(jsonPath("$._embedded.employees[1].name", is("Bilbo Baggins")))
.value(jsonPath("$._embedded.employees[1].role", is("burglar")))
.value(jsonPath("$._embedded.employees[1]._links['self'].href", is("http://localhost/employees/1")))

.value(jsonPath("$._links.*", hasSize(1)))
.value(jsonPath("$._links['self'].href", is("http://localhost/employees")));
}

/**
* @see #728
*/
@Test
void createNewEmployee() throws Exception {

String specBasedJson = MappingUtils.read(new ClassPathResource("new-employee.json", getClass()));

this.testClient.post().uri("http://localhost/employees").contentType(MediaType.APPLICATION_JSON)
.bodyValue(specBasedJson) //
.exchange() //
.expectStatus().isCreated() //
.expectHeader().valueEquals(HttpHeaders.LOCATION, "http://localhost/employees/2");
}

@Configuration
@EnableWebFlux
@EnableHypermediaSupport(type = { HypermediaType.HAL })
static class TestConfig {

@Bean
WebFluxEmployeeController employeeController() {
return new WebFluxEmployeeController();
}

@Bean
WebTestClient webTestClient(WebClientConfigurer webClientConfigurer, ApplicationContext ctx) {

return WebTestClient.bindToApplicationContext(ctx).build().mutate()
.exchangeStrategies(webClientConfigurer.hypermediaExchangeStrategies()).build();
}

@Bean
HalConfiguration halConfiguration() {
return new HalConfiguration().withAdditionalMediatype(MediaType.APPLICATION_JSON);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.mediatype.hal;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsCollectionWithSize.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.hateoas.config.EnableHypermediaSupport;
import org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType;
import org.springframework.hateoas.support.MappingUtils;
import org.springframework.hateoas.support.WebMvcEmployeeController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
* @author Greg Turnquist
*/
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration
class HalHandleApplicationJsonWebMvcIntegrationTest {

@Autowired WebApplicationContext context;

MockMvc mockMvc;

@BeforeEach
void setUp() {

this.mockMvc = webAppContextSetup(this.context).build();
WebMvcEmployeeController.reset();
}

@Test
void singleEmployee() throws Exception {

this.mockMvc.perform(get("/employees/0").accept(MediaType.APPLICATION_JSON)) //

.andExpect(status().isOk()) //
.andExpect(jsonPath("$.name", is("Frodo Baggins"))) //
.andExpect(jsonPath("$.role", is("ring bearer")))

.andExpect(jsonPath("$._links.*", hasSize(2)))
.andExpect(jsonPath("$._links['self'].href", is("http://localhost/employees/0")))
.andExpect(jsonPath("$._links['employees'].href", is("http://localhost/employees")));
}

@Test
void collectionOfEmployees() throws Exception {

this.mockMvc.perform(get("/employees").accept(MediaType.APPLICATION_JSON)) //
.andExpect(status().isOk()) //
.andExpect(jsonPath("$._embedded.employees[0].name", is("Frodo Baggins")))
.andExpect(jsonPath("$._embedded.employees[0].role", is("ring bearer")))
.andExpect(jsonPath("$._embedded.employees[0]._links['self'].href", is("http://localhost/employees/0")))
.andExpect(jsonPath("$._embedded.employees[1].name", is("Bilbo Baggins")))
.andExpect(jsonPath("$._embedded.employees[1].role", is("burglar")))
.andExpect(jsonPath("$._embedded.employees[1]._links['self'].href", is("http://localhost/employees/1")))

.andExpect(jsonPath("$._links.*", hasSize(1)))
.andExpect(jsonPath("$._links['self'].href", is("http://localhost/employees")));
}

@Test
void createNewEmployee() throws Exception {

String specBasedJson = MappingUtils.read(new ClassPathResource("new-employee.json", getClass()));

this.mockMvc.perform(post("/employees") //
.content(specBasedJson) //
.contentType(MediaType.APPLICATION_JSON_VALUE)) //
.andExpect(status().isCreated())
.andExpect(header().stringValues(HttpHeaders.LOCATION, "http://localhost/employees/2"));
}

@Configuration
@EnableWebMvc
@EnableHypermediaSupport(type = HypermediaType.HAL)
static class TestConfig {

@Bean
WebMvcEmployeeController employeeController() {
return new WebMvcEmployeeController();
}

@Bean
HalConfiguration halFormsConfiguration() {
return new HalConfiguration().withAdditionalMediatype(MediaType.APPLICATION_JSON);
}

}

@Configuration
@EnableHypermediaSupport(type = HypermediaType.HAL)
static class WithHalConfiguration {

static final HalConfiguration CONFIG = new HalConfiguration().withAdditionalMediatype(MediaType.APPLICATION_JSON);

@Bean
public HalConfiguration halConfiguration() {
return CONFIG;
}
}
}
Loading