'java costom annotation to accept request body

I am trying for a custom annotation that when applied to a controller would log all the parameters by default.

but I'm facing issues when I'm trying to read the body as the stream is getting closed when the rest controller reads it.

annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ControllerLog {
}

annotation intercepter

@Before("@annotation(controllerLog)")
public void controllerLogImplementation(ControllerLog controllerLog) {
    Map<String, String> headers =  Collections.list(httpServletRequest.getHeaderNames()).stream()
            .collect(Collectors.toMap(val -> val, val -> httpServletRequest.getHeader(val)));
    
    InputStream fis = httpServletRequest.getInputStream();
    InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
    BufferedReader br = new BufferedReader(isr);
    List<String> body = new ArrayList<>();
    br.lines().forEach(input::add);
 
   log.info("In {} API: {} headers: {} parameters: {} body : {}", httpServletRequest.getMethod(), httpServletRequest.getRequestURI(), headers, httpServletRequest.getParameterMap(), body);
}

controller method

@PostMapping("/postMethod")
@ControllerLog
public ResponseEntity<String> post(@RequestBody DocumentUploadRequest request) {
   return new ResponseEntity<>(request, HttpStatus.OK);
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source