Apache CXF :- How do i extract the payload data using cxf interceptors

自古美人都是妖i 提交于 2019-12-31 03:44:10

问题


What steps should I follow to extract the payload using Apache CXF interceptors?


回答1:


Your interceptor needs to extend from the AbstractPhaseInterceptor or a subclass

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

    public void handleMessage(Message message) {
        //Get the message body into payload[] and set a new non-consumed  inputStream into Message
        InputStream in = message.getContent(InputStream.class);
        byte payload[] = IOUtils.readBytesFromStream(in);
        ByteArrayInputStream bin = new ByteArrayInputStream(payload);
        message.setContent(InputStream.class, bin);
    }

    public void handleFault(Message messageParam) {
        //Invoked when interceptor fails
    }
}

Add the interceptor programmatically

MyInterceptor myInterceptor = new MyInterceptor();

Server server = serverFactoryBean.create();
server.getEndpoint().getInInterceptor().add(myInterceptor);

Or using configuration

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:cxf="http://cxf.apache.org/core"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">

    <bean id="MyInterceptor" class="demo.interceptor.MyInterceptor"/>

    <!-- We are adding the interceptors to the bus as we will have only one endpoint/service/bus. -->

    <cxf:bus>
        <cxf:inInterceptors>
            <ref bean="MyInterceptor"/>
        </cxf:inInterceptors>
        <cxf:outInterceptors>
            <ref bean="MyInterceptor"/>
       </cxf:outInterceptors>
    </cxf:bus>
</beans>

Check documentation here




回答2:


You can use LoggingInInterceptor to retrieve payload as String

public class CustomInInterceptor extends LoggingInInterceptor {

    /**
     * SLF4J Log Instance
     */
    private final static Logger LOG = LoggerFactory.getLogger(CustomInInterceptor.class);

    /**
     * formats logging message and also attaches input xml to thread context
     * 
     * @see org.apache.cxf.interceptor.LoggingInInterceptor#formatLoggingMessage(org.apache.cxf.interceptor.LoggingMessage)
     */
    @Override
    protected String formatLoggingMessage(final LoggingMessage loggingMessage) {
  //The below line reads payload and puts into threads context, which I use later to save in db 
    KpContextHolder.setInputXml(loggingMessage.getPayload().toString());
        return super.formatLoggingMessage(loggingMessage);
    }

}


来源:https://stackoverflow.com/questions/38586259/apache-cxf-how-do-i-extract-the-payload-data-using-cxf-interceptors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!