Output SOAP message with XML transformer : SOAP « JDK 6 « Java






Output SOAP message with XML transformer

  

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class MainClass {

  public static void main(String[] args) throws Exception {
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

    SOAPHeader soapHeader = soapEnvelope.getHeader();
    SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName(
        "Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

    SOAPBody soapBody = soapEnvelope.getBody();
    soapBody.addAttribute(soapEnvelope.createName("id", "SOAP-SEC",
        "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body");
    Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
    SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

    Source source = soapPart.getContent();

    Node root = null;
    if (source instanceof DOMSource) {
      root = ((DOMSource) source).getNode();
    } else if (source instanceof SAXSource) {
      InputSource inSource = ((SAXSource) source).getInputSource();
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      DocumentBuilder db = null;

      db = dbf.newDocumentBuilder();

      Document doc = db.parse(inSource);
      root = (Node) doc.getDocumentElement();
    }
    
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(new DOMSource(root), new StreamResult(System.out));    
  }
}

          
  








Related examples in the same category

1.Call google web service and deal with the return with SOAPMessage
2.Create SOAP message
3.Generate DOM with SOAP message
4.Sending a SOAP Message
5.Processing a SOAP Message
6.Calling a .NET Web Service