Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CXF REST: How can I retrieve the POJO object from the message in an interceptor before it gets marshal'd?

We have implemented a REST API in CXF. My goal is to be able to define custom annotations on a POJO and process them in a CXF interceptor before they get marshal'd. I believe I have all the information I need to be able to do this except for retrieving the actual object in the interceptor. My code looks like this:

  1. Resource class

    @Path("/mypath")
    public class MyResource {
    
        @GET
        public MyObject getObject() {
           MyObject o = new MyObject();
           ...
           return o;
        }
    }
    
  2. MyObject

    public class MyObject {
    
        private String x;
    
        @MyAnnotation
        public String getX() {
           return x;
        }
    
        public String setX(x) {
           this.x = x;
        }
    }
    
  3. Interceptor

    public class MyInterceptor extends AbstractPhaseInterceptor<Message> {
    
        public VersionOutInterceptor() {
            super(Phase.POST_LOGICAL);
        }
    
        public final void handleMessage(Message message) {
            // 1. STUCK -- get object from the message
            // 2. parse annotations and manipulate the object
            // 3. put the object back on the message for serialization
        }
    }
    

How do I get the object from the message, manipulate it based on the annotations, and put it back on the message?

like image 582
superdave Avatar asked Jan 16 '23 00:01

superdave


1 Answers

I have similar requirement and this is how I could do it

for In Interceptor I have used PRE_INVOKE Phase and for Out Interceptor PRE_LOGICAL Phase. This code shows only logging but you can change the object if needed by Usecase.

code as below will fetch you the object you are looking for

@Override
   public void handleMessage(Message message) throws Fault {
      MessageContentsList objs = MessageContentsList.getContentsList(message);
      if (objs != null && objs.size() == 1) {
      Object responseObj = objs.get(0);
      DomainPOJO do= (DomainPOJO)responseObj;
   _logger.info(do.toString());
  }
}
like image 138
R-JANA Avatar answered Jan 30 '23 21:01

R-JANA