String payload1 = "<tns:myPayload xmlns:tns=\"urn://test\">Payload One</tns:myPayload>";
OMNamespace ns = factory.createOMNamespace("urn://test", "tns");
ByteArrayDataSource bads1 = new ByteArrayDataSource(payload1.getBytes(encoding), encoding);
OMElement parent = factory.createOMElement("root", null);
OMSourcedElement omse = factory.createOMElement(bads1, localName, ns);
parent.addChild(omse);
OMNode firstChild = parent.getFirstOMChild();
assertTrue("Expected OMSourcedElement child", firstChild instanceof OMSourcedElement);
OMSourcedElement child = (OMSourcedElement) firstChild;
assertTrue("OMSourcedElement is expanded. This is unexpected", !child.isExpanded());
assertTrue("OMSourcedElement should be backed by a ByteArrayDataSource",
child.getDataSource() instanceof ByteArrayDataSource);
// A ByteArrayDataSource does not consume the backing object when read.
// Thus getting the XMLStreamReader of the ByteArrayDataSource should not
// cause expansion of the OMSourcedElement.
XMLStreamReader reader = child.getXMLStreamReader();
reader.next();
assertTrue("OMSourcedElement is expanded. This is unexpected", !child.isExpanded());
// Likewise, a ByteArrayDataSource does not consume the backing object when
// written. Thus serializing the OMSourcedElement should not cause the expansion
// of the OMSourcedElement.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
parent.serialize(baos);
String output = baos.toString(encoding);
// System.out.println(output);
assertTrue("The payload was not present in the output",
output.indexOf(payload1) > 0);
assertTrue("OMSourcedElement is expanded. This is unexpected", !child.isExpanded());
// If a consumer calls build or buildWithAttachments on the tree, the
// tree should not be expanded.
parent.build();
assertTrue("OMSourcedElement is expanded after build(). This is unexpected", !child.isExpanded());
parent.buildWithAttachments();
assertTrue("OMSourcedElement is expanded after buildWithAttachments(). This is unexpected", !child.isExpanded());
// Test getting the raw bytes from the ByteArrayDataSource.
OMDataSourceExt ds = (OMDataSourceExt) child.getDataSource();
byte[] bytes = ds.getXMLBytes("UTF-16"); // Get the bytes as UTF-16
String payload = new String(bytes, "utf-16");
assertTrue("The obtained bytes did not match the payload",
payload1.equals(payload));