Ilya
Ilya

Reputation: 29693

jax-rs Apache CXF, transfer data between interceptors

Let's I have two interceptors. Input interceptor at Phase.RECEIVE and output interceptor at Phase.SETUP_ENDING

public class BeforeInterceptor extends AbstractPhaseInterceptor<Message> 
{
   public BeforeInterceptor()
   {
      super(Phase.RECEIVE);
   }  

and

public class AfterInterceptor extends AbstractPhaseInterceptor<Message> 
{
   public AfterInterceptor()
   {
      super(Phase.SETUP_ENDING);
   }  

and now i want know: how many time was between this two phases?
I must call System.currentTimeMillis(); in BeforeInterceptor, tranfser this value to AfterInterceptor, and call
System.currentTimeMillis() - valueFromBeforeInterceptor in after interceptor.

But how can I transfer data from one interceptor ti another?

Upvotes: 2

Views: 1369

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122394

To pass data between two interceptors that are in the same chain (i.e. two "in" interceptors or two "out" interceptors) you can store arbitrary values on the Message

// BeforeInterceptor
message.put("com.example.MyApp.startTime", System.currentTimeMillis());

// AfterInterceptor
long totalTime = System.currentTimeMillis() -
   (Long)message.get("com.example.MyApp.startTime");

If one interceptor is in the "in" chain and the other is in the "out" chain then you can use the Exchange for the same purpose:

// BeforeInterceptor
inMessage.getExchange().put("com.example.MyApp.startTime", System.currentTimeMillis());

// AfterInterceptor
long totalTime = System.currentTimeMillis() -
   (Long)outMessage.getExchange().get("com.example.MyApp.startTime");

Whichever one you use, it's a good idea to pick keys that you are sure won't clash with any other interceptors, e.g. by using Java package-style hierarchical names.

Upvotes: 5

Related Questions