Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache CXF - share data between In and Out interceptors

Tags:

java

cxf

I am using Apach CXF as REST provider.

I want to gather data when I enter the webservice, gather data before I enter the resposne and add some calculation to the response. For this question and for simplicity, lets assume I want to get the starting time on entering, the finishing time before the response is sent and add the total time to the response.

Now, how do I do that? I created In and Out interceptors that works fine alone, but how do I use the data from the In interceptor in the Out interceptor?

Thanks Idob



UPDATE:

I tried to set the data as contextual parameter with

message.setContextualProperty(key,value);

but I am getteing NULL on

message.getContextualProperty(key);

I also tried the same but just with

message.put(key,value) and message.get(key)

didn't work.

Idea's anyone?

Thank you, Idob

like image 993
Ido Barash Avatar asked Oct 02 '12 08:10

Ido Barash


2 Answers

You can store values on the Exchange. CXF creates an Exchange object for each request to act as a container for the in and out messages for the request/response pair and makes it accessible as message.getExchange() from both.

In interceptor:

public void handleMessage(Message inMessage) throws Fault {
  inMessage.getExchange().put("com.example.myKey", myCustomObject);
}

Out interceptor

public void handleMessage(Message outMessage) throws Fault {
  MyCustomObject obj = (MyCustomObject)outMessage.getExchange().get("com.example.myKey");
}

(or vice-versa for client-side interceptors, where the out would store values and the in would retrieve them). Choose a key that you know won't be used by other interceptors - a package-qualified name is a good choice. Note that, like Message, Exchange is a StringMap and has generic put/get methods taking a Class as the key that give you compile-time type safety and save you having to cast:

theExchange.put(MyCustomObject.class, new MyCustomObject());
MyCustomObject myObj = theExchange.get(MyCustomObject.class);
like image 185
Ian Roberts Avatar answered Nov 11 '22 14:11

Ian Roberts


Your interceptors have access to javax.xml.ws.handler.MessageContext. This extends Map<String,Object>, so you can put whatever you want into the context and access it later on in the request:

public boolean handleMessage(final MessageContext context) {
    context.put("my-key", myCustomObject);
            // do whatever else your interceptor does
}

Later on:

public boolean handleMessage(final MessageContext context) {
    MyCustomObject myCustomObject = context.get("my-key");
            // do whatever else your interceptor does
}
like image 27
artbristol Avatar answered Nov 11 '22 13:11

artbristol