Search code examples
javaspring-wsxmlbeanssoapheadercustom-element

How to add xmlbean document element to soap header spring-ws


I am trying to hit a webservice using spring-ws, but the webservice producer requires a custom element in the soap header. I am very new to webservices, and am having trouble trying to inject the values into the soap header. I am using XMLBeans to transform from xsd to java and also to do the marshaling and unmarshaling. I have constructed the xmlbean document and set all values for the custom header element, I just need to get the document or maybe even just the element attached to that document to be injected into the soap header. Listed below is the wsdl (just header) in soapui (what I used to learn and do initial testing)

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0" xmlns:v11="http://www.ups.com/XMLSchema/XOLTWS/Rate/v1.1" xmlns:v12="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
   <soapenv:Header>
      <v1:UPSSecurity>
         <v1:UsernameToken>
            <v1:Username>name</v1:Username>
            <v1:Password>password</v1:Password>
         </v1:UsernameToken>
         <v1:ServiceAccessToken>
            <v1:AccessLicenseNumber>accesskey</v1:AccessLicenseNumber>
         </v1:ServiceAccessToken>
      </v1:UPSSecurity>
   </soapenv:Header>

Solution

  • I found a solution that works, and isn't much code. I had to ditch using xmlbeans, and just create the elements, but at least the functionality is there and the webservice calls works.

    @Override
    public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException
    {
        try
        {
            SOAPMessage soapMessage = ((SaajSoapMessage)message).getSaajMessage();
            SOAPHeader header = soapMessage.getSOAPHeader();
            SOAPHeaderElement soapHeaderElement = header.addHeaderElement(new QName("http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0", "UPSSecurity", "v1"));
            SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();
            envelope.addNamespaceDeclaration("v1", "http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0");
    
            SOAPElement usernameToken = soapHeaderElement.addChildElement("UsernameToken", "v1");
            SOAPElement username = usernameToken.addChildElement("Username", "v1");
            SOAPElement password = usernameToken.addChildElement("Password", "v1");
    
            SOAPElement serviceAccessToken = soapHeaderElement.addChildElement("ServiceAccessToken", "v1");
            SOAPElement accessLicenseNumber = serviceAccessToken.addChildElement("AccessLicenseNumber", "v1");
    
            username.setTextContent("username");
            password.setTextContent("password");
            accessLicenseNumber.setTextContent("key");
        } 
        catch (SOAPException e)
        {
            e.printStackTrace();
        }
    }