'how to get MicroProfile REST Client annotation in ClientRequestFilter

My RestClient is annotated by a custom annotation and I want to get the annotation value in a ClientRequestFilter.

Here is my MicroProfile RestClient:

@Path("/greetings")
@RegisterRestClient
@MyAnnotation("myValue") 
public interface MyRestClient{

  @GET
  public String hello();
}

I want to get the annotation value in my ClientRequestFilter:

public class MyFilter implements ClientRequestFilter {

  @Override
  public void filter(ClientRequestContext requestContext) {
   // Here i want to get the MyAnnotation value. i.e "myValue"
  }
}

I tried to call the requestContext.getClient().getAnnotations() method but it does not work since requestContext.getClient() is an instance of org.jboss.resteasy.microprofile.client.impl.MpClient

The implementation in question is RESTEasy. I would like to find a way to get this information from both RESTEasy classic and RESTEasy reactive implementations.

Thanks for your help



Solution 1:[1]

Here is the MicroProfile REST Client specific way:

@Provider
public class MyFilter implements ClientRequestFilter {
   
  public void filter(final ClientRequestContext clientRequestContext) {
    
    final Method method = (Method) clientRequestContext
                              .getProperty("org.eclipse.microprofile.rest.client.invokedMethod");
    
    Class<?> declaringClass = method.getDeclaringClass();
    System.out.println(declaringClass);

    MyAnnotation myAnnotation = declaringClass.getAnnotation(MyAnnotation.class);
    System.out.println(myAnnotation.value());
  }
}

which must work in all implementations including RESTEasy (Classic and Reactive) or Apache CXF.

Solution 2:[2]

This should work:

import org.jboss.resteasy.client.jaxrs.internal.ClientRequestContextImpl;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class MyFilter implements ClientRequestFilter {
    @Override
    public void filter(ClientRequestContext requestContext) {
        Class<?> declaringClass = ((ClientRequestContextImpl) requestContext)
            .getInvocation()
            .getClientInvoker()
            .getDeclaring();

        MyAnnotation myAnnotation = declaringClass.getAnnotation(MyAnnotation.class);
        System.out.println(myAnnotation.value());
    }
}

Just to mention, this is really RESTEasy specific. The class ClientRequestContextImpl comes from the internal RESTEasy package and thus might be subject to change.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 xstefank
Solution 2