Custom SoapHeader in CXF

Source: Internet
Author: User
Tags error handling soap xmlns
It programmer development Essentials-all kinds of resources download list, history of the most IT resources, personal collection summary.



Interceptor is a very distinctive pattern in the CXF architecture. You can add many features dynamically without modifying the core module. This is useful for CXF, a message-centric service framework, where CXF implements a number of important functional modules through special processing of messages in interceptor, such as: Logging, SOAP message processing, and compression of messages. Simply put, it can be processed before the request is received and before the business process is processed. Or, before the request packet is sent, the message is processed.

Interceptor

Define two methods, one to process message handlemessage, and one to handle error handlefault.

Interceptorchain

A single interceptor function is limited, CXF to implement a SOAP message processing, you need to combine many interceptor together. So the design of the Interceptorchain, I looked at the Interceptorchain is like a interceptor of the little captain. The little captain has the power to deploy Interceptor (Add,remove), as well as the power to Control Message processing (Dointerceptor,pause,resume,reset,abort), as well as the right to deliver error handling ({Get|set} Faultobserver). More interesting is the Interceptor Processing message Order (Dointerceptstartingat,dointerceptorstartingafter) for flexible control, which is interceptorchain more difficult to understand the place.

Fault

The error message in CXF is defined.

Interceptorprovider

This defines the interceptor's reserve security forces. We can set up In,out,infault,outfault teams in Interceptorprovider and add the interceptor we want to add. And Interceptorchain will be based on these backup units, the formation of their own team instances, complete the specific combat function tasks.

Abstractattributedinterceptorprovider

Interceptorprovider implementation of the abstract class, because this class to inherit the HashMap, we can store some property information like this class.

Abrstractbasicinterceptorprovider

Unlike Abstractattributedinterceptorprovider, this interceptor simply implements the Interceptorprovider function and does not provide an extension to its property store.

Message

Since interceptor is handled for message, when you open the message class file, you will find that there are many constants defined in the message, and you can also get a lot of information about the message operation from the message. You can get settings for objects that have Interceptorchain Exchange Destination, and a generic interface to get settings for content, whether it feels like a message and bus, it's a big grocery store, Everything that is related to message processing can be placed in a message.

service-side interceptors

Package hs.cxf.soapHeader;

Import javax.xml.soap.SOAPException;

Import Javax.xml.soap.SOAPHeader;

Import Javax.xml.soap.SOAPMessage;

Import Org.apache.cxf.binding.soap.SoapMessage;

Import Org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;

Import Org.apache.cxf.interceptor.Fault;

Import Org.apache.cxf.phase.AbstractPhaseInterceptor;

Import Org.apache.cxf.phase.Phase;



Import org.w3c.dom.NodeList; 

 /** * * @Title: Get SOAP Header information * * @Description: * * @Copyright: * * @author ZZ * @version 1.00.000 * */public class Readsoapheader extends abstractphaseinterceptor<soapmessage> {private Saajininterceptor SA



    A = new Saajininterceptor ();

        Public Readsoapheader () {super (PHASE.PRE_PROTOCOL);

    Getafter (). Add (SAAJInInterceptor.class.getName ()); } public void Handlemessage (SoapMessage message) throws Fault {SoapMessage mess = message.getcontent (so

        Apmessage.class);

          if (mess = = null) {  Saa.handlemessage (message);

        Mess = Message.getcontent (Soapmessage.class);

        } SoapHeader head = null;

        try {head = Mess.getsoapheader ();

        } catch (SoapException e) {e.printstacktrace ();

        } if (head = = null) {return;

            } try {//Read the custom node NodeList nodes = Head.getelementsbytagname ("Tns:spid");

            NodeList Nodepass = Head.getelementsbytagname ("Tns:sppassword"); Gets the node value, simple authentication if (Nodes.item (0). Gettextcontent (). Equals ("WDW")) {if (Nodepass.item (0). Gettex

                Tcontent (). Equals ("WDWSB")) {SYSTEM.OUT.PRINTLN ("certified success");

                }} else {SoapException soapexc = new SoapException ("Authentication error");

            throw new Fault (SOAPEXC);

}} catch (Exception e) {SoapException soapexc = new SoapException ("Authentication error");            throw new Fault (SOAPEXC); }

    }



}

