import java.io.InputStream;
import java.io.StringWriter;
public class AttachmentsTest extends AbstractTestCase {
public void testWritingBinaryAttachments() throws Exception {
MIMEResource testMessage = TestConstants.MTOM_MESSAGE;
// Read in message: SOAPPart and 2 image attachments
InputStream inStream = getTestResource(testMessage.getName());
Attachments attachments = new Attachments(inStream, testMessage.getContentType());
attachments.getRootPartInputStream();
String[] contentIDs = attachments.getAllContentIDs();
OMOutputFormat oof = new OMOutputFormat();
oof.setDoOptimize(true);
oof.setMimeBoundary(testMessage.getBoundary());
oof.setRootContentId(testMessage.getStart());
// Write out the message
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(baos, oof);
OMXMLParserWrapper builder =
OMXMLBuilderFactory.createOMBuilder(StAXParserConfiguration.DEFAULT, attachments);
OMElement om = builder.getDocumentElement();
om.serialize(writer);
om.close(false);
String outNormal = baos.toString();
assertTrue(outNormal.indexOf("base64") == -1);
// Now do it again but use base64 content-type-encoding for
// binary attachments
baos = new ByteArrayOutputStream();
oof.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS,
Boolean.TRUE);
writer = new MTOMXMLStreamWriter(baos, oof);
builder =
OMXMLBuilderFactory.createOMBuilder(StAXParserConfiguration.DEFAULT, attachments);
om = builder.getDocumentElement();
om.serialize(writer);
om.close(false);
String outBase64 = baos.toString();
// Do a quick check to see if the data is base64 and is
// writing base64 compliant code.
assertTrue(outBase64.indexOf("base64") != -1);
assertTrue(outBase64.indexOf("GBgcGBQgHBwcJCQgKDBQNDAsL") != -1);
// Now read the data back in
InputStream is = new ByteArrayInputStream(outBase64.getBytes());
Attachments attachments2 = new Attachments(is, testMessage.getContentType());
// Now write it back out with binary...
baos = new ByteArrayOutputStream();
oof.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS,
Boolean.FALSE);
writer = new MTOMXMLStreamWriter(baos, oof);
builder =
OMXMLBuilderFactory.createOMBuilder(StAXParserConfiguration.DEFAULT, attachments2);
om = builder.getDocumentElement();
om.serialize(writer);
om.close(false);
String outBase64ToNormal = baos.toString();
assertTrue(outBase64ToNormal.indexOf("base64") == -1);
// Now do it again but use base64 content-type-encoding for
// binary attachments
is = new ByteArrayInputStream(outBase64.getBytes());
attachments2 = new Attachments(is, testMessage.getContentType());
baos = new ByteArrayOutputStream();
oof.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS,
Boolean.TRUE);
writer = new MTOMXMLStreamWriter(baos, oof);
builder =