0

I am using RestTemplate for testing APIs exposed through Spring DATA REST and I cannot get links when parsing the response. The rest template is configured with Jackson2HalModule backed HttpConverter, and Entity requested has links to associations that appear in the JSON response alright.

Here's the JSON

{
  "name" : "Hero @ Bangalore",
  "venue" : {
    "name" : "Wayne Manor",
    "address" : "1 MG Road",
    "city" : "Bangalore",
    "state" : "Karnataka",
    "pincode" : "560001"
  },
  "seatsAvailable" : 40,
  "workshopType" : "Batman Challengers",
  "date" : "2015-09-10",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/workshops/1{?projection}",
      "templated" : true
    },
    "venue" : {
      "href" : "http://localhost:8080/workshops/1/venue"
    }
  }
}

The RestTemplate is configured as adviced in this post, since we are getting a HAL+JSON response

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.registerModule(new Jackson2HalModule());
MappingJackson2HttpMessageConverter halConverter = new MappingJackson2HttpMessageConverter();
halConverter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
halConverter.setObjectMapper(objectMapper);

restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> existingConverters = restTemplate.getMessageConverters();
List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<>();
httpMessageConverters.add(halMessageConverter);
httpMessageConverters.addAll(existingConverters);

Now, I expect links to be available in the parsed response object too, but that's not the case, here is how I fetch the response

ResponseEntity<Resource<Workshop>> workshopResource = 
restTemplate
        .exchange(DEFAULT_PROJECTION, HttpMethod.GET, null,
            new ParameterizedTypeReference<Resource<Workshop>>() {
            });

Workshop responseBody = workshopResource.getBody().getContent();

but then the assertion for venue link fails

assertTrue(workshopResource.getBody().getLink("venue").equals(paulURI.toString()));  

gives a NullPointerException

Community
  • 1
  • 1
Anadi Misra
  • 1,382
  • 3
  • 26
  • 50

1 Answers1

2

You're not registering the halConverter with the RestTemplate as you're only looking up the existing ones and add those plus the halConverter to an arbitrary list that never makes it into the RestTemplate again.

Oliver Drotbohm
  • 71,632
  • 16
  • 205
  • 196
  • that and `workshopResource.getBody().getLink("venue")` and change to `workshopResource.getBody().getLink("venue").getHref().equals(...)` fixed the test – Anadi Misra Aug 11 '15 at 10:35