New Interceptor configuration in

configuration file

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:jaxws=" Http://cxf.apache.org/jaxws "xsi:schemalocation=" Http://www.springfram Ework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://cxf.apache.org/jaxws   

    Http://cxf.apache.org/schemas/jaxws.xsd "> <import resource=" Classpath:meta-inf/cxf/cxf.xml "/> <import resource= "Classpath:meta-inf/cxf/cxf-extension-soap.xml"/> <import resource= "Classpath:META-IN F/cxf/cxf-servlet.xml "/> <bean id=" Jaxwsservicefactorybean "class=" Org.apache.cxf.jaxws.supp Ort. Jaxwsservicefactorybean "> <property name=" Wrapped "value=" true "/> <property name=" dat Abinding "ref=" Aegisbean "/> </bean> <bean id=" Aegisbean "class=" org.apache.cxf   . aegis.databinding.AegisDatabinding "/>

  

    <jaxws:endpoint id= "collectiveservices" implementor= "Hs.cxf.server.WebServiceSampleImpl" address= " /helloworld "> <jaxws:inInterceptors> <!--log Blocker--<bean CLA ss= "Org.apache.cxf.interceptor.LoggingOutInterceptor"/> <!--custom Blocker-<bean class= "Hs.cxf.soapHeader.ReadSoapHeader"/> </jaxws:inInterceptors> <jaxws:servicefactory&   

            Gt   

<ref bean= "Jaxwsservicefactorybean"/> </jaxws:serviceFactory> </jaxws:endpoint> </beans>

Client Interceptors:

Package hs.cxf.client.SoapHeader;

Import java.util.List;

Import Javax.xml.namespace.QName;

Import Org.apache.cxf.binding.soap.SoapHeader;

Import Org.apache.cxf.binding.soap.SoapMessage;

Import Org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;

Import Org.apache.cxf.headers.Header;

Import Org.apache.cxf.helpers.DOMUtils;

Import Org.apache.cxf.interceptor.Fault;

Import Org.apache.cxf.phase.Phase;

Import org.w3c.dom.Document;

