Search code examples
quarkusjava-17

Request Handling in quarkus


I would like to process the request when the controller method has a custom annotation that I created in quarkus.

@Slf4j
@Provider
@Priority(5000)
@RequiredArgsConstructor
public class ExampleFilter implements ContainerRequestFilter, ContainerResponseFilter {

 @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        String body = getBody(requestContext);
        log.info("Request is: {}", body);

    }

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        log.info("Response is: {}", responseContext.getEntity().toString());
        //I would like here to find the handling controller method of the incoming request and check if it is annotated with my custom annotation.
    }

    private String getBody(ContainerRequestContext requestContext) throws IOException {
        StringBuilder body = new StringBuilder();
        String line;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(requestContext.getEntityStream()));
        while ((line = bufferedReader.readLine()) != null) {
            body.append(line);
        }
        return body.toString();
    }
}

In spring boot I am using RequestMappingHandlerMapping with the request

var handlerChain = handlerMapping.getHandler((HttpServletRequest) servletRequest);
HandlerMethod handlerMethod = (HandlerMethod) handlerChain.getHandler();
handlerMethod.hasMethodAnnotation(MY_CUSTOM_ANNOTATION.class)
//do some stuff here

and I can find if it is annotated.

What can I use in quarkus in order to achieve the same?


Solution

  • You can do something like this:

    @Slf4j
    @Provider
    @Priority(5000)
    @RequiredArgsConstructor
    public class ExampleFilter implements ContainerRequestFilter, ContainerResponseFilter {
    
        @Context
        private ResourceInfo resourceInfo;
    
    
     @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
    
            String body = getBody(requestContext);
            log.info("Request is: {}", body);
    
        }
    
        @Override
        public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
            log.info("Response is: {}", responseContext.getEntity().toString());
    
            resourceInfo.getResourceMethod().isAnnotationPresent(MY_CUSTOM_ANNOTATION.class)
    
        }
    }