How add a new _link to an entity using spring data rest? - spring

I want to add an extra link to a entity such as:
"_links": {
"self": {
"href": "http://localhost:8080/api/organizaciones"
},
"profile": {
"href": "http://localhost:8080/api/profile/organizaciones"
},
"search": {
"href": "http://localhost:8080/api/organizaciones/search"
},
"disable": {
"href": "http://localhost:8080/api/organizaciones/disable"
}
}
The idea behind this scenario is that I need to expose a soft delete via its own link within Organizacion entity... right now I'm only able to do:
http://localhost:8080/api/organizaciones/search/disable?id=100
in order to perform the soft delete. How can I achieve this the right way? Or is it my only alternative creating a controller?

You just need to add a class extending the ResourceProcessor interface and add it to the spring-context(http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_the_resourceprocessor_interface)
For example
#Bean
public ResourceProcessor<Resource<Person>> personProcessor() {
return new ResourceProcessor<Resource<Person>>() {
#Override
public Resource<Person> process(Resource<Person> resource) {
resource.add(new Link("http://localhost:8080/people", "added-link"));
return resource;
}
};
}
Where the Person entity can be replaced with your Organizacion entity.

I finally figured it out, I did what was mentioned by Alex in a comment.
I have to give credit to the father of spring-data-rest to #olivergieke I checked one of his examples, more precise: restbucks
First created the following component
#Component
#RequiredArgsConstructor
public class OrganizacionResourceProcessor implements ResourceProcessor<Resource<Organizacion>>{
private static final String DISABLE_REL = "deshabilitar";
private static final String ENABLE_REL = "habilitar";
private final #NonNull EntityLinks entityLinks;
#Override
public Resource<Organizacion> process(Resource<Organizacion> resource) {
Organizacion organizacion = resource.getContent();
if(organizacion.isEnabled()){
resource.add(entityLinks.linkForSingleResource(Organizacion.class, organizacion.getId()).slash(DISABLE_REL).withRel(DISABLE_REL));
}
if(organizacion.isDisabled()){
resource.add(entityLinks.linkForSingleResource(Organizacion.class, organizacion.getId()).slash(ENABLE_REL).withRel(ENABLE_REL));
}
return resource;
}
}
Then created the controller to support those two operations...
#RepositoryRestController
#RequestMapping("/organizaciones")
#ExposesResourceFor(Organizacion.class)
#RequiredArgsConstructor
#Slf4j
#Transactional
public class OrganizacionController {
private final #NonNull OrganizacionRepository organizacionRepository;
private final #NonNull EntityLinks entityLinks;
#GetMapping(value="/{id}/habilitar")
public ResponseEntity<?> desactivarOrganizacion(#PathVariable("id") Long id) {
Preconditions.checkNotNull(id);
Organizacion organizacion = organizacionRepository.findOne(id);
if(organizacion == null){
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
organizacion.setEstado(Estado.DESHABILITADO);
Organizacion pOrg = this.organizacionRepository.save(organizacion);
HttpHeaders header = new HttpHeaders();
header.setLocation(this.entityLinks.linkForSingleResource(Organizacion.class, pOrg.getId()).toUri());//construimos el URL
return new ResponseEntity<Void>(header,HttpStatus.CREATED);
}
#GetMapping(value="/{id}/deshabilitar")
public ResponseEntity<?> activarOrganizacion(#PathVariable("id") Long id){
Preconditions.checkNotNull(id);
Organizacion organizacion = organizacionRepository.findOne(id);
if(organizacion == null){
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
organizacion.setEstado(Estado.ACTIVO);
Organizacion pOrg = this.organizacionRepository.save(organizacion);
HttpHeaders header = new HttpHeaders();
header.setLocation(this.entityLinks.linkForSingleResource(Organizacion.class, pOrg.getId()).toUri());//construimos el URL
return new ResponseEntity<Void>(header,HttpStatus.CREATED);
}
}
and that was it.
This was originally added to Revision 3 of the question.

Related

HATEOAS - links are added on every single request

I have a rest API for class Tag, and want to add a link for each object.
but the duplicate link is added on every request(which calls the findAll() method).
see the pictures below
tag after first request
tag after many requests
What should I change to make it appear only once?
Model -
public class Tag extends RepresentationModel<Tag> {
...
}
Controller -
#RestController
#RequestMapping("tags")
public class TagController {
private final TagService tagService;
#Autowired
public TagController(TagService tagService) {
this.tagService = tagService;
}
#GetMapping()
public ResponseEntity<List<Tag>> findAll() {
List<Tag> tags = this.tagService.findAll();
List<Tag> response = new ArrayList<>();
for(Tag t : tags) {
t.add(linkTo(methodOn(TagController.class).find(t.getId())).withSelfRel());
response.add(t);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
#GetMapping("/{id}")
public ResponseEntity<Tag> find(#PathVariable("id") Long id) {
return ResponseEntity.ok(this.tagService.find(id));
}

Dynamically replacing values in JSON response with Spring Boot and Thymeleaf

Using Spring Boot I'd like to implement a mock service for an external API. As this mock is only used for testing, I'd like to keep things as simple as possible. The external API returns a JSON similar to this one:
{
"customer": {
"email": "foo#bar.com"
},
"result": {
"status_code": 100
},
"transaction": {
"amount": 100,
"currency": "EUR",
"order_no": "123456"
}
}
And the controller:
#Value("classpath:/sample.json")
private Resource sampleResource;
#GetMapping(value = "/api")
public String mockMethod() throws IOException {
final InputStream inputStream = sampleResource.getInputStream();
final String sampleResourceString = StreamUtils.copyToString(sampleResource, StandardCharsets.UTF_8);
return sampleResourceString;
}
So basically, the application loads a JSON string from a file and returns it in the response. Now I'd like to replace the amount and the order_no in the JSON with a dynamic value, like this:
{
"customer": {
"email": "foo#bar.com"
},
"result": {
"status_code": 100
},
"transaction": {
"amount": ${amount},
"currency": "EUR",
"order_no": "${orderNumber}"
}
}
My first idea was to use Thymeleaf for this, so I created the following configuration:
#Configuration
#RequiredArgsConstructor
public class TemplateConfiguration {
private final ApplicationContext applicationContext;
#Bean
public SpringResourceTemplateResolver templateResolver() {
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/templates");
templateResolver.setSuffix(".json");
templateResolver.setTemplateMode(TemplateMode.TEXT);
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
}
But I'm stuck how I can actually "run" the templating so that the sampleResourceString is replaced with the dynamic values.
Or is Thymeleaf maybe actually some kind of "overkill" for this?
Maybe just use String.replace() ?
#GetMapping(value = "/api")
public String mockMethod() throws IOException {
final InputStream inputStream = sampleResource.getInputStream();
final String sampleResourceString = StreamUtils.copyToString(sampleResource, StandardCharsets.UTF_8);
String replacedString = sampleResourceString.replace("${amount}", ...)
.replace("${orderNumber}", ...);
return replacedString;
}
Considering that the JSON has quite a simple structure, I would map them out to classes and use Jackson. For example:
public class DummyResponse {
private DummyResponseCustomer customer;
private DummyResponseTransaction transaction;
private DummyResponseResult result;
// TODO: Getters + Setters + ...
}
public class DummyResponseTransaction  {
private BigDecimal amount;
private String currency;
#JsonProperty("order_no")
private String orderNumber;
// TODO: Getters + Setters + ...
}
And then you could write a controller like this:
#ResponseBody // You need the #ResponseBody annotation or annotate the controller with #RestController
#GetMapping(value = "/api")
public DummyResponse mockMethod() {
return new DummyResponse(
new DummyResponseCustomer("foo#bar.com"),
new DummyResponseResult(100),
new DummyResponseTransaction(new BigDecimal("100"), "EUR", "123456")
);
}
This makes it fairly easy to come up with dynamic values and without having to use a templating engine (like Thymeleaf) or having to handle I/O. Besides that, you probably have these classes somewhere already to consume the external API.

Spring boot consume 2 rest and merge some fields

Im new to Spring Boot and got a problem were i need to consume 2 remote Rest services and merge the results. Would need some insight on the right approach.
I got something like this:
{"subInventories":[
{"OrganizationId": 0,
"OrganizationCode":"",
"SecondaryInventoryName":"",
"Description":""},...{}...],
{"organizations":[
{"OrganizationId":0,
"OrganizationCode":"",
"OrganizationName":"",
"ManagementBusinessUnitId":,
"ManagementBusinessUnitName":""}, ...{}...]}
and need to make it into something like this:
{"items":[
{"OrganizationId":0,
"OrganizationCode":"",
"OrganizationName":"",
"ManagementBusinessUnitId":0,
"ManagementBusinessUnitName":"",
"SecondaryInventoryName":"",
"Description":""},...{}...]
got 2 #Entitys to represent each item, Organizations and Inventories with the attributtes like the JSON fields.
EDIT
Currently trying to get matches with Java8 stream()
#GetMapping("/manipulate")
public List<Organization> getManipulate() {
List<Organization> organization = (List<Organization>)(Object) organizationController.getOrganization();
List<SubInventories> subInventories = (List<SubInventories>)(Object) getSuvInventories();
List<Organization> intersect = organization.stream().filter(o -> subInventories.stream().anyMatch(s -> s.getOrganizationId()==o.getOrganizationId()))
.collect(Collectors.toList());
return intersect;
}
found this searching but i got many classes and I don't know if it would be better to just for each organization get the subinventories and put them in a list of maps like
List<Map<String,Object> myList = new ArrayList<>();
//Loops here
Map<String,Object> a = new HashMap<>();
a.put("OrganizationID", 1231242415)...
myList.add(a)
Quite lost in what the right approach is.
EDIT2
Here the classes I'm using.
Organizations
#Entity
#JsonAutoDetect(fieldVisibility = Visibility.ANY)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Organization implements Serializable{
//#JsonObject("OrganizationId")
#Id
private Long OrganizationId;
private Long ManagementBusinessUnitId;
private String OrganizationCode,OrganizationName,ManagementBusinessUnitName;
public Organization() {
}
//getters setters
}
SubInventories
#Entity
#JsonAutoDetect(fieldVisibility = Visibility.ANY)
#JsonIgnoreProperties(ignoreUnknown = true)
public class SubInventories implements Serializable{
#Id
private Long OrganizationId;
private String OrganizationCode,SecondaryInventoryName,Description;
public SubInventories() {
}
//getters and setters
}
Wrapper to unwrapp consume
#JsonAutoDetect(fieldVisibility = Visibility.ANY)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Wrapper {
//#JsonProperty("items")
private List<Object> items;
public Wrapper() {
}
public List<Object> getOrganization() {
return items;
}
public void setOrganization(List<Object> organization) {
this.items = organization;
}
}
OrganizationController
#RestController
public class OrganizationController {
#Autowired
private RestTemplate restTemplate;
#Autowired
private Environment env;
#GetMapping("/organizations")
public List<Object> getOrganization() {
return getOrganizationInfo();
}
private List<Object> getOrganizationInfo() {
String url = env.getProperty("web.INVENTORY_ORGANIZATIONS");
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
builder.queryParam("fields", "OrganizationId,OrganizationCode,OrganizationName,ManagementBusinessUnitId,ManagementBusinessUnitName");
builder.queryParam("onlyData", "true");
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(env.getProperty("authentication.name"),env.getProperty("authentication.password"));
HttpEntity request = new HttpEntity(headers);
ResponseEntity<Wrapper> temp = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, request, new ParameterizedTypeReference<Wrapper>() {});
List<Object> data = temp.getBody().getOrganization();
return data;
}
}
SubInventoryController
#RestController
public class SubInventoryController {
#Autowired
private RestTemplate restTemplate;
#Autowired
private Environment env;
#GetMapping("/sub")
public List<Object> getSuvInventories() {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("this is private :(");
builder.queryParam("onlyData", "true");
builder.queryParam("expand", "subinventoriesDFF");
builder.queryParam("limit", "999999");
builder.queryParam("fields", "OrganizationId,OrganizationCode,SecondaryInventoryName,Description");
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(env.getProperty("authentication.name"),env.getProperty("authentication.password"));
headers.set("REST-Framework-Version", "2");
HttpEntity request = new HttpEntity(headers);
ResponseEntity<Wrapper> subInventories = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, request, new ParameterizedTypeReference<Wrapper>() {});
List<Object> data = subInventories.getBody().getOrganization();
return data;
}
}
where I'm right now
#RestController
public class MainController {
#Autowired
private RestTemplate restTemplate;
#Autowired
private Environment env;
#Autowired
private OrganizationController organizationController;
#Autowired
private SubInventoryController subInventoryController;
#GetMapping("/manipulate")
public Map<Organization, List<SubInventories>> getManipulate() {
List<Organization> organizations = (List<Organization>)(Object) organizationController.getOrganization();
List<SubInventories> subInventories = (List<SubInventories>)(Object) subInventoryController.getSuvInventories();
Map<Organization,List<SubInventories>> result = new HashMap<Organization,List<SubInventories>>();
for(Organization organization : organizations) {
List<SubInventories> subInventoryMatched = (List<SubInventories>) subInventories.stream().filter( s -> s.getOrganizationId()== organization.getOrganizationId()).collect(Collectors.toList());
result.put(organizations.get(0), subInventoryMatched);
}
return result;
}
}
From what I understand I need to make a wrapper class for each POJO cause the response looks like this
/organizations
{
"items": [
{
"OrganizationId": 1,
"OrganizationCode": "adasd",
"OrganizationName": "Hotel Bahía Príncipe Sunlight Costa Adeje",
"ManagementBusinessUnitId": 131231,
"ManagementBusinessUnitName": "asdasfdas"
},
{
"OrganizationId": 2,
"OrganizationCode": "adadas",
"OrganizationName": "Hadasd",
"ManagementBusinessUnitId": 1231,
"ManagementBusinessUnitName": "aewfrqaew"
}]}
and /subInventories
{
"items": [
{
"OrganizationId": 1,
"OrganizationCode": "asada",
"SecondaryInventoryName": "adfasdfasdgf",
"Description": "pub"
},
{
"OrganizationId": 2,
"OrganizationCode": "asgfrgtsdh",
"SecondaryInventoryName": "B LOB",
"Description": "pub2"
}
]}
If used the generic one with Object I get a java.lang.ClassCastException: java.util.LinkedHashMap incompatible with com.demo.model.Organization in the stream().filter and for the merge of the fields another class to get the desired
{
"items": [
{
"OrganizationId": 1,
"OrganizationCode": "asdas",
"OrganizationName": "adsadasd",
"ManagementBusinessUnitId": 1,
"ManagementBusinessUnitName": "asdasdf",
"SecondaryInventoryName": "sfsdfsfa",
"Description": "pub1"
}]}
Tons of classes if i get lots of POJO
I assume the following from the information you provide:
You have two Datatypes (Java classes). They should be merged together to one Java class
You have to load this data from different sources
Non of the classes are leading
I can provide you some example code. The code is based on the previos adoptions. This will give you an idea. It's not a simple copy and paste solution.
At first create a class with all fields you want to include in the result:
public class Matched {
private Object fieldA;
private Object fieldB;
// Some getter and Setter
}
The Basic idea is that you load your data. Than find the two corresponding objects. After that do your matching for each field.
public List<Matched> matchYourData() {
// load your data
List<DataA> dataAList = loadYourDataA();
List<DataB> dataBList = loadYourDataB();
List<Matched> resultList = new ArryList<>();
for (dataA: DataA) {
DataB dataB = dataBList.stream()
.filter(data -> data.getId() == dataA.getId())
.findFirst().orElseThrow();
// Now you have your data. Let's match them.
Matched matched = new Matched();
matched.setFieldA(dataB.getFieldA() == dataA.getFieldA() ? doSomething() : doSomethingElse());
// Set all your fields. Decide for everyone the matching strategy
resultList.add(matched);
}
return resultList;
}
This is a quite simple solution. Of course you can use Tools like Mapstruct for mapping purpose. But this depends on your environment.

Use custom inheritor from the hateoas.CollectionModel in hateoas.server.RepresentationModelProcessor

I have simple RestController that return CollectionModel:
#RequestMapping("/test")
public ResponseEntity<?> index() {
List<DemoEntity> all = Arrays.asList(new DemoEntity(1L, "first"),
new DemoEntity(2L, "second"),
new DemoEntity(3L, "third"));
List<EntityModel<DemoEntity>> list = new ArrayList<>();
all.forEach(demoEntity -> list.add(new EntityModel<>(demoEntity)));
CollectionModel<EntityModel<DemoEntity>> collectionModel = new CollectionModel<>(list);
return ResponseEntity.ok(collectionModel);
}
DemoEntity has only two fields, id and name. SecondEntity is the same.
I am trying to use RepresentationModelProcessor:
#Configuration
public class SpringDataRestConfig {
#Bean
public RepresentationModelProcessor<EntityModel<DemoEntity>> demoEntityProcessor() {
return new RepresentationModelProcessor<EntityModel<DemoEntity>>() {
#Override
public EntityModel<DemoEntity> process(EntityModel<DemoEntity> entity) {
return new MyHateoasEntityModel<>(entity.getContent(), entity.getLink("self").orElse(new Link("self")));
}
};
}
#Bean
public RepresentationModelProcessor<CollectionModel<EntityModel<DemoEntity>>> demoEntitiesProcessor() {
return new RepresentationModelProcessor<CollectionModel<EntityModel<DemoEntity>>>() {
#Override
public CollectionModel<EntityModel<DemoEntity>> process(CollectionModel<EntityModel<DemoEntity>> collection) {
// return new CollectionModel<>(collection.getContent());
return new MyHateoasCollectionModel<>(collection.getContent());
}
};
}
#Bean
public RepresentationModelProcessor<EntityModel<SecondEntity>> secondEntityProcessor() {
return new RepresentationModelProcessor<EntityModel<SecondEntity>>() {
#Override
public EntityModel<SecondEntity> process(EntityModel<SecondEntity> entity) {
return new MyHateoasEntityModel<>(entity.getContent(), entity.getLink("self").orElse(new Link("self")));
}
};
}
#Bean
public RepresentationModelProcessor<CollectionModel<EntityModel<SecondEntity>>> secondEntitiesProcessor() {
return new RepresentationModelProcessor<CollectionModel<EntityModel<SecondEntity>>>() {
#Override
public CollectionModel<EntityModel<SecondEntity>> process(CollectionModel<EntityModel<SecondEntity>> collection) {
// return new CollectionModel<>(collection.getContent());
return new MyHateoasCollectionModel<>(collection.getContent());
}
};
}
}
One thing here is that I want to use my own classes MyHateoasEntityModel and MyHateoasCollectionModel. They are quite simple:
public class MyHateoasEntityModel<T> extends EntityModel<T> {
private T entity;
public MyHateoasEntityModel(T entity, Iterable<Link> links) {
super(entity, Collections.emptyList());
this.entity = entity;
}
public MyHateoasEntityModel(T entity, Link... links) {
this(entity, Collections.emptyList());
}
}
public class MyHateoasCollectionModel<T> extends CollectionModel<T> {
public MyHateoasCollectionModel(Iterable<T> content, Link... links) {
super(content, Collections.emptyList());
}
}
The question is that when the controller is called, the demoEntityProcessor, demoEntitiesProcessor methods are called in turn. And this is what i want from the application. But then, somehow, secondEntitiesProcessor is called, but shouldn't.
Earlier, spring boot 1.5.17 was used, and everything works fine.
All code on: https://github.com/KarinaPleskach/Hateoas

Expose enums with Spring Data REST

I'm using Spring Boot 1.5.3, Spring Data REST, HATEOAS.
I've a simple entity model:
#Entity
public class User extends AbstractEntity implements UserDetails {
private static final long serialVersionUID = 5745401123028683585L;
public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();
#NotNull(message = "The name of the user cannot be blank")
#Column(nullable = false)
private String name;
/** CONTACT INFORMATION **/
private String landlinePhone;
private String mobilePhone;
#NotNull(message = "The username cannot be blank")
#Column(nullable = false, unique = true)
private String username;
#Email(message = "The email address is not valid")
private String email;
#JsonIgnore
private String password;
#Column(nullable = false)
private String timeZone = "Europe/Rome";
#JsonIgnore
private LocalDateTime lastPasswordResetDate;
#Column(nullable = false, columnDefinition = "BOOLEAN default true")
private boolean enabled = true;
#Type(type = "json")
#Column(columnDefinition = "json")
private Roles[] roles = new Roles[] {};
and my enum Roles is:
public enum Roles {
ROLE_ADMIN, ROLE_USER, ROLE_MANAGER, ROLE_TECH;
#JsonCreator
public static Roles create(String value) {
if (value == null) {
throw new IllegalArgumentException();
}
for (Roles v : values()) {
if (value.equals(v.toString())) {
return v;
}
}
throw new IllegalArgumentException();
}
}
I'm creating a client in Angular 4. Spring Data REST is great and expose repository easily return my model HATEOAS compliant:
{
"_embedded": {
"users": [
{
"name": "Administrator",
"username": "admin",
"roles": [
"Amministratore"
],
"activeWorkSession": "",
"_links": {
"self": {
"href": "http://localhost:8080/api/v1/users/1"
},
"user": {
"href": "http://localhost:8080/api/v1/users/1{?projection}",
"templated": true
}
}
},
Like you can see I'm also translating via rest-messages.properties the value of my enums. Great!
My Angular page now needs the complete lists of roles (enums). I've some question:
understand the better way for the server to return the list of roles
how to return this list
My first attemp was to create a RepositoryRestController in order to take advantage of what Spring Data REST offers.
#RepositoryRestController
#RequestMapping(path = "/api/v1")
public class UserController {
#Autowired
private EntityLinks entityLinks;
#RequestMapping(method = RequestMethod.GET, path = "/users/roles", produces = "application/json")
public Resource<Roles> findRoles() {
Resource<Roles> resource = new Resource<>(Roles.ROLE_ADMIN);
return resource;
}
Unfortunately, for some reason, the call to this methods return a 404 error. I debugged and the resource is created correctly, so I guess the problem is somewhere in the JSON conversion.
how to return this list?
#RepositoryRestController
#RequestMapping("/roles")
public class RoleController {
#GetMapping
public ResponseEntity<?> getAllRoles() {
List<Resource<Roles>> content = new ArrayList<>();
content.addAll(Arrays.asList(
new Resource<>(Roles.ROLE1 /*, Optional Links */),
new Resource<>(Roles.ROLE2 /*, Optional Links */)));
return ResponseEntity.ok(new Resources<>(content /*, Optional Links */));
}
}
I was playing around with this and have found a couple of ways to do it.
Assume you have a front end form that wants to display a combo box containing priorities for a single Todo such as High, Medium, Low. The form needs to know the primary key or id which is the enum value in this instance and the value should be the readable formatted value the combo box should display.
If you wish to customize the json response in 1 place only such as a single endpoint then I found this useful. The secret sauce is using the value object PriorityValue to allow you to rename the json field through #Relation.
public enum Priority {
HIGH("High"),
NORMAL("Normal"),
LOW("Low");
private final String description;
Priority(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public static List<Priority> orderedValues = new ArrayList<>();
static {
orderedValues.addAll(Arrays.asList(Priority.values()));
}
}
#RepositoryRestController
#RequestMapping(value="/")
public class PriorityController {
#Relation(collectionRelation = "priorities")
#JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
private class PriorityValue {
private String id;
private String value;
public PriorityValue(String id,
String value) {
this.id = id;
this.value = value;
}
}
#GetMapping(value = "/api/priorities", produces = MediaTypes.HAL_JSON_VALUE)
public ResponseEntity<Resources<PriorityValue>> getPriorities() {
List<PriorityValue> priorities = Priority.orderedValues.stream()
.map(p -> new PriorityValue(p.name(), p.getDescription()))
.collect(Collectors.toList());
Resources<PriorityValue> resources = new Resources<>(priorities);
resources.add(linkTo(methodOn(PriorityController.class).getPriorities()).withSelfRel());
return ResponseEntity.ok(resources);
}
}
Another approach is to use a custom JsonSerializer. The only issue using this is everywhere a Priority enum is serialized you will end up using this format which may not be what you want.
#JsonSerialize(using = PrioritySerializer.class)
#Relation(collectionRelation = "priorities")
public enum Priority {
HIGH("High"),
NORMAL("Normal"),
LOW("Low");
private final String description;
Priority(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public static List<Priority> orderedValues = new ArrayList<>();
static {
orderedValues.addAll(Arrays.asList(Priority.values()));
}
}
#RepositoryRestController
#RequestMapping(value="/api")
public class PriorityController {
#GetMapping(value = "/priorities", produces = MediaTypes.HAL_JSON_VALUE)
public ResponseEntity<Resources<Priority>> getPriorities() {
Resources<Priority> resources = new Resources<>(Priority.orderedValues);
resources.add(linkTo(methodOn(PriorityController.class).getPriorities()).withSelfRel());
return ResponseEntity.ok(resources);
}
}
public class PrioritySerializer extends JsonSerializer<Priority> {
#Override
public void serialize(Priority priority,
JsonGenerator generator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
generator.writeStartObject();
generator.writeFieldName("id");
generator.writeString(priority.name());
generator.writeFieldName("value");
generator.writeString(priority.getDescription());
generator.writeEndObject();
}
}
The final json response from http://localhost:8080/api/priorities
{
"_embedded": {
"priorities": [
{
"id": "HIGH",
"value": "High"
},
{
"id": "NORMAL",
"value": "Normal"
},
{
"id": "LOW",
"value": "Low"
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/priorities"
}
}
}

Resources