Import org.w3c.dom.Element; /** * * @Title: Encapsulates the soap Header information before sending a message * * @Description: * * @Copyright: * * @author ZZ * @version 1 .00.000 * */public class Addsoapheader extends Abstractsoapinterceptor {private static String nameuri= "Htt   

      

        P://127.0.0.1:8080/cxftest/ws/helloworld ";   

        Public Addsoapheader () {super (phase.write); } public void Handlemessage (SoapMessage message) throws Fault {String sppassword= "W   

   DWSB ";         String spname= "WDW";   

            QName qname=new QName ("Requestsoapheader");   

            Document doc=domutils.createdocument ();   

            Custom node Element spid=doc.createelement ("Tns:spid");   

            Spid.settextcontent (spname);   

            Custom node Element sppass=doc.createelement ("Tns:sppassword");   

               

            Sppass.settextcontent (Sppassword);   

            Element Root=doc.createelementns (Nameuri, "Tns:requestsoapheader");   

            Root.appendchild (SPID);   

               

            Root.appendchild (Sppass);   

            SoapHeader head=new SoapHeader (qname,root);   

            List 

When client calls:

Package hs.cxf.client;

Import Hs.cxf.client.SoapHeader.AddSoapHeader;

Import java.util.ArrayList;

Import javax.xml.bind.JAXBElement;

Import Javax.xml.namespace.QName;

Import org.apache.cxf.endpoint.Client;

Import Org.apache.cxf.frontend.ClientProxy;

Import Org.apache.cxf.interceptor.Interceptor;

Import Org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

Import Org.apache.cxf.transport.http.HTTPConduit;



Import Org.apache.cxf.transports.http.configuration.HTTPClientPolicy; /** * @Title: * * @Description: * * @Copyright: * * @author ZZ * @version 1.00.000 * */public C

        Lass TestClient {/** * Test 1 */@SuppressWarnings ("unchecked") public void TestSend1 () {



            try {Jaxwsproxyfactorybean factory = new Jaxwsproxyfactorybean ();

            arraylist<interceptor> list = new arraylist<interceptor> ();

            Add SOAP Header List.add (new Addsoapheader ()); Add a SOAP message log to hitIndian List.add (New Org.apache.cxf.interceptor.LoggingOutInterceptor ());

            Factory.setoutinterceptors (list);

            Factory.setserviceclass (Webservicesample.class);



            Factory.setaddress ("Http://127.0.0.1:8080/cxfTest/ws/HelloWorld");

            Object obj = Factory.create (); System.out.println (obj = = null?)

            "NULL": Obj.getclass (). GetName ());

                if (obj! = null) {webservicesample WS = (webservicesample) obj;

                String str = ws.say ("test");



                System.out.println (str);

                str = Ws.say ("1111");



                System.out.println (str);

                User U = new user (); Jaxbelement<string> JE = new jaxbelement<string> (New QName ("Http://bean.cxf.hs", "NA

                Me "), String.class," Zhang San ");

                U.setname (JE);

                str = ws.sayusername (u);



           System.out.println (str);     Interact with objects Reqbean req = new Reqbean ();

                        Req.setexp (New jaxbelement<string> (New QName ("Http://bean.cxf.hs", "exp"), String.class,

                "<exp>111<exp>")); Req.setseqid (New jaxbelement<string> (New QName ("Http://bean.cxf.hs", "SeqId"), String.clas

                S, "12345678"));

                Respbean resp = ws.action (req);

                System.out.println ("resp_id:" + resp.getrespid (). GetValue ());

            System.out.println ("Resp_exp:" + resp.getexp (). GetValue ());

        }} catch (Exception ex) {ex.printstacktrace (); }}/** * Test 2 */@SuppressWarnings ("unchecked") public void TestSend2 () {Strin

        G WebServiceURL = "Http://127.0.0.1:8080/cxfTest/ws/HelloWorld";

        String webservicecontimeout = "60000"; String webservicerevtImeout = "60000";



        Jaxwsproxyfactorybean factory = new Jaxwsproxyfactorybean ();

        arraylist<interceptor> list = new arraylist<interceptor> ();

        Add SOAP header information List.add (new Addsoapheader ());

        Add SOAP message Log print list.add (new Org.apache.cxf.interceptor.LoggingOutInterceptor ());

        Factory.setoutinterceptors (list);

        Factory.setserviceclass (Webservicesample.class);

        Factory.setaddress (WebServiceURL);



        Webservicesample service = (webservicesample) factory.create ();

        Time-out setting Client CLIENTP = clientproxy.getclient (service);

        Httpconduit http = (httpconduit) clientp.getconduit ();

        Httpclientpolicy httpclientpolicy = new Httpclientpolicy ();

        Httpclientpolicy.setconnectiontimeout (Integer. ValueOf (webservicecontimeout));

        Httpclientpolicy.setreceivetimeout (Integer. ValueOf (webservicerevtimeout)); HttpclientpolicY.setallowchunking (FALSE);

        

    

        Http.setclient (Httpclientpolicy);

        Interact with objects Reqbean req = new Reqbean ();

                Req.setexp (New jaxbelement<string> (New QName ("Http://bean.cxf.hs", "exp"), String.class,

        "<exp>111<exp>"));

                Req.setseqid (New jaxbelement<string> (New QName ("Http://bean.cxf.hs", "SeqId"), String.class,

        "12345678"));

        System.out.println (">>>>>> Send Message <<<<<<<<<");

        Respbean resp = service.action (req);

        System.out.println ("resp_id:" + resp.getrespid (). GetValue ());



    System.out.println ("Resp_exp:" + resp.getexp (). GetValue ()); }/** * @param args */public static void main (string[] args) {testclient TC = new TESTC

        Lient ();

        Tc.testsend1 (); System.out.println (">>>>>>>>>>>>2<<<<<<<<<<<<< ");

        Tc.testsend2 (); System.out.println (">>>>>>>>>>>>END<<<<<<<<<

    <<<< "); }



}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.