Home > Blockchain >  create a wrapper class accepting function in java
create a wrapper class accepting function in java

Time:06-05

i want to make a wrapper class, that does pre-processing, executes the passed function, and then do some post-processing before returning the response. How i can write the wrapper class to accept function as parameter and invoke it?

@Autowired
private SomeService service;

@GetMapping("/path")
public CustomResponse(CustomRequest request){
  1. preprocess(request)
  2. CustomResponse response = service.functionA(request)
  3. postprocess(response)
  4. return response;
------------------------- vs --------------------------------
  1. return CustomWrapper.execute(request,???,response)
}

-- **Need help in writing this class.**

class CustomWrapper{
  void preprocess();
  ?? execute();
  void postprocess();
}

CodePudding user response:

This should be basically what you're looking for, if you want you can hard code the postprocessor and preprocessor so it can be used like your example, but this is a bit more general:

public class CustomProcessor {

    private Function<CustomRequest, CustomRequest> preprocessor;
    private Function<CustomResponse, ResponseEntity<CustomResponse>> postprocessor;

    public CustomProcessor(
            Function<CustomRequest, CustomRequest> preprocessor,
            Function<CustomResponse, ResponseEntity<CustomResponse>> postprocessor
    ) {
        this.preprocessor = preprocessor;
        this.postprocessor = postprocessor;
    }

    public ResponseEntity<CustomResponse> execute(CustomRequest request, Function<CustomRequest, CustomResponse> processor) {
        request = preprocessor.apply(request);
        CustomResponse response = processor.apply(request);
        return postprocessor.apply(response);
    }

}

CodePudding user response:

with help of @void void answer was able to achieve as required.

public class ControllerTemplate<Req, Res> {

  private static final Logger logger = LogManager.getLogger(ControllerTemplate.class);

  public Res execute(Req req, Function<Req, Res> processor) {
    preProcess(req);
    Res res = processor.apply(req);
    postProcess(res);
    return res;
  }

  private void postProcess(Res res) {
    logger.info("response body: {}", res);
  }

  private void preProcess(Req req) {
    logger.info("request body: {}", req);
  }
}

calling function

 @GetMapping("/logLevel")
  public String updateLogLevel(@RequestParam String level) {
    return new ControllerTemplate<String, String>()
        .execute(level, req -> log4jService.changeLogLevel(req));
  }
  • Related