8173602: JAXP: TESTBUG: javax/xml/jaxp/unittest/transform/TransformerTest.java needs refactoring

Reviewed-by: dfuchs
This commit is contained in:
Christoph Langer 2017-02-06 11:03:48 +01:00
parent 509dfad588
commit 3a9453a2ef
2 changed files with 584 additions and 393 deletions

View File

@ -24,32 +24,32 @@
package transform; package transform;
import static jaxp.library.JAXPTestUtilities.getSystemProperty; import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import static jaxp.library.JAXPTestUtilities.tryRunWithTmpPermission;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter; import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource; import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.testng.Assert; import org.testng.Assert;
import org.testng.AssertJUnit; import org.testng.AssertJUnit;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners; import org.testng.annotations.Listeners;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.w3c.dom.Document; import org.w3c.dom.Document;
@ -67,8 +67,7 @@ import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader; import org.xml.sax.XMLReader;
import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.AttributesImpl;
import com.sun.org.apache.xml.internal.serialize.OutputFormat; import transform.util.TransformerTestTemplate;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
/* /*
* @test * @test
@ -91,38 +90,92 @@ public class TransformerTest {
private static final String NAMESPACE_PREFIXES = private static final String NAMESPACE_PREFIXES =
"http://xml.org/sax/features/namespace-prefixes"; "http://xml.org/sax/features/namespace-prefixes";
private static abstract class TestTemplate { public static class Test6272879 extends TransformerTestTemplate {
protected void printSnippet(String title, String snippet) {
StringBuilder div = new StringBuilder(); private static String XSL_INPUT =
for (int i = 0; i < title.length(); i++) "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + LINE_SEPARATOR +
div.append("="); "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + LINE_SEPARATOR +
System.out.println(title + "\n" + div + "\n" + snippet + "\n"); "<xsl:output method=\"xml\" indent=\"no\" encoding=\"ISO-8859-1\"/>" + LINE_SEPARATOR +
} "<xsl:template match=\"/\">" + LINE_SEPARATOR +
"<xsl:element name=\"TransformateurXML\">" + LINE_SEPARATOR +
" <xsl:for-each select=\"XMLUtils/test\">" + LINE_SEPARATOR +
" <xsl:element name=\"test2\">" + LINE_SEPARATOR +
" <xsl:element name=\"valeur2\">" + LINE_SEPARATOR +
" <xsl:attribute name=\"attribut2\">" + LINE_SEPARATOR +
" <xsl:value-of select=\"valeur/@attribut\"/>" + LINE_SEPARATOR +
" </xsl:attribute>" + LINE_SEPARATOR +
" <xsl:value-of select=\"valeur\"/>" + LINE_SEPARATOR +
" </xsl:element>" + LINE_SEPARATOR +
" </xsl:element>" + LINE_SEPARATOR +
" </xsl:for-each>" + LINE_SEPARATOR +
"</xsl:element>" + LINE_SEPARATOR +
"</xsl:template>" + LINE_SEPARATOR +
"</xsl:stylesheet>";
private static String XML_INPUT =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + LINE_SEPARATOR +
// "<!DOCTYPE XMLUtils [" + LINE_SEPARATOR +
// "<!ELEMENT XMLUtils (test*)>" + LINE_SEPARATOR +
// "<!ELEMENT test (valeur*)>" + LINE_SEPARATOR +
// "<!ELEMENT valeur (#PCDATA)>" + LINE_SEPARATOR +
// "<!ATTLIST valeur attribut CDATA #REQUIRED>]>" +
// LINE_SEPARATOR +
"<XMLUtils>" + LINE_SEPARATOR +
" <test>" + LINE_SEPARATOR +
" <valeur attribut=\"Attribut 1\">Valeur 1</valeur>" + LINE_SEPARATOR +
" </test>" + LINE_SEPARATOR +
" <test>" + LINE_SEPARATOR +
" <valeur attribut=\"Attribut 2\">Valeur 2</valeur>" + LINE_SEPARATOR +
" </test>" + LINE_SEPARATOR +
"</XMLUtils>";
public Test6272879() {
super(XSL_INPUT, XML_INPUT);
} }
/** /*
* Reads the contents of the given file into a string. * @bug 6272879
* WARNING: this method adds a final line feed even if the last line of the file doesn't contain one. * @summary Test for JDK-6272879
* * DomResult had truncated Strings in some places
* @param f
* The file to read
* @return The content of the file as a string, with line terminators as \"n"
* for all platforms
* @throws IOException
* If there was an error reading
*/ */
private String getFileContentAsString(File f) throws IOException { @Test
try (BufferedReader reader = new BufferedReader(new FileReader(f))) { public void run() throws TransformerException, ClassNotFoundException, InstantiationException,
String line; IllegalAccessException, ClassCastException
StringBuilder sb = new StringBuilder(); {
while ((line = reader.readLine()) != null) { // print input
sb.append(line).append("\n"); printSnippet("Stylesheet:", getXsl());
printSnippet("Source before transformation:", getSourceXml());
// transform to DOM result
Transformer t = getTransformer();
DOMResult result = new DOMResult();
t.transform(getStreamSource(), result);
// print output
printSnippet("Result after transformation:", prettyPrintDOMResult(result));
// do some assertions
Document document = (Document)result.getNode();
NodeList nodes = document.getElementsByTagName("valeur2");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
AssertJUnit.assertEquals("Node value mismatch",
"Valeur " + (i + 1),
node.getFirstChild().getNodeValue());
AssertJUnit.assertEquals("Node attribute mismatch",
"Attribut " + (i + 1),
node.getAttributes().item(0).getNodeValue());
} }
return sb.toString();
} }
} }
private class XMLReaderFor6305029 implements XMLReader { public static class Test6305029 extends TransformerTestTemplate {
private static String XML_INPUT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<prefix:localName xmlns:prefix=\"namespaceUri\"/>";
// custom XMLReader representing XML_INPUT
private class MyXMLReader implements XMLReader {
private boolean namespaces = true; private boolean namespaces = true;
private boolean namespacePrefixes = false; private boolean namespacePrefixes = false;
private EntityResolver resolver; private EntityResolver resolver;
@ -213,108 +266,44 @@ public class TransformerTest {
} }
} }
/* public Test6305029() {
* @bug 6272879 super(null, XML_INPUT);
* @summary Test for JDK-6272879
*/
@Test
public final void testBug6272879() throws Exception {
final String xsl =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + LINE_SEPARATOR +
"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + LINE_SEPARATOR +
"<xsl:output method=\"xml\" indent=\"no\" encoding=\"ISO-8859-1\"/>" + LINE_SEPARATOR +
"<xsl:template match=\"/\">" + LINE_SEPARATOR +
"<xsl:element name=\"TransformateurXML\">" + LINE_SEPARATOR +
" <xsl:for-each select=\"XMLUtils/test\">" + LINE_SEPARATOR +
" <xsl:element name=\"test2\">" + LINE_SEPARATOR +
" <xsl:element name=\"valeur2\">" + LINE_SEPARATOR +
" <xsl:attribute name=\"attribut2\">" + LINE_SEPARATOR +
" <xsl:value-of select=\"valeur/@attribut\"/>" + LINE_SEPARATOR +
" </xsl:attribute>" + LINE_SEPARATOR +
" <xsl:value-of select=\"valeur\"/>" + LINE_SEPARATOR +
" </xsl:element>" + LINE_SEPARATOR +
" </xsl:element>" + LINE_SEPARATOR +
" </xsl:for-each>" + LINE_SEPARATOR +
"</xsl:element>" + LINE_SEPARATOR +
"</xsl:template>" + LINE_SEPARATOR +
"</xsl:stylesheet>";
final String sourceXml =
"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + LINE_SEPARATOR +
// "<!DOCTYPE XMLUtils [" + LINE_SEPARATOR +
// "<!ELEMENT XMLUtils (test*)>" + LINE_SEPARATOR +
// "<!ELEMENT test (valeur*)>" + LINE_SEPARATOR +
// "<!ELEMENT valeur (#PCDATA)>" + LINE_SEPARATOR +
// "<!ATTLIST valeur attribut CDATA #REQUIRED>]>" +
// LINE_SEPARATOR +
"<XMLUtils>" + LINE_SEPARATOR +
" <test>" + LINE_SEPARATOR +
" <valeur attribut=\"Attribut 1\">Valeur 1</valeur>" + LINE_SEPARATOR +
" </test>" + LINE_SEPARATOR +
" <test>" + LINE_SEPARATOR +
" <valeur attribut=\"Attribut 2\">Valeur 2</valeur>" + LINE_SEPARATOR +
" </test>" + LINE_SEPARATOR +
"</XMLUtils>";
System.out.println("Stylesheet:");
System.out.println("=============================");
System.out.println(xsl);
System.out.println();
System.out.println("Source before transformation:");
System.out.println("=============================");
System.out.println(sourceXml);
System.out.println();
// transform to DOM result
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(new StreamSource(new ByteArrayInputStream(xsl.getBytes())));
DOMResult result = new DOMResult();
t.transform(new StreamSource(new ByteArrayInputStream(sourceXml.getBytes())), result);
Document document = (Document)result.getNode();
System.out.println("Result after transformation:");
System.out.println("============================");
tryRunWithTmpPermission(() -> {
OutputFormat format = new OutputFormat();
format.setIndenting(true);
new XMLSerializer(System.out, format).serialize(document);
}, new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.serialize"));
System.out.println();
System.out.println("Node content for element valeur2:");
System.out.println("=================================");
NodeList nodes = document.getElementsByTagName("valeur2");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
System.out.println(" Node value: " + node.getFirstChild().getNodeValue());
System.out.println(" Node attribute: " + node.getAttributes().item(0).getNodeValue());
AssertJUnit.assertEquals("Node value mismatch", "Valeur " + (i + 1), node.getFirstChild().getNodeValue());
AssertJUnit.assertEquals("Node attribute mismatch", "Attribut " + (i + 1), node.getAttributes().item(0).getNodeValue());
}
} }
/* /*
* @bug 6305029 * @bug 6305029
* @summary Test for JDK-6305029 * @summary Test for JDK-6305029
* Test identity transformation
*/ */
@Test @Test
public final void testBug6305029() throws TransformerException { public void run() throws TransformerFactoryConfigurationError, TransformerException {
final String XML_DOCUMENT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<prefix:localName xmlns:prefix=\"namespaceUri\"/>"; // get Identity transformer
Transformer t = getTransformer();
// test SAXSource // test SAXSource from custom XMLReader
SAXSource saxSource = new SAXSource(new XMLReaderFor6305029(), new InputSource()); SAXSource saxSource = new SAXSource(new MyXMLReader(), new InputSource());
StringWriter resultWriter = new StringWriter(); StringWriter resultWriter = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance(); t.transform(saxSource, new StreamResult(resultWriter));
tf.newTransformer().transform(saxSource, new StreamResult(resultWriter)); String resultString = resultWriter.toString();
AssertJUnit.assertEquals("Identity transform of SAXSource", XML_DOCUMENT, resultWriter.toString()); printSnippet("Result after transformation from custom SAXSource:", resultString);
AssertJUnit.assertEquals("Identity transform of SAXSource", getSourceXml(), resultString);
// test StreamSource // test StreamSource
StreamSource streamSource = new StreamSource(new StringReader(XML_DOCUMENT)); printSnippet("Source before transformation of StreamSource:", getSourceXml());
resultWriter = new StringWriter(); resultWriter = new StringWriter();
tf.newTransformer().transform(streamSource, new StreamResult(resultWriter)); t.transform(getStreamSource(), new StreamResult(resultWriter));
AssertJUnit.assertEquals("Identity transform of StreamSource", XML_DOCUMENT, resultWriter.toString()); resultString = resultWriter.toString();
printSnippet("Result after transformation of StreamSource:", resultString);
AssertJUnit.assertEquals("Identity transform of StreamSource", getSourceXml(), resultString);
}
}
public static class Test6505031 extends TransformerTestTemplate {
public Test6505031() throws IOException {
super();
setXsl(fromInputStream(getClass().getResourceAsStream("transform.xsl")));
setSourceXml(fromInputStream(getClass().getResourceAsStream("template.xml")));
} }
/* /*
@ -322,19 +311,20 @@ public class TransformerTest {
* @summary Test transformer parses keys and their values coming from different xml documents. * @summary Test transformer parses keys and their values coming from different xml documents.
*/ */
@Test @Test
public final void testBug6505031() throws TransformerException { public void run() throws TransformerFactoryConfigurationError, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = getTransformer();
Transformer t = tf.newTransformer(new StreamSource(getClass().getResource("transform.xsl").toString()));
t.setParameter("config", getClass().getResource("config.xml").toString()); t.setParameter("config", getClass().getResource("config.xml").toString());
t.setParameter("mapsFile", getClass().getResource("maps.xml").toString()); t.setParameter("mapsFile", getClass().getResource("maps.xml").toString());
StringWriter sw = new StringWriter(); StringWriter resultWriter = new StringWriter();
t.transform(new StreamSource(getClass().getResource("template.xml").toString()), new StreamResult(sw)); t.transform(getStreamSource(), new StreamResult(resultWriter));
String s = sw.toString(); String resultString = resultWriter.toString();
Assert.assertTrue(s.contains("map1key1value") && s.contains("map2key1value")); Assert.assertTrue(resultString.contains("map1key1value") && resultString.contains("map2key1value"));
}
} }
private static class Test8169631 extends TestTemplate { public static class Test8169631 extends TransformerTestTemplate {
private final static String xsl =
private static String XSL_INPUT =
"<?xml version=\"1.0\"?>" + LINE_SEPARATOR + "<?xml version=\"1.0\"?>" + LINE_SEPARATOR +
"<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + LINE_SEPARATOR + "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + LINE_SEPARATOR +
" <xsl:template match=\"/\">" + LINE_SEPARATOR + " <xsl:template match=\"/\">" + LINE_SEPARATOR +
@ -345,7 +335,7 @@ public class TransformerTest {
" </xsl:template>" + LINE_SEPARATOR + " </xsl:template>" + LINE_SEPARATOR +
"</xsl:stylesheet>" + LINE_SEPARATOR; "</xsl:stylesheet>" + LINE_SEPARATOR;
private final static String sourceXml = private static String XML_INPUT =
"<?xml version=\"1.0\"?>" + LINE_SEPARATOR + "<?xml version=\"1.0\"?>" + LINE_SEPARATOR +
"<envelope xmlns=\"http://www.sap.com/myns\" xmlns:sap=\"http://www.sap.com/myns\">" + LINE_SEPARATOR + "<envelope xmlns=\"http://www.sap.com/myns\" xmlns:sap=\"http://www.sap.com/myns\">" + LINE_SEPARATOR +
" <sap:row sap:attrib=\"a\">1</sap:row>" + LINE_SEPARATOR + " <sap:row sap:attrib=\"a\">1</sap:row>" + LINE_SEPARATOR +
@ -353,6 +343,10 @@ public class TransformerTest {
" <row sap:attrib=\"c\">3</row>" + LINE_SEPARATOR + " <row sap:attrib=\"c\">3</row>" + LINE_SEPARATOR +
"</envelope>" + LINE_SEPARATOR; "</envelope>" + LINE_SEPARATOR;
public Test8169631() {
super(XSL_INPUT, XML_INPUT);
}
/** /**
* Utility method to print out transformation result and check values. * Utility method to print out transformation result and check values.
* *
@ -380,60 +374,50 @@ public class TransformerTest {
type + " should have count of "+ attribCount + " attributes."); type + " should have count of "+ attribCount + " attributes.");
} }
public void run() throws IOException, TransformerException, @DataProvider(name = "testdata8169631")
SAXException, ParserConfigurationException public Object[][] testData()
throws TransformerConfigurationException, SAXException, IOException,
ParserConfigurationException, XMLStreamException
{ {
printSnippet("Source:", sourceXml); // get Transformers
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = getTransformer(tf);
Transformer tFromTemplates = getTemplates(tf).newTransformer();
printSnippet("Stylesheet:", xsl); // get DOMSource objects
// create default transformer (namespace aware)
TransformerFactory tf1 = TransformerFactory.newInstance();
ByteArrayInputStream bais = new ByteArrayInputStream(xsl.getBytes());
Transformer t1 = tf1.newTransformer(new StreamSource(bais));
// test transformation from stream source with namespace support
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bais = new ByteArrayInputStream(sourceXml.getBytes());
t1.transform(new StreamSource(bais), new StreamResult(baos));
verifyResult("StreamSource with namespace support", baos.toString(), 0, 1);
// test transformation from DOM source with namespace support
bais.reset();
baos.reset();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DOMSource domSourceWithoutNS = getDOMSource(dbf);
dbf.setNamespaceAware(true); dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new InputSource(bais)); DOMSource domSourceWithNS = getDOMSource(dbf);
t1.transform(new DOMSource(doc), new StreamResult(baos));
verifyResult("DOMSource with namespace support", baos.toString(), 0, 1);
// test transformation from DOM source without namespace support // get SAXSource objects
bais.reset();
baos.reset();
dbf.setNamespaceAware(false);
doc = dbf.newDocumentBuilder().parse(new InputSource(bais));
t1.transform(new DOMSource(doc), new StreamResult(baos));
verifyResult("DOMSource without namespace support", baos.toString(), 3, 3);
// test transformation from SAX source with namespace support
bais.reset();
baos.reset();
SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParserFactory spf = SAXParserFactory.newInstance();
SAXSource saxSourceWithoutNS = getSAXSource(spf);
spf.setNamespaceAware(true); spf.setNamespaceAware(true);
XMLReader xmlr = spf.newSAXParser().getXMLReader(); SAXSource saxSourceWithNS = getSAXSource(spf);
SAXSource saxS = new SAXSource(xmlr, new InputSource(bais));
t1.transform(saxS, new StreamResult(baos));
verifyResult("SAXSource with namespace support", baos.toString(), 0, 1);
// test transformation from SAX source without namespace support // get StAXSource objects
bais.reset(); XMLInputFactory xif = XMLInputFactory.newInstance();
baos.reset(); StAXSource staxSourceWithNS = getStAXSource(xif);
spf.setNamespaceAware(false);
xmlr = spf.newSAXParser().getXMLReader(); // print XML/XSL snippets to ease understanding of result
saxS = new SAXSource(xmlr, new InputSource(bais)); printSnippet("Source:", getSourceXml());
t1.transform(saxS, new StreamResult(baos)); printSnippet("Stylesheet:", getXsl());
verifyResult("SAXSource without namespace support", baos.toString(), 3, 3);
} return new Object[][] {
// test StreamSource input with all transformers
// namespace awareness is set by transformer
{t, getStreamSource(), "StreamSource with namespace support", 0, 1},
{tFromTemplates, getStreamSource(), "StreamSource with namespace support using templates", 0, 1},
// now test DOMSource, SAXSource and StAXSource
// with rotating use of created transformers
// namespace awareness is set by source objects
{t, domSourceWithNS, "DOMSource with namespace support", 0, 1},
{t, domSourceWithoutNS, "DOMSource without namespace support", 3, 3},
{tFromTemplates, saxSourceWithNS, "SAXSource with namespace support", 0, 1},
{tFromTemplates, saxSourceWithoutNS, "SAXSource without namespace support", 3, 3},
{t, staxSourceWithNS, "StAXSource with namespace support", 0, 1}
};
} }
/* /*
@ -441,11 +425,28 @@ public class TransformerTest {
* @summary Test combinations of namespace awareness settings on * @summary Test combinations of namespace awareness settings on
* XSL transformations * XSL transformations
*/ */
@Test @Test(dataProvider = "testdata8169631")
public final void testBug8169631() throws IOException, SAXException, public void run(Transformer t, Source s, String label, int elementcount, int attributecount)
TransformerException, ParserConfigurationException throws TransformerException
{ {
new Test8169631().run(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.transform(s, new StreamResult(baos));
verifyResult(label, baos.toString(), elementcount, attributecount);
}
}
public static class Test8150704 extends TransformerTestTemplate {
public Test8150704() {
super();
}
@DataProvider(name = "testdata8150704")
public Object[][] testData() {
return new Object[][] {
{"Bug8150704-1.xsl", "Bug8150704-1.xml", "Bug8150704-1.ref"},
{"Bug8150704-2.xsl", "Bug8150704-2.xml", "Bug8150704-2.ref"}
};
} }
/* /*
@ -453,30 +454,24 @@ public class TransformerTest {
* @summary Test that XSL transformation with lots of temporary result * @summary Test that XSL transformation with lots of temporary result
* trees will not run out of DTM IDs. * trees will not run out of DTM IDs.
*/ */
@Test @Test(dataProvider = "testdata8150704")
public final void testBug8150704() throws TransformerException, IOException { public void run(String xsl, String xml, String ref) throws IOException, TransformerException {
System.out.println("Testing transformation of Bug8150704-1.xml..."); System.out.println("Testing transformation of " + xml + "...");
TransformerFactory tf = TransformerFactory.newInstance(); setXsl(fromInputStream(getClass().getResourceAsStream(xsl)));
Transformer t = tf.newTransformer(new StreamSource(getClass().getResource("Bug8150704-1.xsl").toString())); setSourceXml(fromInputStream(getClass().getResourceAsStream(xml)));
StringWriter sw = new StringWriter(); Transformer t = getTransformer();
t.transform(new StreamSource(getClass().getResource("Bug8150704-1.xml").toString()), new StreamResult(sw)); StringWriter resultWriter = new StringWriter();
String resultstring = sw.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); t.transform(getStreamSource(), new StreamResult(resultWriter));
String reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-1.ref").getPath())); String resultString = resultWriter.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n").trim();
Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-1.xml does not match reference"); String reference = fromInputStream(getClass().getResourceAsStream(ref)).trim();
System.out.println("Passed."); Assert.assertEquals(resultString, reference, "Output of transformation of " + xml + " does not match reference");
System.out.println("Testing transformation of Bug8150704-2.xml...");
t = tf.newTransformer(new StreamSource(getClass().getResource("Bug8150704-2.xsl").toString()));
sw = new StringWriter();
t.transform(new StreamSource(getClass().getResource("Bug8150704-2.xml").toString()), new StreamResult(sw));
resultstring = sw.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n");
reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-2.ref").getPath()));
Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-2.xml does not match reference");
System.out.println("Passed."); System.out.println("Passed.");
} }
}
private static class Test8162598 extends TestTemplate { public static class Test8162598 extends TransformerTestTemplate {
private static final String xsl =
private static String XSL_INPUT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + LINE_SEPARATOR + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + LINE_SEPARATOR +
"<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + LINE_SEPARATOR + "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + LINE_SEPARATOR +
" <xsl:template match=\"/\">" + LINE_SEPARATOR + " <xsl:template match=\"/\">" + LINE_SEPARATOR +
@ -494,8 +489,13 @@ public class TransformerTest {
" </xsl:template>" + LINE_SEPARATOR + " </xsl:template>" + LINE_SEPARATOR +
"</xsl:stylesheet>"; "</xsl:stylesheet>";
private static final String sourceXml = private static String XML_INPUT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><aaa></aaa>" + LINE_SEPARATOR; "<?xml version=\"1.0\" encoding=\"UTF-8\"?><aaa></aaa>" + LINE_SEPARATOR;
public Test8162598() {
super(XSL_INPUT, XML_INPUT);
}
/** /**
* Utility method for testBug8162598(). * Utility method for testBug8162598().
* Provides a convenient way to check/assert the expected namespaces * Provides a convenient way to check/assert the expected namespaces
@ -510,7 +510,6 @@ public class TransformerTest {
* @param nsc * @param nsc
* Expected namespace of the first sibling of the first sibling * Expected namespace of the first sibling of the first sibling
*/ */
private void checkNodeNS(Node test, String nstest, String nsb, String nsc) { private void checkNodeNS(Node test, String nstest, String nsb, String nsc) {
String testNodeName = test.getNodeName(); String testNodeName = test.getNodeName();
if (nstest == null) { if (nstest == null) {
@ -532,29 +531,27 @@ public class TransformerTest {
} }
} }
/*
* @bug 8162598
* @summary Test XSLTC handling of namespaces, especially empty namespace
* definitions to reset the default namespace
*/
@Test
public void run() throws Exception { public void run() throws Exception {
printSnippet("Source:", sourceXml); // print input
printSnippet("Source:", getSourceXml());
printSnippet("Stylesheet:", xsl); printSnippet("Stylesheet:", getXsl());
// transform to DOM result // transform to DOM result
TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = getTransformer();
ByteArrayInputStream bais = new ByteArrayInputStream(xsl.getBytes());
Transformer t = tf.newTransformer(new StreamSource(bais));
DOMResult result = new DOMResult(); DOMResult result = new DOMResult();
bais = new ByteArrayInputStream(sourceXml.getBytes()); t.transform(getStreamSource(), result);
t.transform(new StreamSource(bais), result);
// print output
printSnippet("Result after transformation:", prettyPrintDOMResult(result));
// do some verifications
Document document = (Document)result.getNode(); Document document = (Document)result.getNode();
System.out.println("Result after transformation:");
System.out.println("============================");
tryRunWithTmpPermission(() -> {
OutputFormat format = new OutputFormat();
format.setIndenting(true);
new XMLSerializer(System.out, format).serialize(document);
}, new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.serialize"));
System.out.println();
checkNodeNS(document.getElementsByTagName("test1").item(0), "ns2", "ns2", null); checkNodeNS(document.getElementsByTagName("test1").item(0), "ns2", "ns2", null);
checkNodeNS(document.getElementsByTagName("test2").item(0), "ns1", "ns2", null); checkNodeNS(document.getElementsByTagName("test2").item(0), "ns1", "ns2", null);
checkNodeNS(document.getElementsByTagName("test3").item(0), null, null, null); checkNodeNS(document.getElementsByTagName("test3").item(0), null, null, null);
@ -565,17 +562,19 @@ public class TransformerTest {
} }
} }
/* public static class Test8169112 extends TransformerTestTemplate{
* @bug 8162598
* @summary Test XSLTC handling of namespaces, especially empty namespace public static String XML_INPUT =
* definitions to reset the default namespace "<?xml version=\"1.0\"?><DOCROOT/>";
*/
@Test public Test8169112() throws IOException {
public final void testBug8162598() throws Exception { super();
new Test8162598().run(); setXsl(fromInputStream(getClass().getResourceAsStream("Bug8169112.xsl")));
setSourceXml(XML_INPUT);
} }
/** /**
* @throws TransformerException
* @bug 8169112 * @bug 8169112
* @summary Test compilation of large xsl file with outlining. * @summary Test compilation of large xsl file with outlining.
* *
@ -584,29 +583,19 @@ public class TransformerTest {
* dummy content. The test succeeds if no Exception is thrown * dummy content. The test succeeds if no Exception is thrown
*/ */
@Test @Test
public final void testBug8169112() throws FileNotFoundException, public void run() throws TransformerException {
TransformerException Transformer t = getTransformer();
{ t.transform(getStreamSource(), new StreamResult(new ByteArrayOutputStream()));
TransformerFactory tf = TransformerFactory.newInstance(); }
String xslFile = getClass().getResource("Bug8169112.xsl").toString();
Transformer t = tf.newTransformer(new StreamSource(xslFile));
String xmlIn = "<?xml version=\"1.0\"?><DOCROOT/>";
ByteArrayInputStream bis = new ByteArrayInputStream(xmlIn.getBytes());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new StreamSource(bis), new StreamResult(bos));
} }
/** public static class Test8169772 extends TransformerTestTemplate {
* @bug 8169772
* @summary Test transformation of DOM with null valued text node public Test8169772() {
* super();
* This test would throw a NullPointerException during transform when the }
* fix was not present.
*/ private Document getDOMWithBadElement() throws SAXException, IOException, ParserConfigurationException {
@Test
public final void testBug8169772() throws ParserConfigurationException,
SAXException, IOException, TransformerException
{
// create a small DOM // create a small DOM
Document doc = DocumentBuilderFactory.newInstance(). Document doc = DocumentBuilderFactory.newInstance().
newDocumentBuilder().parse( newDocumentBuilder().parse(
@ -620,13 +609,27 @@ public class TransformerTest {
e.appendChild(doc.createTextNode(null)); e.appendChild(doc.createTextNode(null));
doc.getDocumentElement().appendChild(e); doc.getDocumentElement().appendChild(e);
// transform return doc;
ByteArrayOutputStream bos = new ByteArrayOutputStream(); }
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(doc.getDocumentElement()), new StreamResult(bos) /**
); * @throws ParserConfigurationException
System.out.println("Transformation result (DOM with null text node):"); * @throws IOException
System.out.println("================================================"); * @throws SAXException
System.out.println(bos); * @throws TransformerException
* @bug 8169772
* @summary Test transformation of DOM with null valued text node
*
* This test would throw a NullPointerException during transform when the
* fix was not present.
*/
@Test
public void run() throws SAXException, IOException, ParserConfigurationException, TransformerException {
Transformer t = getTransformer();
StringWriter resultWriter = new StringWriter();
DOMSource d = new DOMSource(getDOMWithBadElement().getDocumentElement());
t.transform(d, new StreamResult(resultWriter));
printSnippet("Transformation result (DOM with null text node):", resultWriter.toString());
}
} }
} }

View File

@ -0,0 +1,188 @@
/*
* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package transform.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.stream.Collectors;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/*
* Template for Transformer tests
*/
public abstract class TransformerTestTemplate {
private String xsl = null;
private String sourceXml = null;
public TransformerTestTemplate() {
super();
}
public TransformerTestTemplate(String xsl, String sourceXml) {
super();
this.xsl = xsl;
this.sourceXml = sourceXml;
}
public String getXsl() {
return xsl;
}
public void setXsl(String xsl) {
this.xsl = xsl;
}
public String getSourceXml() {
return sourceXml;
}
public void setSourceXml(String sourceXml) {
this.sourceXml = sourceXml;
}
public String fromInputStream(InputStream is) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
return br.lines().collect(Collectors.joining("\n"));
}
}
// print an XML Snippet under a given title
public void printSnippet(String title, String snippet) {
StringBuilder div = new StringBuilder();
for (int i = 0; i < title.length(); i++)
div.append("=");
System.out.println(title + "\n" + div + "\n" + snippet + "\n");
}
// pretty print a DOMResult
public String prettyPrintDOMResult(DOMResult dr) throws ClassNotFoundException, InstantiationException,
IllegalAccessException, ClassCastException
{
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domImplementationLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
StringWriter writer = new StringWriter();
LSOutput formattedOutput = domImplementationLS.createLSOutput();
formattedOutput.setCharacterStream(writer);
LSSerializer domSerializer = domImplementationLS.createLSSerializer();
domSerializer.getDomConfig().setParameter("format-pretty-print", true);
domSerializer.getDomConfig().setParameter("xml-declaration", false);
domSerializer.write(dr.getNode(), formattedOutput);
return writer.toString();
}
public Transformer getTransformer() throws TransformerConfigurationException {
return getTransformer(null);
}
// utility to obtain Transformer from TransformerFactory
public Transformer getTransformer(TransformerFactory tf)
throws TransformerConfigurationException
{
if (tf == null) {
tf = TransformerFactory.newInstance();
}
if (xsl == null) {
return tf.newTransformer();
} else {
return tf.newTransformer(
new StreamSource(new ByteArrayInputStream(xsl.getBytes()))
);
}
}
// utility to obtain Templates from TransformerFactory
public Templates getTemplates(TransformerFactory tf)
throws TransformerConfigurationException
{
return tf.newTemplates(
new StreamSource(new ByteArrayInputStream(xsl.getBytes()))
);
}
// utility to construct StreamSource
public StreamSource getStreamSource() {
return new StreamSource(
new ByteArrayInputStream(sourceXml.getBytes())
);
}
// utility to construct DOMSource from DocumentBuilderFactory
public DOMSource getDOMSource(DocumentBuilderFactory dbf)
throws SAXException, IOException, ParserConfigurationException
{
return new DOMSource(
dbf.newDocumentBuilder().parse(
new InputSource(
new ByteArrayInputStream(sourceXml.getBytes())
)
)
);
}
// utility to construct SAXSource from SAXParserFactory
public SAXSource getSAXSource(SAXParserFactory spf)
throws SAXException, ParserConfigurationException
{
return new SAXSource(
spf.newSAXParser().getXMLReader(),
new InputSource(new ByteArrayInputStream(sourceXml.getBytes()))
);
}
// utility to construct StAXSource from XMLInputFactory
public StAXSource getStAXSource(XMLInputFactory xif)
throws XMLStreamException
{
return new StAXSource(
xif.createXMLStreamReader(new StringReader(sourceXml))
);
}
}