下面列出了怎么用javax.xml.transform.stream.StreamResult的API类实例代码及写法,或者点击链接到github查看源代码。
private static String nodeToString(Node node) {
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
throw new RuntimeException(te);
}
String asStr = sw.toString();
String xmlDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
String badStart = xmlDecl+"<";
if( asStr.startsWith(badStart) ){ // missing newline after xmlDecl
asStr = xmlDecl+NEWLINE+asStr.substring(xmlDecl.length());
}
// convert the newline character in render-markup elements from
// to 
 (hex encoding of same character), to be consistent
// with the previous XML serializer.
asStr = asStr.replace(" ", "
");
return asStr+NEWLINE;
}
private void removeByXpathExpression(String pomFilePath, String expression) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, TransformerException {
File xmlFile = new File(pomFilePath);
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xpath.compile(expression).
evaluate(doc, XPathConstants.NODESET);
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
node.getParentNode().removeChild(node);
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
// need to convert to file and then to path to override a problem with spaces
Result output = new StreamResult(new File(pomFilePath).getPath());
Source input = new DOMSource(doc);
transformer.transform(input, output);
}
}
@Test
public void getAsXML() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document xmldocument = builder.newDocument();
Element root = xmldocument.createElement("root"); //$NON-NLS-1$
this.sre.getAsXML(xmldocument, root);
xmldocument.appendChild(root);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer trans = transFactory.newTransformer();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
DOMSource source = new DOMSource(xmldocument);
PrintWriter flot = new PrintWriter(baos);
StreamResult xmlStream = new StreamResult(flot);
trans.transform(source, xmlStream);
String content = new String(baos.toByteArray());
String[] expected = new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
"<root libraryPath=\"" + this.path.toPortableString() + "\" standalone=\"false\"/>", };
StringBuilder b = new StringBuilder();
for (String s : expected) {
b.append(s);
// b.append("\n");
}
assertEquals(b.toString(), content);
}
}
/**
* Serializes an Xml document to an array of bytes.
*
* @param doc
* @return the array of bytes representing the Xml document
* @throws IOException
* @throws TransformerException
*/
private byte[] serializeDocument(Document doc) throws IOException, TransformerException {
traceFunc("serializeDocument");
synchronized (this) {
ByteArrayOutputStream s = new ByteArrayOutputStream();
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
DOMSource source = new DOMSource(doc);
StreamResult outputTarget = new StreamResult(s);
transformer.transform(source, outputTarget);
traceFunc("END serializeDocument");
return s.toByteArray();
}
}
@Test
public void renderNoModelKeyAndBindingResultFirst() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
Map<String, Object> model = new LinkedHashMap<>();
model.put(BindingResult.MODEL_KEY_PREFIX + modelKey, new BeanPropertyBindingResult(toBeMarshalled, modelKey));
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
given(marshallerMock.supports(BeanPropertyBindingResult.class)).willReturn(true);
given(marshallerMock.supports(Object.class)).willReturn(true);
view.render(model, request, response);
assertEquals("Invalid content type", "application/xml", response.getContentType());
assertEquals("Invalid content length", 0, response.getContentLength());
verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class));
}
private static final void writeDoc(Document doc, OutputStream out)
throws IOException
{
try {
TransformerFactory tf = TransformerFactory.newInstance();
try {
tf.setAttribute("indent-number", new Integer(2));
} catch (IllegalArgumentException iae) {
}
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(doc),
new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
} catch(TransformerException e) {
throw new AssertionError(e);
}
}
/**
* Marshals the object graph with the given root into the provided {@code javax.xml.transform.Result}.
* <p>This implementation inspects the given result, and calls {@code marshalDomResult},
* {@code marshalSaxResult}, or {@code marshalStreamResult}.
* @param graph the root of the object graph to marshal
* @param result the result to marshal to
* @throws IOException if an I/O exception occurs
* @throws XmlMappingException if the given object cannot be marshalled to the result
* @throws IllegalArgumentException if {@code result} if neither a {@code DOMResult},
* a {@code SAXResult}, nor a {@code StreamResult}
* @see #marshalDomResult(Object, javax.xml.transform.dom.DOMResult)
* @see #marshalSaxResult(Object, javax.xml.transform.sax.SAXResult)
* @see #marshalStreamResult(Object, javax.xml.transform.stream.StreamResult)
*/
@Override
public final void marshal(Object graph, Result result) throws IOException, XmlMappingException {
if (result instanceof DOMResult) {
marshalDomResult(graph, (DOMResult) result);
}
else if (StaxUtils.isStaxResult(result)) {
marshalStaxResult(graph, result);
}
else if (result instanceof SAXResult) {
marshalSaxResult(graph, (SAXResult) result);
}
else if (result instanceof StreamResult) {
marshalStreamResult(graph, (StreamResult) result);
}
else {
throw new IllegalArgumentException("Unknown Result type: " + result.getClass());
}
}
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES)
@FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_INTEGER_VALUES)
@FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = EdgePropertyFeatures.FEATURE_FLOAT_VALUES)
public void shouldTransformGraphMLV2ToV3ViaXSLT() throws Exception {
final InputStream stylesheet = Thread.currentThread().getContextClassLoader().getResourceAsStream("tp2-to-tp3-graphml.xslt");
final InputStream datafile = getResourceAsStream(GraphMLResourceAccess.class, "tinkerpop-classic-tp2.xml");
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final TransformerFactory tFactory = TransformerFactory.newInstance();
final StreamSource stylesource = new StreamSource(stylesheet);
final Transformer transformer = tFactory.newTransformer(stylesource);
final StreamSource source = new StreamSource(datafile);
final StreamResult result = new StreamResult(output);
transformer.transform(source, result);
final GraphReader reader = GraphMLReader.build().create();
reader.readGraph(new ByteArrayInputStream(output.toByteArray()), graph);
assertClassicGraph(graph, false, true);
}
private void report(Map<ReportBuilderImpl.ReportKey, Object> data)
throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory bFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = bFactory.newDocumentBuilder();
// Adds all elements.
final Document doc = docBuilder.newDocument();
final Element root = addRoot(doc, data);
addProcessors(doc, root, data);
addElement(doc, root, data, INPUT, (String) data.get(INPUT));
addElement(doc, root, data, OUTPUT, (String) data.get(OUTPUT));
addElement(doc, root, data, SOURCE_CLASSPATH, (String) data.get(SOURCE_CLASSPATH));
addElement(doc, root, data, PERFORMANCE, Long.toString((Long) data.get(PERFORMANCE)));
// write the content into xml file
TransformerFactory transfFactory = TransformerFactory.newInstance();
Transformer transformer = transfFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(resultFile.getAbsolutePath());
transformer.transform(source, result);
}
@Test
public void testSendingHolidayRequest() {
final String request = "<hr:HolidayRequest xmlns:hr=\"http://joedayz.pe/hr/schemas\">"
+ " <hr:Holiday>"
+ " <hr:StartDate>2013-10-20</hr:StartDate>"
+ " <hr:EndDate>2013-11-22</hr:EndDate>"
+ " </hr:Holiday>"
+ " <hr:Employee>"
+ " <hr:Number>1</hr:Number>"
+ " <hr:FirstName>John</hr:FirstName>"
+ " <hr:LastName>Doe</hr:LastName>"
+ " </hr:Employee>"
+ "</hr:HolidayRequest>";
StreamSource source = new StreamSource(new StringReader(request));
StreamResult result = new StreamResult(System.out);
this.webServiceTemplate.sendSourceAndReceiveToResult(source, result);
assertThat(this.output.toString(),
containsString("Booking holiday for"));
}
/**
* Test for xi:fallback where the fall back text is parsed as text. This
* test uses a nested xi:include for the fallback test.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeFallbackTextPos() throws Exception {
String resultFile = USER_DIR + "doc_fallback_text.out";
String goldFile = GOLDEN_DIR + "doc_fallback_textGold.xml";
String xmlFile = XML_DIR + "doc_fallback_text.xml";
try (FileOutputStream fos = new FileOutputStream(resultFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setXIncludeAware(true);
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile));
doc.setXmlStandalone(true);
TransformerFactory.newInstance().newTransformer()
.transform(new DOMSource(doc), new StreamResult(fos));
}
assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
private static final void writeDoc(Document doc, OutputStream out)
throws IOException
{
try {
TransformerFactory tf = TransformerFactory.newInstance();
try {
tf.setAttribute("indent-number", new Integer(2));
} catch (IllegalArgumentException iae) {
}
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(doc),
new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
} catch(TransformerException e) {
throw new AssertionError(e);
}
}
@Test
public void testXMLSerialisation() throws SAXException, IOException {
FSManifestIterable it = new FSManifestIterable(bundlerepo);
BundleRepoDescriptor repo = new BundleRepoDescriptor(bundlerepo.toURI(),
ExecutionEnvironmentProfileProvider.getInstance());
repo.populate(it.iterator());
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler hd;
try {
hd = tf.newTransformerHandler();
} catch (TransformerConfigurationException e) {
throw new BuildException("Sax configuration error: " + e.getMessage(), e);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamResult stream = new StreamResult(out);
hd.setResult(stream);
OBRXMLWriter.writeManifests(it, hd, false);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
BundleRepoDescriptor repo2 = OBRXMLParser.parse(bundlerepo.toURI(), in);
assertEquals(repo, repo2);
}
/**
* Test newTransformerHandler with a Template Handler.
*
* @throws Exception If any errors occur.
*/
public void testcase08() throws Exception {
String outputFile = USER_DIR + "saxtf008.out";
String goldFile = GOLDEN_DIR + "saxtf008GF.out";
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXTransformerFactory saxTFactory
= (SAXTransformerFactory)TransformerFactory.newInstance();
TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
reader.setContentHandler(thandler);
reader.parse(XSLT_FILE);
TransformerHandler tfhandler
= saxTFactory.newTransformerHandler(thandler.getTemplates());
Result result = new StreamResult(fos);
tfhandler.setResult(result);
reader.setContentHandler(tfhandler);
reader.parse(XML_FILE);
}
assertTrue(compareWithGold(goldFile, outputFile));
}
/**
* Retrieves a list of dependencies of the given scope
*/
public static List<String> getDependencies(String pom, String scope) throws Exception {
String expression = "/project/dependencies/dependency[scope='" + scope + "']";
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(pom);
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(expression);
List<String> dependencies = new LinkedList<>();
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
try (StringWriter writer = new StringWriter()) {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node), new StreamResult(writer));
String xml = writer.toString();
dependencies.add(xml);
}
}
return dependencies;
}
private static InputStream convert(final Source source) {
try {
InputStreamFromOutputStream<Void> isOs = new InputStreamFromOutputStream<Void>() {
protected Void produce(OutputStream sink) throws Exception {
Result result = new StreamResult(sink);
Transformer transformer = ValidatorHelper.TRF.newTransformer();
transformer.setOutputProperty("omit-xml-declaration", "yes");
transformer.transform(source, result);
return null;
}
};
return isOs;
} catch (Exception var2) {
throw new IllegalArgumentException(var2);
}
}
private static InputStream convert(final Source source) {
try {
InputStreamFromOutputStream<Void> isOs = new InputStreamFromOutputStream<Void>() {
protected Void produce(OutputStream sink) throws Exception {
Result result = new StreamResult(sink);
Transformer transformer = ValidatorHelper.TRF.newTransformer();
transformer.setOutputProperty("omit-xml-declaration", "yes");
transformer.transform(source, result);
return null;
}
};
return isOs;
} catch (Exception var2) {
throw new IllegalArgumentException(var2);
}
}
/**
* @param destinationFolder Destination folder for saving the file
* @param fileName Destination file name
* @param doc Document object to be converted to xml formatted file
* @return Returns true if successfully converted
* @brief Converts a given Document object to xml format file
*/
public static boolean saveXmlFile(String destinationFolder, String fileName, Document doc) {
File f = new File(destinationFolder);
if (!f.isDirectory()) {
f.mkdirs();
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer;
try {
File newTemplateFile=new File(destinationFolder + fileName);
if(newTemplateFile.exists())
return false;
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(newTemplateFile);
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
return true;
}
protected String getStringFromDocument(Document doc) {
try {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex) {
ex.printStackTrace();
return null;
}
}
public static String CreateXMLStringFromSubNodeWithoutDeclaration(Element xml) {
xml = xml.getAllElements().first();
String result = "";
try {
StringWriter sw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance()
.newTransformer();
serializer
.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Node fragmentNode = builder.parse(
new InputSource(new StringReader(xml.html())))
.getDocumentElement();
serializer.transform(new DOMSource(fragmentNode), new StreamResult(sw));
result = sw.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
@Test
public void test() {
try {
Source source = new StreamSource(util.BOMInputStream.createStream("UTF-16BE", this.getClass().getResourceAsStream("Hello.wsdl.data")),
this.getClass().getResource("Hello.wsdl.data").toExternalForm());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, new StreamResult(baos));
System.out.println(new String(baos.toByteArray()));
ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
InputSource inSource = new InputSource(bis);
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(inSource.getSystemId(), inSource.getByteStream());
while (reader.hasNext()) {
reader.next();
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
Assert.fail("Exception occured: " + ex.getMessage());
}
}
@Test
public void testDOMSave() throws Exception
{
// load the configuration
final XMLPropertiesConfiguration conf = load(TEST_PROPERTIES_FILE);
// update the configuration
conf.addProperty("key4", "value4");
conf.clearProperty("key2");
conf.setHeader("Description of the new property list");
// save the configuration
final File saveFile = folder.newFile("test2.properties.xml");
// save as DOM into saveFile
final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
final Document document = dBuilder.newDocument();
conf.save(document, document);
final TransformerFactory tFactory = TransformerFactory.newInstance();
final Transformer transformer = tFactory.newTransformer();
final DOMSource source = new DOMSource(document);
final Result result = new StreamResult(saveFile);
transformer.transform(source, result);
// reload the configuration
final XMLPropertiesConfiguration conf2 = load(saveFile.getAbsolutePath());
// test the configuration
assertEquals("header", "Description of the new property list", conf2.getHeader());
assertFalse("The configuration is empty", conf2.isEmpty());
assertEquals("'key1' property", "value1", conf2.getProperty("key1"));
assertEquals("'key3' property", "value3", conf2.getProperty("key3"));
assertEquals("'key4' property", "value4", conf2.getProperty("key4"));
}
/**
* Writes a XML representation of the JAR specification to to the underlying stream.
*
* @param jarPackage the JAR package data
* @exception IOException if writing to the underlying stream fails
*/
public void writeXML(JarPackageData jarPackage) throws IOException {
Assert.isNotNull(jarPackage);
DocumentBuilder docBuilder= null;
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
docBuilder= factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(JarPackagerMessages.JarWriter_error_couldNotGetXmlBuilder);
}
Document document= docBuilder.newDocument();
// Create the document
Element xmlJarDesc= document.createElement(JarPackagerUtil.DESCRIPTION_EXTENSION);
document.appendChild(xmlJarDesc);
xmlWriteJarLocation(jarPackage, document, xmlJarDesc);
xmlWriteOptions(jarPackage, document, xmlJarDesc);
xmlWriteRefactoring(jarPackage, document, xmlJarDesc);
xmlWriteSelectedProjects(jarPackage, document, xmlJarDesc);
if (jarPackage.areGeneratedFilesExported())
xmlWriteManifest(jarPackage, document, xmlJarDesc);
xmlWriteSelectedElements(jarPackage, document, xmlJarDesc);
try {
// Write the document to the stream
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, fEncoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(fOutputStream);
transformer.transform(source, result);
} catch (TransformerException e) {
throw new IOException(JarPackagerMessages.JarWriter_error_couldNotTransformToXML);
}
}
public String documentToString(Document document) throws TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
return writer.getBuffer().toString().replaceAll("\n|\r|\t", "");
}
public static void saveDocument(Document document,File file) {
try {
FileOutputStream fs = new FileOutputStream(file);
// Write it out again
TransformerFactory xformFactory = TransformerFactory.newInstance();
Transformer idTransform = xformFactory.newTransformer();
Source input = new DOMSource(document);
Result output = new StreamResult(fs);
idTransform.setOutputProperty(OutputKeys.INDENT, "yes");
idTransform.transform(input, output);
}catch(Throwable throwable){
throwable.printStackTrace();
}
}
private void transfer(OutputStream out, InputStream dataStream,
InputStream styleStream) throws IOException, TransformerException {
Source data = new StreamSource(dataStream);
Source style = new StreamSource(styleStream);
Result output = new StreamResult(out);
Transformer xslt = TransformerFactory.newInstance().newTransformer(
style);
xslt.transform(data, output);
}
void transform(TransformerFactory factory) throws TransformerConfigurationException, TransformerException {
SAXSource xslSource = new SAXSource(new InputSource(xslFile));
xslSource.setSystemId(xslFileId);
Transformer transformer = factory.newTransformer(xslSource);
StringWriter stringResult = new StringWriter();
Result result = new StreamResult(stringResult);
transformer.transform(new SAXSource(new InputSource(xmlFile)), result);
}
public static InputStream toInputStream(Document doc) throws CarbonException {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Source xmlSource = new DOMSource(doc);
Result result = new StreamResult(outputStream);
TransformerFactory factory = getSecuredTransformerFactory();
factory.newTransformer().transform(xmlSource, result);
InputStream in = new ByteArrayInputStream(outputStream.toByteArray());
return in;
} catch (TransformerException var5) {
throw new CarbonException("Error in transforming DOM to InputStream", var5);
}
}
@Test
@Ignore("No contract to call endDocument() in case of an Exception")
public void testX32ContentHandlerAsWriterError() throws Exception {
CloseObservableWriter cow = new CloseObservableWriter() {
@Override
public void write(char[] arg0, int arg1, int arg2) {
throw new RuntimeException("fakeFailure");
}
};
Result result = new StreamResult(cow);
SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler transformerHandler = tf.newTransformerHandler();
transformerHandler.setResult(result);
try (MessageOutputStream stream = new MessageOutputStream(null, transformerHandler, (IForwardTarget)null, null, null)) {
try {
try (Writer writer = stream.asWriter()) {
writer.write(testString);
}
fail("exception should be thrown");
} catch (Exception e) {
assertThat(e.getMessage(),StringContains.containsString("fakeFailure"));
}
}
assertTrue(cow.isCloseCalled());
}
void doOneTestIteration() throws Exception {
// Prepare output stream
StringWriter xmlResultString = new StringWriter();
StreamResult xmlResultStream = new StreamResult(xmlResultString);
// Prepare xml source stream
Source src = new StreamSource(new StringReader(xml));
Transformer t = createTransformer();
//Transform the xml
t.transform(src, xmlResultStream);
}