1
10package org.jstk.wss4axis;
11
12import java.io.ByteArrayInputStream;
13import java.io.ByteArrayOutputStream;
14import java.io.IOException;
15
16import javax.xml.soap.MessageFactory;
17import javax.xml.soap.SOAPMessage;
18import javax.xml.soap.MimeHeaders;
19import javax.xml.soap.SOAPException;
20
21import javax.xml.parsers.DocumentBuilderFactory;
22import javax.xml.parsers.DocumentBuilder;
23import javax.xml.parsers.ParserConfigurationException;
24import javax.xml.transform.TransformerFactory;
25import javax.xml.transform.Transformer;
26import javax.xml.transform.Source;
27import javax.xml.transform.dom.DOMSource;
28import javax.xml.transform.dom.DOMResult;
29import javax.xml.transform.stream.StreamResult;
30import javax.xml.transform.TransformerConfigurationException;
31import javax.xml.transform.TransformerException;
32import org.xml.sax.SAXException;
33import org.w3c.dom.Document;
34
35
36public class SOAPUtility {
37
42 private static class MyByteArrayOutputStream extends ByteArrayOutputStream {
43 public MyByteArrayOutputStream(){
44 super();
45 }
46 public ByteArrayInputStream getByteArrayInputStream(){
47 return new ByteArrayInputStream(buf, 0, count);
48 }
49 }
50
51 public static Document toDocument(SOAPMessage soapMsg) throws
52 ParserConfigurationException, SAXException, SOAPException, IOException {
53 MyByteArrayOutputStream baos = new MyByteArrayOutputStream();
54 soapMsg.writeTo(baos);
55 ByteArrayInputStream bais = baos.getByteArrayInputStream();
56
57 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
58 dbf.setNamespaceAware(true);
59 DocumentBuilder db = dbf.newDocumentBuilder();
60 Document doc = db.parse(bais);
61 return doc;
62 }
63
74 public static SOAPMessage toSOAPMessage(Document doc) throws
75 TransformerConfigurationException, TransformerException, SOAPException, IOException {
76 TransformerFactory tf = TransformerFactory.newInstance();
77 Transformer transformer = tf.newTransformer();
78 MyByteArrayOutputStream baos = new MyByteArrayOutputStream();
79 transformer.transform(new DOMSource(doc), new StreamResult(baos));
80 ByteArrayInputStream bais = baos.getByteArrayInputStream();
81
82 MessageFactory mf = MessageFactory.newInstance();
83 SOAPMessage soapMsg = mf.createMessage(new MimeHeaders(), bais);
84 return soapMsg;
85 }
86
97 public static void main(String[] args) throws Exception {
98 Document doc = XmlUtility.readXML("soap.xml");
99 System.out.println("Document read from file:");
00 XmlUtility.writeXML(doc, System.out);
01 System.out.println();
02
03 SOAPMessage soapMsg = toSOAPMessage(doc);
04 System.out.println("Document converted to SOAPMessage:");
05 soapMsg.writeTo(System.out);
06 System.out.println();
07
08 doc = toDocument(soapMsg);
09 System.out.println("SOAPMessage converted to Document:");
10 XmlUtility.writeXML(doc, System.out);
11 System.out.println();
12 }
13}