Tuesday, March 30, 2010

SOAP with Attachment API for Java (SAAJ) example

SAAJ is an indispensable tool for manipulating SOAP messages, especially if they have got attachments. We have illustrated all the steps in creating a SwA (SOAP Messages with Attachments) in the short self-explanatory example which can be adapted for all purposes.

package saajexample;

import java.awt.Image;
import java.awt.Toolkit;
import javax.xml.soap.*;

public class Main {

public static void main(String[] args) throws Exception {
// Factory needed to create SOAP message
MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
// illustrate the story so far by dumping out the message
message.writeTo(System.out);
// detach the header from the SOAP Envelope
message.getSOAPHeader().detachNode();
System.out.println("");
message.writeTo(System.out);
// manipulate the body of the SOAP message
SOAPBody body = message.getSOAPBody();
SOAPElement getStockPrice = body.addChildElement(
"getStockPrice",
"rt",
"http://www.rajeev.com/jws/StockQuote");
System.out.println("");
message.writeTo(System.out);
getStockPrice.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);
System.out.println("");
message.writeTo(System.out);
SOAPElement code = getStockPrice.addChildElement("stockCode");
System.out.println("");
message.writeTo(System.out);
code.addTextNode("IBM");
System.out.println("");
message.writeTo(System.out);
// attach an image
Image image = Toolkit.getDefaultToolkit().createImage("raj.jpg");
AttachmentPart jpegAttach = message.createAttachmentPart();
// use setDataHandler method below if connecting to FileDataSource object for pdf file
jpegAttach.setContent(image, "image/jpeg");
// add the mime type for the image
jpegAttach.addMimeHeader("Content-Transfer-Encoding", "binary");
jpegAttach.setContentId("xxx");
message.addAttachmentPart(jpegAttach);
System.out.println("");
// message.writeTo(System.out); // cannot stream image
// check attachment created successfully
System.out.printf("Number of attachments: %d%n", message.countAttachments());
// remove the attachment and verify
message.removeAllAttachments();
System.out.printf("Number of attachments: %d%n", message.countAttachments());

}
}

No comments:

Post a Comment