godo57
godo57

Reputation: 548

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

Upvotes: 0

Views: 1415

Answers (2)

blinkingnoise
blinkingnoise

Reputation: 36

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.

Upvotes: 2

xstefank
xstefank

Reputation: 499

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.

Upvotes: 1

Related Questions