Project

Profile

Help

Bug #4121 ยป TestResults.java

Gunther Rademacher, 2019-01-29 23:48

 
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;


import net.sf.saxon.jaxp.SaxonTransformerFactory;

public class TestResults
{
private Transformer transformer;
private Transformer identityTransformer;

@Before
public void before() throws Exception {
String xslt =
"<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>\n" +
" <xsl:template match='/'>\n" +
" <xsl:variable name='node'>\n" +
" <xsl:sequence select='.'/>\n" +
" </xsl:variable>\n" +
" <xsl:sequence select='$node/node()'/>\n" +
" </xsl:template>\n" +
"</xsl:stylesheet>";
TransformerFactory transformerFactory = new SaxonTransformerFactory();
transformer = transformerFactory.newTransformer(new StreamSource(new StringReader(xslt)));
omitXmlDeclaration(transformer);
identityTransformer = transformerFactory.newTransformer();
omitXmlDeclaration(identityTransformer);
}

private void omitXmlDeclaration(Transformer transformer)
{
transformer.setOutputProperty("omit-xml-declaration", "yes");
}

@Test
public void testStreamResult() throws Exception
{
String input = "<input/>";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
transformer.transform(new StreamSource(new StringReader(input)), result);
String output = new String(baos.toByteArray(), StandardCharsets.UTF_8);
Assert.assertEquals(input, output);
}

@Test
public void testDomResult() throws Exception
{
String input = "<input/>";
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = documentBuilder.newDocument();
transformer.transform(new StreamSource(new StringReader(input)), new DOMResult(document));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
identityTransformer.transform(new DOMSource(document), result);
String output = new String(baos.toByteArray(), StandardCharsets.UTF_8);
Assert.assertEquals(input, output);
}
}
    (1-1/1)