background image

Examining the DOMSrcExample Class

<< SOAPBodyElement | Building the Programs >>
<< SOAPBodyElement | Building the Programs >>

Examining the DOMSrcExample Class

Examining the DOMSrcExample Class
DOMSrcExample
differs from DOMExample in only a few ways. First, after it parses the document,
DOMSrcExample
uses the document to create a DOMSource object. This code is the same as that of
DOMExample
except for the last line:
static DOMSource domSource;
...
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(args[0]));
domSource = new DOMSource(document);
...
Then, after DOMSrcExample creates the message, it does not get the header and body and add the
document to the body, as DOMExample does. Instead, DOMSrcExample gets the SOAP part and
sets the DOMSource object as its content:
// Create a message
SOAPMessage message = messageFactory.createMessage();
// Get the SOAP part and set its content to domSource
SOAPPart soapPart = message.getSOAPPart();
soapPart.setContent(domSource);
The example then uses the getContents method to obtain the contents of both the header (if it
exists) and the body of the message.
The most important difference between these two examples is the kind of document you can
use to create the message. Because DOMExample adds the document to the body of the SOAP
message, you can use any valid XML file to create the document. But because DOMSrcExample
makes the document the entire content of the message, the document must already be in the
form of a valid SOAP message, and not just any XML document.
Building and Running the DOM and DOMSource Examples
When you run DOMExample and DOMSrcExample, you can specify one of two sample XML files in
the directory tut-install/javaeetutorial5/examples/saaj/dom/:
slide.xml
, a file that consists only of a message body
domsrc.xml
, an example that has a SOAP header (the contents of the HeaderExample SOAP
1.1 output) and the same message body as slide.xml
You can use either of these files when you run DOMExample. You can use domsrc.xml to run
DOMSrcExample
.
Code Examples
Chapter 19 · SOAP with Attachments API for Java
619