I have controller endpoint in spring boot microservice which receives some data (xml), should check it with another microservice and if ok, pass it to third microservice for an answer. I'd like to do smth like that:
@PostMapping("/")
public ResponseEntity<Resource> request(@RequestBody Resource inputResource) {
if (check(inputResource)) {
Resource r = getAnswer(inputResource);
return ResponseEntity.ok()
.contentLength(r.contentLength())
.contentType(contentType)
.body(r);
} else {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "check failed");
}
}
private boolean check(Resource resource) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
HttpEntity<?> entity = new HttpEntity<>(resource.getInputStream(), headers);
ResponseEntity<String> response = this.restTemplate.exchange(checkUrl,
HttpMethod.POST, entity, String.class);
return !response.getStatusCode().isError();
} catch (Exception ex) {
return false;
}
}
private Resource getAnswer(Resource resource) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
HttpEntity<?> entity = new HttpEntity<>(resource.getInputStream(), headers);
ResponseEntity<Resource> response = this.restTemplate.exchange(forwardUrl,
HttpMethod.POST, entity, Resource.class);
if (response.getStatusCode().isError()) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "forwarding failed");
}
return response.getBody();
}
Can i do it like this? I.e. read from endpoint's input resource first time to pass the resource's stream to checking service and second time to pass it to destination service or should i first buffer it? Can i also get answer from the destination service as the resource to return it from endpoint or should i use extractor to process answering inputstream? Please, advise.