When we use jax-rs services sometimes we need to add request pre processors to services. In this post i will discuss how we can use cxf interceptor in jax-rs services.
You may find more information from this url[http://cxf.apache.org/docs/interceptors.html]
package demo.jaxrs.server;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
public class CustomOutInterceptor extends AbstractPhaseInterceptor {
public CustomOutInterceptor() {
//We will use PRE_INVOKE phase as we need to process message before hit actual service
super(Phase.PRE_INVOKE );
}
public void handleMessage(Message outMessage) {
System.out.println("Token: "+ ((TreeMap) outMessage.get(Message.PROTOCOL_HEADERS)).get("Authorization"));
// Do your processing with Authorization transport header.
}
}
Then we need to register Interceptor by adding entry to webapp/WEB-INF/cxf-servlet.xml file. Then it will execute before request dispatch to actual service.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <jaxrs:server id="APIService" address="/"> <jaxrs:serviceBeans> <ref bean="serviceBean"/> </jaxrs:serviceBeans> <jaxrs:inInterceptors> <ref bean="testInterceptor"/> </jaxrs:inInterceptors> </jaxrs:server> <bean id="testInterceptor" class="demo.jaxrs.server.CustomOutInterceptor" /> <bean id="serviceBean" class="demo.jaxrs.server.APIService"/> </beans>
Then compile web app and deploy in application server. Once you send request with Authorization header you will noticed that it printed in server logs.
See following sample curl request
curl -k -v -H "Authorization: Bearer d5701a8ed6f677f215fa4d65c05e361" http://127.0.0.1:9763/APIManager/qqqq-1.0.0-admin/
And server logs for request
Token: [Bearer d5701a8ed6f677f215fa4d65c05e361]
API Service -- invoking getAPI, API id is: qqqq-1.0.0-admin
No comments:
Post a Comment