--- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DBFNamespaceTest.java 2015-01-09 15:41:17.437086945 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DBFNamespaceTest.java 2015-01-09 15:41:17.358086822 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, 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 @@ -23,64 +23,59 @@ package javax.xml.parsers.ptests; -import static jaxp.library.JAXPTestUtilities.FILE_SEP; import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; - import java.io.File; -import java.io.IOException; - import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; +import static javax.xml.parsers.ptests.ParserTestConst.GOLDEN_DIR; +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; - +import jaxp.library.JAXPFileBaseTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.w3c.dom.Document; -import org.xml.sax.SAXException; /** * This tests DocumentBuilderFactory for namespace processing and no-namespace * processing. */ -public class DBFNamespaceTest { +public class DBFNamespaceTest extends JAXPFileBaseTest { /** * Provide input for the cases that supporting namespace or not. + * @return a two-dimensional array contains factory, output file name and + * golden validate file name. */ @DataProvider(name = "input-provider") public Object[][] getInput() { DocumentBuilderFactory dbf1 = DocumentBuilderFactory.newInstance(); - String outputfile1 = USER_DIR + FILE_SEP + "dbfnstest01.out"; - String goldfile1 = TestUtils.GOLDEN_DIR + FILE_SEP + "dbfnstest01GF.out"; + String outputfile1 = USER_DIR + "dbfnstest01.out"; + String goldfile1 = GOLDEN_DIR + "dbfnstest01GF.out"; DocumentBuilderFactory dbf2 = DocumentBuilderFactory.newInstance(); dbf2.setNamespaceAware(true); - String outputfile2 = USER_DIR + FILE_SEP + "dbfnstest02.out"; - String goldfile2 = TestUtils.GOLDEN_DIR + FILE_SEP + "dbfnstest02GF.out"; + String outputfile2 = USER_DIR + "dbfnstest02.out"; + String goldfile2 = GOLDEN_DIR + "dbfnstest02GF.out"; return new Object[][] { { dbf1, outputfile1, goldfile1 }, { dbf2, outputfile2, goldfile2 } }; } /** * Test to parse and transform a document without supporting namespace and * with supporting namespace. + * @param dbf a Document Builder factory for creating document object. + * @param outputfile output file name. + * @param goldfile golden validate file name. + * @throws Exception If any errors occur. */ @Test(dataProvider = "input-provider") - public void testNamespaceTest(DocumentBuilderFactory dbf, String outputfile, String goldfile) { - try { - Document doc = dbf.newDocumentBuilder().parse(new File(TestUtils.XML_DIR, "namespace1.xml")); - dummyTransform(doc, outputfile); - assertTrue(compareWithGold(goldfile, outputfile)); - } catch (SAXException | IOException | ParserConfigurationException | TransformerFactoryConfigurationError | TransformerException e) { - failUnexpected(e); - } + public void testNamespaceTest(DocumentBuilderFactory dbf, String outputfile, + String goldfile) throws Exception { + Document doc = dbf.newDocumentBuilder().parse(new File(XML_DIR, "namespace1.xml")); + dummyTransform(doc, outputfile); + assertTrue(compareWithGold(goldfile, outputfile)); } /** @@ -89,16 +84,14 @@ * not chosen, namespaceURI in callbacks should be an empty string otherwise * it should be namespaceURI. * - * @throws TransformerFactoryConfigurationError - * @throws TransformerException - * @throws IOException + * @throws Exception If any errors occur. */ - private void dummyTransform(Document document, String fileName) throws TransformerFactoryConfigurationError, TransformerException, IOException { + private void dummyTransform(Document document, String fileName) + throws Exception { DOMSource domSource = new DOMSource(document); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - File file = new File(fileName); - System.out.println("The fileName is " + file.getAbsolutePath()); - transformer.transform(domSource, new SAXResult(MyCHandler.newInstance(file))); + try(MyCHandler chandler = MyCHandler.newInstance(new File(fileName))) { + TransformerFactory.newInstance().newTransformer(). + transform(domSource, new SAXResult(chandler)); + } } - } --- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderImpl01.java 2015-01-09 15:41:17.790087495 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderImpl01.java 2015-01-09 15:41:17.712087373 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, 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 @@ -24,33 +24,32 @@ package javax.xml.parsers.ptests; import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; - import java.io.File; import java.io.FileInputStream; -import java.io.IOException; - +import java.io.FilePermission; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; +import jaxp.library.JAXPFileReadOnlyBaseTest; +import static org.testng.Assert.assertNotNull; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * This checks for the methods of DocumentBuilder */ -public class DocumentBuilderImpl01 implements EntityResolver { - +public class DocumentBuilderImpl01 extends JAXPFileReadOnlyBaseTest + implements EntityResolver { /** * Provide DocumentBuilder. * - * @throws ParserConfigurationException + * @return data provider has single DocumentBuilder. + * @throws ParserConfigurationException if a DocumentBuilder cannot be + * created which satisfies the configuration requested. */ @DataProvider(name = "builder-provider") public Object[][] getBuilder() throws ParserConfigurationException { @@ -60,17 +59,18 @@ } /** - * Testcase to test the default functionality of isValidation method. Expect + * Test the default functionality of isValidation method. Expect * to return false because not setting the validation. + * @param docBuilder document builder instance. */ @Test(dataProvider = "builder-provider") public void testCheckDocumentBuilderImpl01(DocumentBuilder docBuilder) { assertFalse(docBuilder.isValidating()); - } /** - * Testcase to test the default functionality of isNamespaceAware method. + * Test the default functionality of isNamespaceAware method. + * @param docBuilder document builder instance. */ @Test(dataProvider = "builder-provider") public void testCheckDocumentBuilderImpl02(DocumentBuilder docBuilder) { @@ -78,51 +78,71 @@ } /** - * Testcase to test the parse(InputStream). - */ - @Test(dataProvider = "builder-provider") - public void testCheckDocumentBuilderImpl04(DocumentBuilder docBuilder) { - try { - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderImpl01.xml"))); - } catch (SAXException | IOException e) { - failUnexpected(e); + * Test the parse(InputStream). + * @param docBuilder document builder instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "builder-provider") + public void testCheckDocumentBuilderImpl04(DocumentBuilder docBuilder) + throws Exception { + try (FileInputStream fis = new FileInputStream(new File(XML_DIR, + "DocumentBuilderImpl01.xml"))) { + assertNotNull(docBuilder.parse(fis)); } } /** - * Testcase to test the parse(File). - */ - @Test(dataProvider = "builder-provider") - public void testCheckDocumentBuilderImpl05(DocumentBuilder docBuilder) { - try { - Document doc = docBuilder.parse(new File(TestUtils.XML_DIR, "DocumentBuilderImpl01.xml")); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + * Test the parse(File). + * + * @param docBuilder document builder instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "builder-provider") + public void testCheckDocumentBuilderImpl05(DocumentBuilder docBuilder) + throws Exception { + assertNotNull(docBuilder.parse(new File(XML_DIR, + "DocumentBuilderImpl01.xml"))); } /** - * Testcase to test the parse(InputStream,systemId). - */ - @Test(dataProvider = "builder-provider") - public void testCheckDocumentBuilderImpl06(DocumentBuilder docBuilder) { - try { - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderImpl02.xml")), new File(TestUtils.XML_DIR).toURI() - .toASCIIString() + FILE_SEP); - } catch (SAXException | IOException e) { - failUnexpected(e); + * Test the parse(InputStream,systemId). + * @param docBuilder document builder instance. + * @throws Exception If any errors occur. + */ + @Test(groups = {"readLocalFiles"}, dataProvider = "builder-provider") + public void testCheckDocumentBuilderImpl06(DocumentBuilder docBuilder) + throws Exception { + setPermissions(new FilePermission(XML_DIR + "../-", + "read")); + try (FileInputStream fis = new FileInputStream(new File(XML_DIR, + "DocumentBuilderImpl02.xml"))) { + assertNotNull(docBuilder.parse(fis, new File(XML_DIR).toURI() + .toASCIIString() + FILE_SEP)); } } /** - * Testcase to test the setEntityResolver. + * Test the setEntityResolver. + * @param docBuilder document builder instance. */ @Test(dataProvider = "builder-provider") public void testCheckDocumentBuilderImpl07(DocumentBuilder docBuilder) { docBuilder.setEntityResolver(this); - resolveEntity("publicId", "http://www.myhost.com/today"); + assertNotNull(resolveEntity("publicId", "http://www.myhost.com/today")); } + /** + * Allow the application to resolve external entities. + * + * @param publicId The public identifier of the external entity + * being referenced, or null if none was supplied. + * @param systemId The system identifier of the external entity + * being referenced. + * @return An InputSource object describing the new input source, + * or null to request that the parser open a regular + * URI connection to the system identifier. + */ + @Override public InputSource resolveEntity(String publicId, String systemId) { if (systemId.equals("http://www.myhost.com/today")) return new InputSource(systemId); --- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/FactoryConfErrorTest.java 2015-01-09 15:41:18.243088201 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/FactoryConfErrorTest.java 2015-01-09 15:41:18.166088081 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, 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 @@ -26,6 +26,7 @@ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPBaseTest; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; @@ -35,7 +36,7 @@ * Class containing the test cases for SAXParserFactory/DocumentBuilderFactory * newInstance methods. */ -public class FactoryConfErrorTest { +public class FactoryConfErrorTest extends JAXPBaseTest { /** * Set properties DocumentBuilderFactory and SAXParserFactory to invalid @@ -43,8 +44,8 @@ */ @BeforeTest public void setup() { - System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "xx"); - System.setProperty("javax.xml.parsers.SAXParserFactory", "xx"); + setSystemProperty("javax.xml.parsers.DocumentBuilderFactory", "xx"); + setSystemProperty("javax.xml.parsers.SAXParserFactory", "xx"); } /** @@ -53,8 +54,8 @@ */ @AfterTest public void cleanup() { - System.clearProperty("javax.xml.parsers.DocumentBuilderFactory"); - System.clearProperty("javax.xml.parsers.SAXParserFactory"); + setSystemProperty("javax.xml.parsers.DocumentBuilderFactory", null); + setSystemProperty("javax.xml.parsers.SAXParserFactory", null); } /** @@ -67,7 +68,7 @@ } /** - * To test exeception thrown if javax.xml.parsers.DocumentBuilderFactory is + * To test exception thrown if javax.xml.parsers.DocumentBuilderFactory is * invalid. */ @Test(expectedExceptions = FactoryConfigurationError.class) --- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserFactTest.java 2015-01-09 15:41:18.605088765 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserFactTest.java 2015-01-09 15:41:18.528088645 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, 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 @@ -22,24 +22,16 @@ */ package javax.xml.parsers.ptests; - -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - +import jaxp.library.JAXPBaseTest; import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; /** - * Class containing the test cases for SAXParserFactory API + * Class containing the test cases for SAXParserFactory API. */ -public class SAXParserFactTest { +public class SAXParserFactTest extends JAXPBaseTest { private static final String NAMESPACES = "http://xml.org/sax/features/namespaces"; private static final String NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; @@ -49,20 +41,17 @@ private static final String EXTERNAL_P_ENTITIES = "http://xml.org/sax/features/external-parameter-entities"; /** - * Testcase to test if newSAXParser() method returns SAXParser. + * Test if newSAXParser() method returns SAXParser. + * @throws Exception If any errors occur. */ @Test - public void testParser01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxparser = spf.newSAXParser(); - } catch (ParserConfigurationException | SAXException e) { - failUnexpected(e); - } + public void testParser01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.newSAXParser(); } /** - * Testcase to test the default functionality (No validation) of the parser. + * Test the default functionality (No validation) of the parser. */ @Test public void testValidate01() { @@ -71,7 +60,7 @@ } /** - * Testcase to test the functionality of setValidating and isvalidating + * Test the functionality of setValidating and isvalidating * methods. */ @Test @@ -82,7 +71,7 @@ } /** - * Parser should not be namespaceaware by default. + * Parser should not be namespace-aware by default. */ @Test public void testNamespace01() { @@ -91,7 +80,7 @@ } /** - * Testcase to test the functionality of setNamespaceAware and + * Test the functionality of setNamespaceAware and * isNamespaceAware methods. */ @Test @@ -102,167 +91,132 @@ } /** - * Testcase to test the functionality of setNamespaceAware and getFeature() + * Test the functionality of setNamespaceAware and getFeature() * methods for namespaces property. + * @throws Exception If any errors occur. */ @Test - public void testFeature01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertFalse(spf.getFeature(NAMESPACES)); + public void testFeature01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertFalse(spf.getFeature(NAMESPACES)); - spf.setNamespaceAware(true); - assertTrue(spf.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + spf.setNamespaceAware(true); + assertTrue(spf.getFeature(NAMESPACES)); } /** - * Testcase to test the functionality of setFeature and getFeature methods + * Test the functionality of setFeature and getFeature methods * for namespaces property. + * @throws Exception If any errors occur. */ @Test - public void testFeature02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); + public void testFeature02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(NAMESPACES, true); - assertTrue(spf.getFeature(NAMESPACES)); + spf.setFeature(NAMESPACES, true); + assertTrue(spf.getFeature(NAMESPACES)); - spf.setFeature(NAMESPACES, false); - assertFalse(spf.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + spf.setFeature(NAMESPACES, false); + assertFalse(spf.getFeature(NAMESPACES)); } /** - * Testcase to test the functionality of setFeature and getFeature methods + * Test the functionality of setFeature and getFeature methods * for namespace-prefixes property. + * @throws Exception If any errors occur. */ @Test - public void testFeature03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); + public void testFeature03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(NAMESPACE_PREFIXES, true); - assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); + spf.setFeature(NAMESPACE_PREFIXES, true); + assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); - spf.setFeature(NAMESPACE_PREFIXES, false); - assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + spf.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); } /** - * Testcase to test the functionality of getFeature method for + * Test the functionality of getFeature method for * string-interning property. + * @throws Exception If any errors occur. */ @Test - public void testFeature04() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertTrue(spf.getFeature(STRING_INTERNING)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + public void testFeature04() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertTrue(spf.getFeature(STRING_INTERNING)); } /** - * Testcase to test the functionality of getFeature and setValidating + * Test the functionality of getFeature and setValidating * methods for validation property. + * @throws Exception If any errors occur. */ @Test - public void testFeature05() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertFalse(spf.getFeature(VALIDATION)); - spf.setValidating(true); - assertTrue(spf.getFeature(VALIDATION)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } - + public void testFeature05() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertFalse(spf.getFeature(VALIDATION)); + spf.setValidating(true); + assertTrue(spf.getFeature(VALIDATION)); } /** - * Testcase to test the functionality of setFeature and getFeature methods + * Test the functionality of setFeature and getFeature methods * for validation property. + * @throws Exception If any errors occur. */ @Test - public void testFeature06() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - - spf.setFeature(VALIDATION, true); - assertTrue(spf.getFeature(VALIDATION)); - - spf.setFeature(VALIDATION, false); - assertFalse(spf.getFeature(VALIDATION)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } - + public void testFeature06() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setFeature(VALIDATION, true); + assertTrue(spf.getFeature(VALIDATION)); + spf.setFeature(VALIDATION, false); + assertFalse(spf.getFeature(VALIDATION)); } /** - * Testcase to test the functionality of getFeature method for + * Test the functionality of getFeature method for * external-general-entities property. + * @throws Exception If any errors occur. */ @Test - public void testFeature07() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertTrue(spf.getFeature(EXTERNAL_G_ENTITIES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } - + public void testFeature07() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertTrue(spf.getFeature(EXTERNAL_G_ENTITIES)); } /** - * Testcase to test the functionality of setFeature and getFeature methods + * Test the functionality of setFeature and getFeature methods * for external-general-entities property. + * @throws Exception If any errors occur. */ @Test - public void testFeature08() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(EXTERNAL_G_ENTITIES, false); - assertFalse(spf.getFeature(EXTERNAL_G_ENTITIES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + public void testFeature08() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setFeature(EXTERNAL_G_ENTITIES, false); + assertFalse(spf.getFeature(EXTERNAL_G_ENTITIES)); } /** - * Testcase to test the functionality of getFeature method for + * Test the functionality of getFeature method for * external-parameter-entities property. + * @throws Exception If any errors occur. */ @Test - public void testFeature09() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertTrue(spf.getFeature(EXTERNAL_P_ENTITIES)); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } + public void testFeature09() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertTrue(spf.getFeature(EXTERNAL_P_ENTITIES)); } /** - * Testcase to test the functionality of setFeature method for + * Test the functionality of setFeature method for * external-parameter-entitie property. + * @throws Exception If any errors occur. */ @Test - public void testFeature10() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(EXTERNAL_P_ENTITIES, false); - } catch (ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException e) { - failUnexpected(e); - } - + public void testFeature10() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setFeature(EXTERNAL_P_ENTITIES, false); + assertFalse(spf.getFeature(EXTERNAL_P_ENTITIES)); } } --- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest.java 2015-01-09 15:41:19.068089487 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest.java 2015-01-09 15:41:18.993089370 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, 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 @@ -23,16 +23,14 @@ package javax.xml.parsers.ptests; -import static jaxp.library.JAXPTestUtilities.failUnexpected; - import java.io.File; import java.io.FileInputStream; +import java.io.FilePermission; import java.io.IOException; - -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; +import jaxp.library.JAXPFileReadOnlyBaseTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.xml.sax.HandlerBase; @@ -43,16 +41,15 @@ /** * Class contains the test cases for SAXParser API */ -public class SAXParserTest { - +public class SAXParserTest extends JAXPFileReadOnlyBaseTest { /** * Provide SAXParser. * - * @throws SAXException - * @throws ParserConfigurationException + * @return a data provider contains a SAXParser instance. + * @throws Exception If any errors occur. */ @DataProvider(name = "parser-provider") - public Object[][] getParser() throws ParserConfigurationException, SAXException { + public Object[][] getParser() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxparser = spf.newSAXParser(); return new Object[][] { { saxparser } }; @@ -62,498 +59,454 @@ * Test case with FileInputStream null, parsing should fail and throw * IllegalArgumentException. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse01(SAXParser saxparser) throws IllegalArgumentException { - try { - FileInputStream instream = null; - HandlerBase handler = new HandlerBase(); - saxparser.parse(instream, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse01(SAXParser saxparser) throws Exception { + FileInputStream instream = null; + saxparser.parse(instream, new HandlerBase()); } /** - * Testcase with an error in xml file, parsing should fail and throw - * SAXException. + * Test with by setting URI as null, parsing should fail and throw + * IllegalArgumentException. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse02(SAXParser saxparser) throws SAXException { - try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "invalid.xml")); - saxparser.parse(instream, handler); - } catch (IOException e) { - failUnexpected(e); - } + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse02(SAXParser saxparser) throws Exception { + String uri = null; + saxparser.parse(uri, new HandlerBase()); } /** - * Testcase with a valid in xml file, parser should parse the xml document. + * Test with non-existence URI, parsing should fail and throw IOException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse03(SAXParser saxparser) { + @Test(expectedExceptions = { SAXException.class }, + dataProvider = "parser-provider") + public void testParse03(SAXParser saxparser) throws Exception { + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir, "read")); try { - HandlerBase handler = new HandlerBase(); - saxparser.parse(new File(TestUtils.XML_DIR, "parsertest.xml"), handler); - } catch (IOException | SAXException e) { - failUnexpected(e); + saxparser.parse("", new HandlerBase()); + } finally { + setPermissions(); } } /** - * Testcase with valid input stream, parser should parse the xml document - * successfully. + * Test with File null, parsing should fail and throw + * IllegalArgumentException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse04(SAXParser saxparser) { - try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "correct.xml")); - saxparser.parse(instream, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse04(SAXParser saxparser) throws Exception { + File file = null; + saxparser.parse(file, new HandlerBase()); } /** - * Testcase with valid input source, parser should parse the xml document - * successfully. + * Test with empty string as File, parsing should fail and throw + * SAXException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse05(SAXParser saxparser) { + @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") + public void testParse05(SAXParser saxparser) throws Exception { + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir, "read")); try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "parsertest.xml")); - saxparser.parse(instream, handler, new File(TestUtils.XML_DIR).toURI().toASCIIString()); - } catch (SAXException | IOException e) { - failUnexpected(e); + saxparser.parse(new File(""), new HandlerBase()); + } finally { + setPermissions(); } } /** - * Testcase with uri null, parsing should fail and throw + * Test with input source null, parsing should fail and throw * IllegalArgumentException. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse07(SAXParser saxparser) throws IllegalArgumentException { - try { - String uri = null; - HandlerBase handler = new HandlerBase(); - saxparser.parse(uri, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse06(SAXParser saxparser) throws Exception { + InputSource is = null; + saxparser.parse(is, new HandlerBase()); } /** - * Testcase with non-existant uri, parsing should fail and throw - * IOException. + * Test with FileInputStream null, parsing should fail and throw + * IllegalArgumentException. * - * @throws SAXException - * @throws IOException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = { SAXException.class, IOException.class }, dataProvider = "parser-provider") - public void testParse08(SAXParser saxparser) throws SAXException, IOException { - String uri = " "; - - HandlerBase handler = new HandlerBase(); - saxparser.parse(uri, handler); - + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse07(SAXParser saxparser) throws Exception { + FileInputStream instream = null; + saxparser.parse(instream, new DefaultHandler()); } /** - * Testcase with proper uri, parser should parse successfully. + * Test with URI null, parsing should fail and throw + * IllegalArgumentException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse09(SAXParser saxparser) { - try { - File file = new File(TestUtils.XML_DIR, "correct.xml"); - HandlerBase handler = new HandlerBase(); - saxparser.parse(file.toURI().toASCIIString(), handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse08(SAXParser saxparser) throws Exception { + String uri = null; + saxparser.parse(uri, new DefaultHandler()); } /** - * Testcase with File null, parsing should fail and throw - * IllegalArgumentException. + * Test with non-existence URI, parsing should fail and throw + * SAXException or IOException. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse10(SAXParser saxparser) throws IllegalArgumentException { + @Test(expectedExceptions = { SAXException.class, IOException.class }, + dataProvider = "parser-provider") + public void testParse09(SAXParser saxparser) throws Exception { + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir + "/../-", "read")); + String uri = " "; try { - File file = null; - HandlerBase handler = new HandlerBase(); - saxparser.parse(file, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); + saxparser.parse(uri, new DefaultHandler()); + } finally { + setPermissions(); } } /** - * Testcase with empty string as File, parsing should fail and throw + * Test with empty string as File, parsing should fail and throw * SAXException. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse11(SAXParser saxparser) throws SAXException { + public void testParse10(SAXParser saxparser) throws Exception { + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir, "read")); + File file = new File(""); try { - HandlerBase handler = new HandlerBase(); - File file = new File(""); - saxparser.parse(file, handler); - } catch (IOException e) { - failUnexpected(e); + saxparser.parse(file, new DefaultHandler()); + } finally { + setPermissions(); } } /** - * Testcase with xml file that has errors parsing should fail and throw - * SAXException. + * Test with File null, parsing should fail and throw + * IllegalArgumentException. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse12(SAXParser saxparser) throws SAXException { - try { - HandlerBase handler = new HandlerBase(); - File file = new File(TestUtils.XML_DIR, "valid.xml"); - saxparser.parse(file, handler); - } catch (IOException e) { - failUnexpected(e); - } + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse11(SAXParser saxparser) throws Exception { + saxparser.parse((File) null, new DefaultHandler()); } /** - * Testcase with xml file that has no errors Parser should successfully - * parse the xml document. + * Test with input source null, parsing should fail and throw + * IllegalArgumentException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse13(SAXParser saxparser) { - try { - HandlerBase handler = new HandlerBase(); - File file = new File(TestUtils.XML_DIR, "correct.xml"); - saxparser.parse(file, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } - + @Test(expectedExceptions = IllegalArgumentException.class, + dataProvider = "parser-provider") + public void testParse12(SAXParser saxparser) throws Exception { + InputSource is = null; + saxparser.parse(is, new DefaultHandler()); } /** - * Testcase with input source null, parsing should fail and throw - * IllegalArgumentException. + * Test with an error in XML file, parsing should fail and throw + * SAXException. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse14(SAXParser saxparser) throws IllegalArgumentException { - try { - InputSource is = null; - HandlerBase handler = new HandlerBase(); - saxparser.parse(is, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse13(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream(new File( + XML_DIR, "invalid.xml"))) { + saxparser.parse(instream, new HandlerBase()); } } /** - * Testcase with input source attached an invaild xml, parsing should fail - * and throw SAXException. + * Test with a valid in XML file, parser should parse the XML document. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse15(SAXParser saxparser) throws SAXException { - try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "invalid.xml")); - InputSource is = new InputSource(instream); - saxparser.parse(is, handler); - } catch (IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse14(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "parsertest.xml"), + new HandlerBase()); } /** - * Testcase with input source attached an vaild xml, parser should - * successfully parse the xml document. + * Test with valid input stream, parser should parse the XML document + * successfully. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse16(SAXParser saxparser) { - try { - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "correct.xml")); - InputSource is = new InputSource(instream); - saxparser.parse(is, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse15(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream(new File(XML_DIR, + "correct.xml"))) { + saxparser.parse(instream, new HandlerBase()); + } } /** - * Testcase with FileInputStream null, parsing should fail and throw - * IllegalArgumentException. + * Test with valid input source, parser should parse the XML document + * successfully. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse17(SAXParser saxparser) throws IllegalArgumentException { - try { - FileInputStream instream = null; - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(instream, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse16(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "parsertest.xml"))) { + saxparser.parse(instream, new HandlerBase(), + new File(XML_DIR).toURI().toASCIIString()); } } /** - * Testcase with an error in xml file, parsing should fail and throw - * SAXException. + * Test with proper URI, parser should parse successfully. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse18(SAXParser saxparser) throws SAXException { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "invalid.xml")); - saxparser.parse(instream, handler); - } catch (IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse17(SAXParser saxparser) throws Exception { + File file = new File(XML_DIR, "correct.xml"); + saxparser.parse(file.toURI().toASCIIString(), new HandlerBase()); } /** - * Testcase with valid input stream, parser should parse the xml document - * successfully. + * Test with XML file that has errors parsing should fail and throw + * SAXException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse19(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(new File(TestUtils.XML_DIR, "parsertest.xml"), handler); - } catch (IOException | SAXException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse18(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "valid.xml"), new HandlerBase()); } /** - * Testcase with valid input stream, parser should parse the xml document - * successfully. + * Test with XML file that has no errors Parser should successfully + * parse the XML document. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse20(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "correct.xml")); - saxparser.parse(instream, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse19(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "correct.xml"), new HandlerBase()); } /** - * Testcase with valid input source, parser should parse the xml document - * successfully. + * Test with input source attached an invalid XML, parsing should fail + * and throw SAXException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse21(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "parsertest.xml")); - saxparser.parse(instream, handler, new File(TestUtils.XML_DIR).toURI().toASCIIString()); - } catch (SAXException | IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse20(SAXParser saxparser) throws Exception { + try(FileInputStream instream = new FileInputStream(new File(XML_DIR, + "invalid.xml"))) { + saxparser.parse(new InputSource(instream), new HandlerBase()); } - } /** - * Testcase with uri null, parsing should fail and throw - * IllegalArgumentException. + * Test with input source attached an valid XML, parser should + * successfully parse the XML document. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse23(SAXParser saxparser) throws IllegalArgumentException { - try { - String uri = null; - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(uri, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse21(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream(new File(XML_DIR, + "correct.xml"))) { + saxparser.parse(new InputSource(instream), new HandlerBase()); } } /** - * Testcase with non-existant uri, parsing should fail and throw - * SAXException or IOException. + * Test with an error in xml file, parsing should fail and throw + * SAXException. * - * @throws SAXException - * @throws IOException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = { SAXException.class, IOException.class }, dataProvider = "parser-provider") - public void testParse24(SAXParser saxparser) throws SAXException, IOException { - String uri = " "; - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(uri, handler); - + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse22(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "invalid.xml"))) { + saxparser.parse(instream, new DefaultHandler()); + } } /** - * Testcase with proper uri, parser should parse successfully. + * Test with valid input stream, parser should parse the XML document + * successfully. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse25(SAXParser saxparser) { - try { - File file = new File(TestUtils.XML_DIR, "correct.xml"); - - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(file.toURI().toASCIIString(), handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse23(SAXParser saxparser) throws Exception { + DefaultHandler handler = new DefaultHandler(); + saxparser.parse(new File(XML_DIR, "parsertest.xml"), handler); } /** - * Testcase with File null, parsing should fail and throw - * IllegalArgumentException. + * Test with valid input stream, parser should parse the XML document + * successfully. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse26(SAXParser saxparser) throws IllegalArgumentException { - try { + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse24(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream(new File(XML_DIR, + "correct.xml"))) { DefaultHandler handler = new DefaultHandler(); - saxparser.parse((File) null, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); + saxparser.parse(instream, handler); } } /** - * Testcase with empty string as File, parsing should fail and throw - * SAXException. + * Test with valid input source, parser should parse the XML document + * successfully. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse27(SAXParser saxparser) throws SAXException { - try { - DefaultHandler handler = new DefaultHandler(); - File file = new File(""); - saxparser.parse(file, handler); - } catch (IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse25(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "parsertest.xml"))) { + saxparser.parse(instream, new DefaultHandler(), + new File(XML_DIR).toURI().toASCIIString()); } } /** - * Testcase with xml file that has errors, parsing should fail and throw - * SAXException. + * Test with proper URI, parser should parse successfully. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse28(SAXParser saxparser) throws SAXException { - try { - DefaultHandler handler = new DefaultHandler(); - File file = new File(TestUtils.XML_DIR, "valid.xml"); - saxparser.parse(file, handler); - } catch (IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse26(SAXParser saxparser) throws Exception { + File file = new File(XML_DIR, "correct.xml"); + saxparser.parse(file.toURI().toASCIIString(), new DefaultHandler()); } /** - * Testcase with xml file that has no errors, parser should successfully - * parse the xml document. + * Test with XML file that has errors, parsing should fail and throw + * SAXException. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse29(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - File file = new File(TestUtils.XML_DIR, "correct.xml"); - saxparser.parse(file, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse27(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "valid.xml"), new DefaultHandler()); } /** - * Testcase with input source null, parsing should fail and throw - * IllegalArgumentException. + * Test with XML file that has no errors, parser should successfully + * parse the XML document. * - * @throws IllegalArgumentException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class, dataProvider = "parser-provider") - public void testParse30(SAXParser saxparser) throws IllegalArgumentException { - try { - InputSource is = null; - DefaultHandler handler = new DefaultHandler(); - saxparser.parse(is, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse28(SAXParser saxparser) throws Exception { + saxparser.parse(new File(XML_DIR, "correct.xml"), new DefaultHandler()); } /** - * Testcase with an invalid xml file, parser should throw SAXException. + * Test with an invalid XML file, parser should throw SAXException. * - * @throws SAXException + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") - public void testParse31(SAXParser saxparser) throws SAXException { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "invalid.xml")); - InputSource is = new InputSource(instream); - saxparser.parse(is, handler); - } catch (IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class, + dataProvider = "parser-provider") + public void testParse29(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "invalid.xml"))) { + saxparser.parse(new InputSource(instream), new DefaultHandler()); } } /** - * Test case to parse an xml file that not use namespaces. + * Test case to parse an XML file that not use namespaces. + * + * @param saxparser a SAXParser instance. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "parser-provider") - public void testParse32(SAXParser saxparser) { - try { - DefaultHandler handler = new DefaultHandler(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "correct.xml")); - InputSource is = new InputSource(instream); - saxparser.parse(is, handler); - } catch (SAXException | IOException e) { - failUnexpected(e); + @Test(groups = {"readLocalFiles"}, dataProvider = "parser-provider") + public void testParse30(SAXParser saxparser) throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "correct.xml"))) { + saxparser.parse(new InputSource(instream), new DefaultHandler()); } } /** - * Test case to parse an xml file that uses namespaces. + * Test case to parse an XML file that uses namespaces. + * + * @throws Exception If any errors occur. */ - @Test - public void testParse33() { - try { + @Test(groups = {"readLocalFiles"}) + public void testParse31() throws Exception { + try (FileInputStream instream = new FileInputStream( + new File(XML_DIR, "ns4.xml"))) { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); - SAXParser saxparser = spf.newSAXParser(); - HandlerBase handler = new HandlerBase(); - FileInputStream instream = new FileInputStream(new File(TestUtils.XML_DIR, "ns4.xml")); - saxparser.parse(instream, handler); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); + spf.newSAXParser().parse(instream, new HandlerBase()); } } -} +} \ No newline at end of file --- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest02.java 2015-01-09 15:41:19.425090043 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest02.java 2015-01-09 15:41:19.348089923 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, 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 @@ -23,260 +23,239 @@ package javax.xml.parsers.ptests; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; - -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - +import jaxp.library.JAXPBaseTest; +import static org.testng.Assert.assertNotNull; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import org.xml.sax.Parser; import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.XMLReader; import org.xml.sax.ext.DeclHandler; import org.xml.sax.ext.LexicalHandler; /** * Class contains the test cases for SAXParser API */ -public class SAXParserTest02 { - final String DOM_NODE = "http://xml.org/sax/properties/dom-node"; - final String XML_STRING = "http://xml.org/sax/properties/xml-string"; - final String DECL_HANDLER = "http://xml.org/sax/properties/declaration-handler"; - final String LEXICAL_HANDLER = "http://xml.org/sax/properties/lexical-handler"; +public class SAXParserTest02 extends JAXPBaseTest { + private static final String DOM_NODE = "http://xml.org/sax/properties/dom-node"; + private static final String XML_STRING = "http://xml.org/sax/properties/xml-string"; + private static final String DECL_HANDLER = "http://xml.org/sax/properties/declaration-handler"; + private static final String LEXICAL_HANDLER = "http://xml.org/sax/properties/lexical-handler"; /** * Provide SAXParser. - * - * @throws SAXException - * @throws ParserConfigurationException + * + * @return a data provider contains a SAXParser instance. + * @throws Exception If any errors occur. */ @DataProvider(name = "parser-provider") - public Object[][] getParser() throws ParserConfigurationException, SAXException { + public Object[][] getParser() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxparser = spf.newSAXParser(); return new Object[][] { { saxparser } }; } /** - * Testcase to test the default functionality (No validation) of the parser. + * Test to test the default functionality (No validation) of the parser. + * + * @param saxparser a SAXParser instance. */ @Test(dataProvider = "parser-provider") public void testValidate01(SAXParser saxparser) { - try { - assertFalse(saxparser.isValidating()); - } catch (FactoryConfigurationError e) { - failUnexpected(e); - } - + assertFalse(saxparser.isValidating()); } /** - * Testcase to test the functionality of setValidating and isvalidating + * Test to test the functionality of setValidating and isValidating * methods. + * + * @throws Exception If any errors occur. */ @Test - public void testValidate02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setValidating(true); - spf.newSAXParser(); - assertTrue(spf.isValidating()); - } catch (FactoryConfigurationError | ParserConfigurationException | SAXException e) { - failUnexpected(e); - } - + public void testValidate02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setValidating(true); + spf.newSAXParser(); + assertTrue(spf.isValidating()); } /** - * Test case to test isNamespaceAware() method. By default, namespaces are + * Test isNamespaceAware() method. By default, namespaces are * not supported. + * + * @param saxparser a SAXParser instance. */ @Test(dataProvider = "parser-provider") public void testNamespace01(SAXParser saxparser) { - try { - assertFalse(saxparser.isNamespaceAware()); - } catch (FactoryConfigurationError e) { - failUnexpected(e); - } - + assertFalse(saxparser.isNamespaceAware()); } /** * Test case to test setnamespaceAware() method. + * + * @throws Exception If any errors occur. */ @Test - public void testNamespace02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxparser = spf.newSAXParser(); - assertTrue(saxparser.isNamespaceAware()); - } catch (FactoryConfigurationError | ParserConfigurationException | SAXException e) { - failUnexpected(e); - } - + public void testNamespace02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser saxparser = spf.newSAXParser(); + assertTrue(saxparser.isNamespaceAware()); } /** * Test case to test if the getParser() method returns instance of Parser. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testParser01(SAXParser saxparser) { - try { - Parser parser = saxparser.getParser(); - } catch (FactoryConfigurationError | SAXException e) { - failUnexpected(e); - } - + public void testParser01(SAXParser saxparser) throws SAXException { + assertNotNull(saxparser.getParser()); } /** * Test case to test if the getXMLReader() method returns instance of * XMLReader. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testXmlReader01(SAXParser saxparser) { - try { - XMLReader xmlReader = saxparser.getXMLReader(); - } catch (FactoryConfigurationError | SAXException e) { - failUnexpected(e); - } + public void testXmlReader01(SAXParser saxparser) throws SAXException { + assertNotNull(saxparser.getXMLReader()); } /** * Test whether the xml-string property is not supported. * - * @throws SAXNotSupportedException + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ - @Test(expectedExceptions = SAXNotSupportedException.class, dataProvider = "parser-provider") - public void testProperty01(SAXParser saxparser) throws SAXNotSupportedException { - try { - Object object = saxparser.getProperty(XML_STRING); - } catch (SAXNotRecognizedException e) { - failUnexpected(e); - } + @Test(expectedExceptions = SAXNotSupportedException.class, + dataProvider = "parser-provider") + public void testProperty01(SAXParser saxparser) throws SAXException { + saxparser.getProperty(XML_STRING); } /** * Test whether the dom-node property is not supported. * - * @throws SAXNotSupportedException + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ - @Test(expectedExceptions = SAXNotSupportedException.class, dataProvider = "parser-provider") - public void testProperty02(SAXParser saxparser) throws SAXNotSupportedException { - try { - Object object = saxparser.getProperty(DOM_NODE); - } catch (SAXNotRecognizedException e) { - failUnexpected(e); - } + @Test(expectedExceptions = SAXNotSupportedException.class, + dataProvider = "parser-provider") + public void testProperty02(SAXParser saxparser) throws SAXException { + saxparser.getProperty(DOM_NODE); } /** * Test the default lexical-handler not exists. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testProperty03(SAXParser saxparser) { - try { - assertNull(saxparser.getProperty(LEXICAL_HANDLER)); - } catch (SAXException e) { - failUnexpected(e); - } - + public void testProperty03(SAXParser saxparser) throws SAXException { + assertNull(saxparser.getProperty(LEXICAL_HANDLER)); } /** * Test the default declaration-handler not exists. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testProperty04(SAXParser saxparser) { - - try { - assertNull(saxparser.getProperty(DECL_HANDLER)); - } catch (SAXException e) { - failUnexpected(e); - } + public void testProperty04(SAXParser saxparser) throws SAXException { + assertNull(saxparser.getProperty(DECL_HANDLER)); } /** * Test to set and get the lexical-handler. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testProperty05(SAXParser saxparser) { - try { - MyLexicalHandler myLexicalHandler = new MyLexicalHandler(); - saxparser.setProperty(LEXICAL_HANDLER, myLexicalHandler); - Object object = saxparser.getProperty(LEXICAL_HANDLER); - assertTrue(object instanceof LexicalHandler); - } catch (SAXException e) { - failUnexpected(e); - } + public void testProperty05(SAXParser saxparser) throws SAXException { + MyLexicalHandler myLexicalHandler = new MyLexicalHandler(); + saxparser.setProperty(LEXICAL_HANDLER, myLexicalHandler); + assertTrue(saxparser.getProperty(LEXICAL_HANDLER) instanceof LexicalHandler); } /** * Test to set and get the declaration-handler. + * + * @param saxparser a SAXParser instance. + * @throws SAXException If any parse errors occur. */ @Test(dataProvider = "parser-provider") - public void testProperty06(SAXParser saxparser) { - try { - MyDeclHandler myDeclHandler = new MyDeclHandler(); - saxparser.setProperty(DECL_HANDLER, myDeclHandler); - Object object = saxparser.getProperty(DECL_HANDLER); - assertTrue(object instanceof DeclHandler); - } catch (SAXException e) { - failUnexpected(e); - } - + public void testProperty06(SAXParser saxparser) throws SAXException { + MyDeclHandler myDeclHandler = new MyDeclHandler(); + saxparser.setProperty(DECL_HANDLER, myDeclHandler); + assertTrue(saxparser.getProperty(DECL_HANDLER) instanceof DeclHandler); } /** - * Customized LexicalHandler used for test. + * Customized LexicalHandler used for test. An empty implementation for + * LexicalHandler. */ private class MyLexicalHandler implements LexicalHandler { + @Override public void comment(char[] ch, int start, int length) { } + @Override public void endCDATA() { } + @Override public void endDTD() { } + @Override public void endEntity(String name) { } + @Override public void startCDATA() { } + @Override public void startDTD(String name, String publicId, String systemId) { } + @Override public void startEntity(String name) { } } /** - * Customized DeclHandler used for test. + * Customized DeclHandler used for test. An empty implementation for + * DeclHandler. */ private class MyDeclHandler implements DeclHandler { + @Override public void attributeDecl(String eName, String aName, String type, String valueDefault, String value) { } + @Override public void elementDecl(String name, String model) { } + @Override public void externalEntityDecl(String name, String publicId, String systemId) { } + @Override public void internalEntityDecl(String name, String value) { } } --- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest03.java 2015-01-09 15:41:19.780090596 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/SAXParserTest03.java 2015-01-09 15:41:19.703090476 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, 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 @@ -23,17 +23,17 @@ package javax.xml.parsers.ptests; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; - import java.io.File; -import java.io.IOException; - -import javax.xml.parsers.ParserConfigurationException; +import java.io.FilePermission; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; - +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; +import jaxp.library.JAXPFileReadOnlyBaseTest; +import static org.testng.Assert.fail; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.xml.sax.SAXException; @@ -41,68 +41,70 @@ /** * Class contains the test cases for SAXParser API */ -public class SAXParserTest03 { +public class SAXParserTest03 extends JAXPFileReadOnlyBaseTest { /** * Provide SAXParserFactory. * - * @throws Exception + * @return a dimensional contains. */ @DataProvider(name = "input-provider") public Object[][] getFactory() { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(true); - MyErrorHandler handler = MyErrorHandler.newInstance(); - return new Object[][] { { spf, handler } }; + return new Object[][] { { spf, MyErrorHandler.newInstance() } }; } /** * parsertest.xml holds a valid document. This method tests the validating * parser. + * + * @param spf a Parser factory. + * @param handler an error handler for capturing events. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "input-provider") - public void testParseValidate01(SAXParserFactory spf, MyErrorHandler handler) { - try { - SAXParser saxparser = spf.newSAXParser(); - saxparser.parse(new File(TestUtils.XML_DIR, "parsertest.xml"), handler); - assertFalse(handler.errorOccured); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + @Test(groups = {"readLocalFiles"}, dataProvider = "input-provider") + public void testParseValidate01(SAXParserFactory spf, MyErrorHandler handler) + throws Exception { + spf.newSAXParser().parse(new File(XML_DIR, "parsertest.xml"), handler); + assertFalse(handler.isErrorOccured()); } /** * validns.xml holds a valid document with XML namespaces in it. This method * tests the Validating parser with namespace processing on. + * + * @param spf a Parser factory. + * @param handler an error handler for capturing events. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "input-provider") - public void testParseValidate02(SAXParserFactory spf, MyErrorHandler handler) { - try { + @Test(groups = {"readLocalFiles"}, dataProvider = "input-provider") + public void testParseValidate02(SAXParserFactory spf, MyErrorHandler handler) + throws Exception { spf.setNamespaceAware(true); - SAXParser saxparser = spf.newSAXParser(); - saxparser.parse(new File(TestUtils.XML_DIR, "validns.xml"), handler); - assertFalse(handler.errorOccured); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + spf.newSAXParser().parse(new File(XML_DIR, "validns.xml"), handler); + assertFalse(handler.isErrorOccured()); } /** * invalidns.xml holds an invalid document with XML namespaces in it. This * method tests the validating parser with namespace processing on. It * should throw validation error. + * + * @param spf a Parser factory. + * @param handler an error handler for capturing events. + * @throws Exception If any errors occur. */ - @Test(dataProvider = "input-provider") - public void testParseValidate03(SAXParserFactory spf, MyErrorHandler handler) { + @Test(groups = {"readLocalFiles"}, dataProvider = "input-provider") + public void testParseValidate03(SAXParserFactory spf, MyErrorHandler handler) + throws Exception { try { spf.setNamespaceAware(true); SAXParser saxparser = spf.newSAXParser(); - saxparser.parse(new File(TestUtils.XML_DIR, "invalidns.xml"), handler); - failUnexpected(new RuntimeException()); - } catch (ParserConfigurationException | SAXException | IOException e) { - if (e instanceof SAXException) { - assertTrue(handler.errorOccured); - } + saxparser.parse(new File(XML_DIR, "invalidns.xml"), handler); + fail("Expecting SAXException here"); + } catch (SAXException e) { + assertTrue(handler.isErrorOccured()); } } --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/ErrorListenerTest.java 2015-01-09 15:41:20.120091126 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/ErrorListenerTest.java 2015-01-09 15:41:20.043091006 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -24,12 +24,14 @@ package javax.xml.transform.ptests; import java.io.File; +import java.io.FilePermission; import javax.xml.transform.ErrorListener; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import org.testng.annotations.Test; @@ -37,7 +39,7 @@ /** * Class containing the test cases for ErrorListener interface */ -public class ErrorListenerTest implements ErrorListener { +public class ErrorListenerTest extends JAXPBaseTest implements ErrorListener { /** * Define ErrorListener's status. */ @@ -58,9 +60,10 @@ try { TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setErrorListener (listener); + setPermissions(new FilePermission(XML_DIR + "invalid.xsl", "read")); tfactory.newTransformer(new StreamSource( new File(XML_DIR + "invalid.xsl"))); - fail("We expect an Exception here"); + fail("Expect TransformerConfigurationException here"); } catch (TransformerConfigurationException ex) { assertEquals(listener.status, ListenerStatus.FATAL); } --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TfClearParamTest.java 2015-01-09 15:41:20.457091652 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TfClearParamTest.java 2015-01-09 15:41:20.381091533 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -24,11 +24,8 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; @@ -36,21 +33,20 @@ import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * Class containing the test cases for SAXParserFactory API */ -public class TfClearParamTest { +public class TfClearParamTest extends JAXPFileReadOnlyBaseTest { /** - * Test xslt file. + * Test style-sheet file name. */ private final String XSL_FILE = XML_DIR + "cities.xsl"; @@ -72,193 +68,164 @@ /** * Obtains transformer's parameter with the same name that set before. Value * should be same as set one. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. */ @Test - public void clear01() { - try { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - assertEquals(transformer.getParameter(LONG_PARAM_NAME).toString(), PARAM_VALUE); - } catch (TransformerConfigurationException ex) { - failUnexpected(ex); - } - + public void clear01() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + assertEquals(transformer.getParameter(LONG_PARAM_NAME).toString(), PARAM_VALUE); } /** * Obtains transformer's parameter with the a name that wasn't set before. * Null is expected. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. */ @Test - public void clear02() { - try { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - transformer.clearParameters(); - assertNull(transformer.getParameter(LONG_PARAM_NAME)); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } + public void clear02() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + transformer.clearParameters(); + assertNull(transformer.getParameter(LONG_PARAM_NAME)); + } + + /** + * Obtains transformer's parameter with a short name that set before. Value + * should be same as set one. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. + */ + @Test + public void clear03() throws TransformerConfigurationException { + TransformerFactory tfactory = TransformerFactory.newInstance(); + Transformer transformer = tfactory.newTransformer(); + + transformer.setParameter(SHORT_PARAM_NAME, PARAM_VALUE); + assertEquals(transformer.getParameter(SHORT_PARAM_NAME).toString(), PARAM_VALUE); + } + + /** + * Obtains transformer's parameter with a short name that set with an integer + * object before. Value should be same as the set integer object. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. + */ + @Test + public void clear04() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + + int intObject = 5; + transformer.setParameter(SHORT_PARAM_NAME, intObject); + assertEquals(transformer.getParameter(SHORT_PARAM_NAME), intObject); } /** * Obtains transformer's parameter whose initiated with a stream source with * the a name that set before. Value should be same as set one. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. */ - @Test - public void clear03() { - try { - Transformer transformer = TransformerFactory.newInstance(). - newTransformer(new StreamSource(new File(XSL_FILE))); + @Test (groups = {"readLocalFiles"}) + public void clear05() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance(). + newTransformer(new StreamSource(new File(XSL_FILE))); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); } /** * Obtains transformer's parameter whose initiated with a stream source with * the a name that wasn't set before. Null is expected. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. */ - @Test - public void clear04() { - try { - Transformer transformer = TransformerFactory.newInstance(). - newTransformer(new StreamSource(new File(XSL_FILE))); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - transformer.clearParameters(); - assertNull(transformer.getParameter(LONG_PARAM_NAME)); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } - + @Test (groups = {"readLocalFiles"}) + public void clear06() throws TransformerConfigurationException { + Transformer transformer = TransformerFactory.newInstance(). + newTransformer(new StreamSource(new File(XSL_FILE))); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + transformer.clearParameters(); + assertNull(transformer.getParameter(LONG_PARAM_NAME)); } /** * Obtains transformer's parameter whose initiated with a sax source with * the a name that set before. Value should be same as set one. + * @throws Exception If any errors occur. */ - @Test - public void clear05() { - try { - InputSource is = new InputSource(new FileInputStream(XSL_FILE)); + @Test (groups = {"readLocalFiles"}) + public void clear07() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_FILE)) { SAXSource saxSource = new SAXSource(); - saxSource.setInputSource(is); + saxSource.setInputSource(new InputSource(fis)); Transformer transformer = TransformerFactory.newInstance().newTransformer(saxSource); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); } } /** * Obtains transformer's parameter whose initiated with a sax source with * the a name that wasn't set before. Null is expected. + * @throws Exception If any errors occur. */ - @Test - public void clear06() { - try { - InputSource is = new InputSource(new FileInputStream(XSL_FILE)); + @Test (groups = {"readLocalFiles"}) + public void clear08() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_FILE)) { SAXSource saxSource = new SAXSource(); - saxSource.setInputSource(is); + saxSource.setInputSource(new InputSource(fis)); Transformer transformer = TransformerFactory.newInstance().newTransformer(saxSource); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); transformer.clearParameters(); assertNull(transformer.getParameter(LONG_PARAM_NAME)); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); } } /** * Obtains transformer's parameter whose initiated with a dom source with * the a name that set before. Value should be same as set one. + * @throws Exception If any errors occur. */ - @Test - public void clear07() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(XSL_FILE)); - DOMSource domSource = new DOMSource((Node)document); + @Test (groups = {"readLocalFiles"}) + public void clear09() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(XSL_FILE)); + DOMSource domSource = new DOMSource((Node)document); - Transformer transformer = tfactory.newTransformer(domSource); + Transformer transformer = tfactory.newTransformer(domSource); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); - } catch (IOException | ParserConfigurationException - | TransformerConfigurationException | SAXException ex){ - failUnexpected(ex); - } + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + assertEquals(transformer.getParameter(LONG_PARAM_NAME), PARAM_VALUE); } /** * Obtains transformer's parameter whose initiated with a dom source with * the a name that wasn't set before. Null is expected. + * @throws Exception If any errors occur. */ - @Test - public void clear08() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(XSL_FILE)); - DOMSource domSource = new DOMSource((Node)document); - - Transformer transformer = tfactory.newTransformer(domSource); - transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); - transformer.clearParameters(); - assertNull(transformer.getParameter(LONG_PARAM_NAME)); - } catch (IOException | ParserConfigurationException - | TransformerConfigurationException | SAXException ex){ - failUnexpected(ex); - } - } - - /** - * Obtains transformer's parameter with a short name that set before. Value - * should be same as set one. - */ - @Test - public void clear09() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - Transformer transformer = tfactory.newTransformer(); - - transformer.setParameter(SHORT_PARAM_NAME, PARAM_VALUE); - assertEquals(transformer.getParameter(SHORT_PARAM_NAME).toString(), PARAM_VALUE); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } - } - - /** - * Obtains transformer's parameter with a short name that set with an integer - * object before. Value should be same as the set integer object. - */ - @Test - public void clear10() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - Transformer transformer = tfactory.newTransformer(); - - int intObject = 5; - transformer.setParameter(SHORT_PARAM_NAME, intObject); - assertEquals(transformer.getParameter(SHORT_PARAM_NAME), intObject); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } + @Test (groups = {"readLocalFiles"}) + public void clear10() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(XSL_FILE)); + DOMSource domSource = new DOMSource((Node)document); + + Transformer transformer = tfactory.newTransformer(domSource); + transformer.setParameter(LONG_PARAM_NAME, PARAM_VALUE); + transformer.clearParameters(); + assertNull(transformer.getParameter(LONG_PARAM_NAME)); } } --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerExcpTest.java 2015-01-09 15:41:20.811092203 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerExcpTest.java 2015-01-09 15:41:20.734092083 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,12 +23,14 @@ package javax.xml.transform.ptests; import java.io.File; +import java.io.FilePermission; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; @@ -38,13 +40,14 @@ /** * Basic test for TransformerException specification. */ -public class TransformerExcpTest { +public class TransformerExcpTest extends JAXPBaseTest { /** - * Transform an unformatted xslt file. TransformerException is thrown. + * Transform an unformatted style-sheet file. TransformerException is thrown. */ @Test public void tfexception() { try { + setPermissions(new FilePermission(XML_DIR + "-", "read")); // invalid.xsl has well-formedness error. Therefore transform throws // TransformerException StreamSource streamSource @@ -60,6 +63,8 @@ assertNotNull(e.getException()); assertNull(e.getLocationAsString()); assertEquals(e.getMessageAndLocation(),e.getMessage()); + } finally { + setPermissions(); } } --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerFactoryTest.java 2015-01-09 15:41:21.165092755 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerFactoryTest.java 2015-01-09 15:41:21.087092633 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -24,39 +24,35 @@ import java.io.*; import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.stream.*; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.w3c.dom.*; -import org.xml.sax.SAXException; /** * Class containing the test cases for TransformerFactory API's * getAssociatedStyleSheet method. */ -public class TransformerFactoryTest { +public class TransformerFactoryTest extends JAXPFileBaseTest { /** * This test case checks for the getAssociatedStylesheet method * of TransformerFactory. * The style sheet returned is then copied to an tfactory01.out - * It will then be verified to see if it matches the golden files + * It will then be verified to see if it matches the golden files. + * + * @throws Exception If any errors occur. */ @Test - public void tfactory01() { - String outputFile = CLASS_DIR + "tfactory01.out"; + public void tfactory01() throws Exception { + String outputFile = USER_DIR + "tfactory01.out"; String goldFile = GOLDEN_DIR + "tfactory01GF.out"; String xmlFile = XML_DIR + "TransformerFactoryTest.xml"; String xmlURI = "file:///" + XML_DIR; @@ -76,10 +72,7 @@ "Modern", null); Transformer t = tFactory.newTransformer(); t.transform(s, streamResult); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException | ParserConfigurationException - | TransformerException | SAXException ex) { - failUnexpected(ex); } + assertTrue(compareWithGold(goldFile, outputFile)); } } --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest.java 2015-01-09 15:41:21.594093423 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest.java 2015-01-09 15:41:21.516093302 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -24,12 +24,9 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.ErrorListener; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; @@ -39,150 +36,132 @@ import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * Basic test cases for Transformer API */ -public class TransformerTest { +public class TransformerTest extends JAXPFileReadOnlyBaseTest { /** * XSLT file serves every test method. */ private final static String TEST_XSL = XML_DIR + "cities.xsl"; /** - * This tests if newTransformer(StreamSource) method returns Transformer - */ - @Test - public void transformer01() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - StreamSource streamSource = new StreamSource( - new File(TEST_XSL)); - Transformer transformer = tfactory.newTransformer(streamSource); - assertNotNull(transformer); - } catch (TransformerConfigurationException ex){ - failUnexpected(ex); - } + * This tests if newTransformer(StreamSource) method returns Transformer. + * @throws TransformerConfigurationException If for some reason the + * TransformerHandler can not be created. + */ + @Test (groups = {"readLocalFiles"}) + public void transformer01() throws TransformerConfigurationException { + TransformerFactory tfactory = TransformerFactory.newInstance(); + StreamSource streamSource = new StreamSource( + new File(TEST_XSL)); + Transformer transformer = tfactory.newTransformer(streamSource); + assertNotNull(transformer); } /** - * This tests if newTransformer(SAXSource) method returns Transformer - */ - @Test - public void transformer02() { - try { + * This tests if newTransformer(SAXSource) method returns Transformer. + * @throws Exception If any errors occur. + */ + @Test (groups = {"readLocalFiles"}) + public void transformer02() throws Exception { + try (FileInputStream fis = new FileInputStream(TEST_XSL)) { TransformerFactory tfactory = TransformerFactory.newInstance(); - InputSource is = new InputSource( - new FileInputStream(TEST_XSL)); - SAXSource saxSource = new SAXSource(is); + SAXSource saxSource = new SAXSource(new InputSource(fis)); Transformer transformer = tfactory.newTransformer(saxSource); assertNotNull(transformer); - } catch (TransformerConfigurationException | FileNotFoundException ex){ - failUnexpected(ex); } } /** - * This tests if newTransformer(DOMSource) method returns Transformer - */ - @Test - public void transformer03() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); + * This tests if newTransformer(DOMSource) method returns Transformer. + * + * @throws Exception If any errors occur. + */ + @Test (groups = {"readLocalFiles"}) + public void transformer03() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(TEST_XSL)); + DOMSource domSource = new DOMSource(document); + + Transformer transformer = tfactory.newTransformer(domSource); + assertNotNull(transformer); + } + + /** + * This tests set/get ErrorListener methods of Transformer. + * + * @throws Exception If any errors occur. + */ + @Test (groups = {"readLocalFiles"}) + public void transformer04() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(TEST_XSL)); + DOMSource domSource = new DOMSource(document); + + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(domSource); + transformer.setErrorListener(new MyErrorListener()); + assertNotNull(transformer.getErrorListener()); + assertTrue(transformer.getErrorListener() instanceof MyErrorListener); + } + + /** + * This tests getOutputProperties() method of Transformer. + * + * @throws Exception If any errors occur. + */ + @Test (groups = {"readLocalFiles"}) + public void transformer05() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(TEST_XSL)); + DOMSource domSource = new DOMSource(document); + + Transformer transformer = TransformerFactory.newInstance(). + newTransformer(domSource); + Properties prop = transformer.getOutputProperties(); + + assertEquals(prop.getProperty("indent"), "yes"); + assertEquals(prop.getProperty("method"), "xml"); + assertEquals(prop.getProperty("encoding"), "UTF-8"); + assertEquals(prop.getProperty("standalone"), "no"); + assertEquals(prop.getProperty("version"), "1.0"); + assertEquals(prop.getProperty("omit-xml-declaration"), "no"); + } + + /** + * This tests getOutputProperty() method of Transformer. + * + * @throws Exception If any errors occur. + */ + @Test (groups = {"readLocalFiles"}) + public void transformer06() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(TEST_XSL)); + DOMSource domSource = new DOMSource(document); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(TEST_XSL)); - DOMSource domSource = new DOMSource(document); - - Transformer transformer = tfactory.newTransformer(domSource); - assertNotNull(transformer); - } catch (TransformerConfigurationException | IOException - | ParserConfigurationException | SAXException ex){ - failUnexpected(ex); - } - } - - /** - * This tests set/get ErrorListener methods of Transformer - */ - @Test - public void transformer04() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(TEST_XSL)); - DOMSource domSource = new DOMSource(document); - - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(domSource); - transformer.setErrorListener(new MyErrorListener()); - assertNotNull(transformer.getErrorListener()); - assertTrue(transformer.getErrorListener() instanceof MyErrorListener); - } catch (IOException | IllegalArgumentException | ParserConfigurationException - | TransformerConfigurationException | SAXException ex){ - failUnexpected(ex); - } - } - - /** - * This tests getOutputProperties() method of Transformer - */ - @Test - public void transformer05() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(TEST_XSL)); - DOMSource domSource = new DOMSource(document); - - Transformer transformer = TransformerFactory.newInstance(). - newTransformer(domSource); - Properties prop = transformer.getOutputProperties(); - - assertEquals(prop.getProperty("indent"), "yes"); - assertEquals(prop.getProperty("method"), "xml"); - assertEquals(prop.getProperty("encoding"), "UTF-8"); - assertEquals(prop.getProperty("standalone"), "no"); - assertEquals(prop.getProperty("version"), "1.0"); - assertEquals(prop.getProperty("omit-xml-declaration"), "no"); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerConfigurationException ex){ - failUnexpected(ex); - } - } - - /** - * This tests getOutputProperty() method of Transformer - */ - @Test - public void transformer06() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(TEST_XSL)); - DOMSource domSource = new DOMSource(document); - - Transformer transformer = tfactory.newTransformer(domSource); - assertEquals(transformer.getOutputProperty("method"), "xml"); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerConfigurationException | IllegalArgumentException ex){ - failUnexpected(ex); - } + Transformer transformer = tfactory.newTransformer(domSource); + assertEquals(transformer.getOutputProperty("method"), "xml"); } } --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest02.java 2015-01-09 15:41:21.940093963 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest02.java 2015-01-09 15:41:21.862093841 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -25,42 +25,34 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; /** * Here a transformer is created using DOMSource. Some specific output property * is set on transformer. Then transform(StreamSource, StreamResult) is tested. */ -public class TransformerTest02 { +public class TransformerTest02 extends JAXPFileBaseTest { /** * Unit test for transform(StreamSource, StreamResult). + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "transformer02.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "transformer02.out"; String goldFile = GOLDEN_DIR + "transformer02GF.out"; String xsltFile = XML_DIR + "cities.xsl"; String xmlFile = XML_DIR + "cities.xml"; @@ -69,9 +61,8 @@ FileOutputStream fos = new FileOutputStream(outputFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(xsltFile)); - DOMSource domSource = new DOMSource(document); + DOMSource domSource = new DOMSource(dbf.newDocumentBuilder(). + parse(new File(xsltFile))); Transformer transformer = TransformerFactory.newInstance(). newTransformer(domSource); @@ -79,20 +70,8 @@ StreamResult streamResult = new StreamResult(fos); transformer.setOutputProperty("indent", "no"); - transformer.transform( streamSource, streamResult); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException | IllegalArgumentException - | ParserConfigurationException | TransformerException - | SAXException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + transformer.transform(streamSource, streamResult); } + assertTrue(compareWithGold(goldFile, outputFile)); } } --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest03.java 2015-01-09 15:41:22.294094514 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/TransformerTest03.java 2015-01-09 15:41:22.218094396 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -25,30 +25,20 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Properties; -import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; /** * Here Properties Object is populated with required properties.A transformer @@ -56,13 +46,15 @@ * for transformer. Then transform(StreamSource, StreamResult) is used for * transformation. This tests the setOutputProperties() method. */ -public class TransformerTest03 { +public class TransformerTest03 extends JAXPFileBaseTest { /** * Test for Transformer.setOutputProperties method. + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "transformer03.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "transformer03.out"; String goldFile = GOLDEN_DIR + "transformer03GF.out"; String xsltFile = XML_DIR + "cities.xsl"; String xmlFile = XML_DIR + "cities.xml"; @@ -81,29 +73,14 @@ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(xsltFile)); - DOMSource domSource = new DOMSource(document); + DOMSource domSource = new DOMSource(dbf.newDocumentBuilder(). + parse(new File(xsltFile))); Transformer transformer = TransformerFactory.newInstance(). newTransformer(domSource); - StreamSource streamSource = new StreamSource(fis); - StreamResult streamResult = new StreamResult(fos); - transformer.setOutputProperties(properties); - transformer.transform( streamSource, streamResult); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException - | IOException | TransformerException ex){ - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + transformer.transform(new StreamSource(fis), new StreamResult(fos)); } + assertTrue(compareWithGold(goldFile, outputFile)); } } --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/URIResolverTest.java 2015-01-09 15:41:22.647095064 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/URIResolverTest.java 2015-01-09 15:41:22.572094948 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -24,15 +24,10 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMSource; @@ -40,18 +35,17 @@ import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileBaseTest; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * URIResolver should be invoked when transform happens. */ -public class URIResolverTest implements URIResolver { +public class URIResolverTest extends JAXPFileBaseTest implements URIResolver { /** * System ID constant. */ @@ -72,9 +66,8 @@ */ private final static String XSL_TEMP_FILE = "temp/cities.xsl"; - /** - * expected Href. + * expected HREF. */ private final String validateHref; @@ -82,6 +75,14 @@ * expected Base URI. */ private final String validateBase; + + /** + * Default constructor for testng invocation. + */ + public URIResolverTest(){ + validateHref = null; + validateBase = null; + } /** * Constructor for setting expected Href and expected Base URI. @@ -110,166 +111,144 @@ /** * This is to test the URIResolver.resolve() method when a transformer is - * created using StreamSource. xsl file has xsl:include in it + * created using StreamSource. style-sheet file has xsl:include in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver01() { - try { + @Test (groups = {"readLocalFiles"}) + public static void resolver01() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_INCLUDE_FILE)) { TransformerFactory tfactory = TransformerFactory.newInstance(); URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); tfactory.setURIResolver(resolver); - StreamSource streamSource = new StreamSource(new FileInputStream(XSL_INCLUDE_FILE)); + StreamSource streamSource = new StreamSource(fis); streamSource.setSystemId(SYSTEM_ID); - - Transformer transformer = tfactory.newTransformer(streamSource); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); + assertNotNull(tfactory.newTransformer(streamSource)); } } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using DOMSource. xsl file has xsl:include in it + * created using DOMSource. style-sheet file has xsl:include in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver02() { - try { - TransformerFactory tfactory = TransformerFactory.newInstance(); - URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); - tfactory.setURIResolver(resolver); + @Test (groups = {"readLocalFiles"}) + public static void resolver02() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); + URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); + tfactory.setURIResolver(resolver); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(XSL_INCLUDE_FILE); - DOMSource domSource = new DOMSource(document, SYSTEM_ID); - - Transformer transformer = tfactory.newTransformer(domSource); - } catch (IOException | ParserConfigurationException - | TransformerConfigurationException | SAXException ex){ - failUnexpected(ex); - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(XSL_INCLUDE_FILE); + DOMSource domSource = new DOMSource(document, SYSTEM_ID); + + assertNotNull(tfactory.newTransformer(domSource)); } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using SAXSource. xsl file has xsl:include in it + * created using SAXSource. style-sheet file has xsl:include in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver03() { - try { + @Test (groups = {"readLocalFiles"}) + public static void resolver03() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_INCLUDE_FILE)){ URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setURIResolver(resolver); - InputSource is = new InputSource(new FileInputStream(XSL_INCLUDE_FILE)); + InputSource is = new InputSource(fis); is.setSystemId(SYSTEM_ID); SAXSource saxSource = new SAXSource(is); - - Transformer transformer = tfactory.newTransformer(saxSource); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); + assertNotNull(tfactory.newTransformer(saxSource)); } } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using StreamSource. xsl file has xsl:import in it + * created using StreamSource. style-sheet file has xsl:import in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver04() { - try { + @Test (groups = {"readLocalFiles"}) + public static void resolver04() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_IMPORT_FILE)) { URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setURIResolver(resolver); - - StreamSource streamSource = new StreamSource(new FileInputStream(XSL_IMPORT_FILE)); + StreamSource streamSource = new StreamSource(fis); streamSource.setSystemId(SYSTEM_ID); - - Transformer transformer = tfactory.newTransformer(streamSource); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); + assertNotNull(tfactory.newTransformer(streamSource)); } } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using DOMSource. xsl file has xsl:import in it + * created using DOMSource. style-sheet file has xsl:import in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver05() { - try { - URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); - TransformerFactory tfactory = TransformerFactory.newInstance(); - tfactory.setURIResolver(resolver); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(XSL_IMPORT_FILE)); - DOMSource domSource = new DOMSource(document, SYSTEM_ID); - - Transformer transformer = tfactory.newTransformer(domSource); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerConfigurationException ex){ - failUnexpected(ex); - } - + @Test (groups = {"readLocalFiles"}) + public static void resolver05() throws Exception { + URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); + TransformerFactory tfactory = TransformerFactory.newInstance(); + tfactory.setURIResolver(resolver); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(XSL_IMPORT_FILE)); + DOMSource domSource = new DOMSource(document, SYSTEM_ID); + assertNotNull(tfactory.newTransformer(domSource)); } /** * This is to test the URIResolver.resolve() method when a transformer is - * created using SAXSource. xsl file has xsl:import in it + * created using SAXSource. style-sheet file has xsl:import in it. + * + * @throws Exception If any errors occur. */ - @Test - public static void resolver06() { - try { + @Test (groups = {"readLocalFiles"}) + public static void resolver06() throws Exception { + try (FileInputStream fis = new FileInputStream(XSL_IMPORT_FILE)){ URIResolverTest resolver = new URIResolverTest(XSL_TEMP_FILE, SYSTEM_ID); TransformerFactory tfactory = TransformerFactory.newInstance(); tfactory.setURIResolver(resolver); - - InputSource is = new InputSource(new FileInputStream(XSL_IMPORT_FILE)); + InputSource is = new InputSource(fis); is.setSystemId(SYSTEM_ID); SAXSource saxSource = new SAXSource(is); - - Transformer transformer = tfactory.newTransformer(saxSource); - } catch (FileNotFoundException | TransformerConfigurationException ex){ - failUnexpected(ex); + assertNotNull(tfactory.newTransformer(saxSource)); } - } /** * This is to test the URIResolver.resolve() method when there is an error * in the file. + * + * @throws Exception If any errors occur. */ - @Test - public static void docResolver01() { - try { + @Test (groups = {"readLocalFiles"}) + public static void docResolver01() throws Exception { + try (FileInputStream fis = new FileInputStream(XML_DIR + "doctest.xsl")) { URIResolverTest resolver = new URIResolverTest("temp/colors.xml", SYSTEM_ID); - TransformerFactory tfactory = TransformerFactory.newInstance(); - - StreamSource streamSource = new StreamSource( - new FileInputStream(XML_DIR + FILE_SEP + "doctest.xsl")); + StreamSource streamSource = new StreamSource(fis); streamSource.setSystemId(SYSTEM_ID); - System.err.println(streamSource.getSystemId()); - Transformer transformer = tfactory.newTransformer(streamSource); + Transformer transformer = TransformerFactory.newInstance().newTransformer(streamSource); transformer.setURIResolver(resolver); - File f = new File(XML_DIR + FILE_SEP + "myFake.xml"); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.parse(f); + File f = new File(XML_DIR + "myFake.xml"); + Document document = DocumentBuilderFactory.newInstance(). + newDocumentBuilder().parse(f); // Use a Transformer for output DOMSource source = new DOMSource(document); - System.err.println("Ignore the following output -- just dumping it here"); StreamResult result = new StreamResult(System.err); + // No exception is expected because resolver resolve wrong URI. transformer.transform(source, result); - } catch (IOException | ParserConfigurationException | SAXException - | TransformerException ex) { - failUnexpected(ex); } } } --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/othervm/TFCErrorTest.java 2015-01-09 15:41:22.989095598 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/othervm/TFCErrorTest.java 2015-01-09 15:41:22.914095481 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 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 @@ -23,19 +23,22 @@ package javax.xml.transform.ptests.othervm; import javax.xml.transform.*; +import jaxp.library.JAXPBaseTest; +import static org.testng.Assert.fail; import org.testng.annotations.Test; /** * Negative test for set invalid TransformerFactory property. */ -public class TFCErrorTest{ +public class TFCErrorTest extends JAXPBaseTest { @Test(expectedExceptions = ClassNotFoundException.class) public void tfce01() throws Exception { try{ - System.setProperty("javax.xml.transform.TransformerFactory","xx"); - TransformerFactory tFactory = TransformerFactory.newInstance(); - } catch (TransformerFactoryConfigurationError error) { - throw error.getException(); + setSystemProperty("javax.xml.transform.TransformerFactory","xx"); + TransformerFactory.newInstance(); + fail("Expect TransformerFactoryConfigurationError here"); + } catch (TransformerFactoryConfigurationError expected) { + throw expected.getException(); } } } --- old/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathExpressionTest.java 2015-01-09 15:41:23.352096163 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathExpressionTest.java 2015-01-09 15:41:23.271096037 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,7 +23,7 @@ package javax.xml.xpath.ptests; -import java.io.IOException; +import java.io.FilePermission; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; @@ -31,7 +31,6 @@ import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import static javax.xml.xpath.XPathConstants.BOOLEAN; import static javax.xml.xpath.XPathConstants.NODE; @@ -41,7 +40,7 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import static javax.xml.xpath.ptests.XPathTestConst.XML_DIR; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertEquals; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -49,12 +48,11 @@ import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * Class containing the test cases for XPathExpression API. */ -public class XPathExpressionTest { +public class XPathExpressionTest extends JAXPFileReadOnlyBaseTest { /** * Document object for testing XML file. */ @@ -87,13 +85,11 @@ /** * Create Document object and XPath object for every time - * @throws ParserConfigurationException If the factory class cannot be - * loaded, instantiated - * @throws SAXException If any parse errors occur. - * @throws IOException If operation on xml file failed. + * @throws Exception If any errors occur. */ @BeforeTest - public void setup() throws ParserConfigurationException, SAXException, IOException { + public void setup() throws Exception { + setPermissions(new FilePermission(XML_PATH.toFile().toString(), "read")); document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(XML_PATH.toFile()); xpath = XPathFactory.newInstance().newXPath(); } @@ -101,343 +97,303 @@ /** * Test for evaluate(java.lang.Object item,QName returnType)throws * XPathExpressionException. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression01() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A). - evaluate(document, STRING), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression01() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A). + evaluate(document, STRING), "6"); } /** * evaluate(java.lang.Object item,QName returnType) throws NPE if input * source is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression02() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(null, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression02() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(null, STRING); } /** * evaluate(java.lang.Object item,QName returnType) throws NPE if returnType * is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression03() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(document, null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression03() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(document, null); } /** * Test for method evaluate(java.lang.Object item,QName returnType).If a * request is made to evaluate the expression in the absence of a context * item, simple expressions, such as "1+1", can be evaluated. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression04() { - try { - assertEquals(xpath.compile("1+1").evaluate(document, STRING), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression04() throws XPathExpressionException { + assertEquals(xpath.compile("1+1").evaluate(document, STRING), "2"); } /** * evaluate(java.lang.Object item,QName returnType) throws IAE If returnType * is not one of the types defined in XPathConstants. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckXPathExpression05() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(document, TEST_QNAME); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression05() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(document, TEST_QNAME); } /** * evaluate(java.lang.Object item,QName returnType) return correct boolean * value if returnType is Boolean. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression06() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A). + public void testCheckXPathExpression06() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(document, BOOLEAN), true); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } } /** * evaluate(java.lang.Object item,QName returnType) return correct boolean * value if returnType is Boolean. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression07() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_B). - evaluate(document, BOOLEAN), false); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression07() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_B). + evaluate(document, BOOLEAN), false); } /** * evaluate(java.lang.Object item,QName returnType) return correct number * value when return type is Double. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression08() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A). - evaluate(document, NUMBER), 6d); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression08() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A). + evaluate(document, NUMBER), 6d); } /** * evaluate(java.lang.Object item,QName returnType) evaluate an attribute * value which returnType is Node. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression09() { - try { - Attr attr = (Attr) xpath.compile(EXPRESSION_NAME_A). - evaluate(document, NODE); - assertEquals(attr.getValue(), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression09() throws XPathExpressionException { + Attr attr = (Attr) xpath.compile(EXPRESSION_NAME_A). + evaluate(document, NODE); + assertEquals(attr.getValue(), "6"); } /** * evaluate(java.lang.Object item,QName returnType) evaluate an attribute * value which returnType is NodeList. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression10() { - try { - NodeList nodeList = (NodeList) xpath.compile(EXPRESSION_NAME_A). - evaluate(document, NODESET); - Attr attr = (Attr) nodeList.item(0); - assertEquals(attr.getValue(), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression10() throws XPathExpressionException { + NodeList nodeList = (NodeList) xpath.compile(EXPRESSION_NAME_A). + evaluate(document, NODESET); + Attr attr = (Attr) nodeList.item(0); + assertEquals(attr.getValue(), "6"); } /** * Test for evaluate(java.lang.Object item) when returnType is left off of * the XPath.evaluate method, all expressions are evaluated to a String * value. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression11() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A).evaluate(document), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression11() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A).evaluate(document), "6"); } /** * evaluate(java.lang.Object item) throws NPE if expression is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression12() { - try { - xpath.compile(null).evaluate(document); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression12() throws XPathExpressionException { + xpath.compile(null).evaluate(document); } /** * evaluate(java.lang.Object item) when a request is made to evaluate the * expression in the absence of a context item, simple expressions, such as * "1+1", can be evaluated. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathExpression13() { - try { - assertEquals(xpath.compile("1+1").evaluate(document), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression13() throws XPathExpressionException { + assertEquals(xpath.compile("1+1").evaluate(document), "2"); } /** * evaluate(java.lang.Object item) throws NPE if document is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression14() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression14() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(null); } /** * valuate(InputSource source) return a string value if return type is * String. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression15() { + @Test (groups = {"readLocalFiles"}) + public void testCheckXPathExpression15() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is)), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source) throws NPE if input source is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression16() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression16() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(null); } /** - * evaluate(InputSource source) throws NPE if expression is null + * evaluate(InputSource source) throws NPE if expression is null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression17() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPathExpression17() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(null).evaluate(new InputSource(is)); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source) throws XPathExpressionException if * returnType is String junk characters. - * - * @throws XPathExpressionException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPathExpression18() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPathExpression18() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile("-*&").evaluate(new InputSource(is)); - } catch (IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source) throws XPathExpressionException if * expression is a blank string " ". - * - * @throws XPathExpressionException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPathExpression19() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPathExpression19() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(" ").evaluate(new InputSource(is)); - } catch (IOException ex) { - failUnexpected(ex); } } /** * Test for evaluate(InputSource source,QName returnType) returns a string * value if returnType is String. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression20() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression20() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), STRING), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) throws NPE if source is * null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression21() { - try { - xpath.compile(EXPRESSION_NAME_A).evaluate(null, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathExpression21() throws XPathExpressionException { + xpath.compile(EXPRESSION_NAME_A).evaluate(null, STRING); } /** * evaluate(InputSource source,QName returnType) throws NPE if expression is * null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression22() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPathExpression22() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(null).evaluate(new InputSource(is), STRING); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) throws NPE if returnType is * null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathExpression23() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPathExpression23() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(EXPRESSION_NAME_A).evaluate(new InputSource(is), null); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) throws * XPathExpressionException if expression is junk characters. - * - * @throws XPathExpressionException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPathExpression24() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPathExpression24() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile("-*&").evaluate(new InputSource(is), STRING); - } catch (IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) throws * XPathExpressionException if expression is blank " ". - * - * @throws XPathExpressionException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPathExpression25() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPathExpression25() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(" ").evaluate(new InputSource(is), STRING); - } catch (IOException ex) { - failUnexpected(ex); } } @@ -445,85 +401,85 @@ * evaluate(InputSource source,QName returnType) throws * IllegalArgumentException if returnType is not one of the types defined * in XPathConstants. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckXPathExpression26() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = IllegalArgumentException.class) + public void testCheckXPathExpression26() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.compile(EXPRESSION_NAME_A).evaluate(new InputSource(is), TEST_QNAME); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) return a correct boolean * value if returnType is Boolean. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression27() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression27() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), BOOLEAN), true); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) return a correct boolean * value if returnType is Boolean. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression28() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression28() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_B). evaluate(new InputSource(is), BOOLEAN), false); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * evaluate(InputSource source,QName returnType) return a correct number * value if returnType is Number. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression29() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression29() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), NUMBER), 6d); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * Test for evaluate(InputSource source,QName returnType) returns a node if * returnType is Node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression30() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression30() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { Attr attr = (Attr) xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), NODE); assertEquals(attr.getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * Test for evaluate(InputSource source,QName returnType) return a node list * if returnType is NodeList. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPathExpression31() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPathExpression31() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { NodeList nodeList = (NodeList) xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), NODESET); assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } } --- old/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFactoryTest.java 2015-01-09 15:41:23.707096717 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFactoryTest.java 2015-01-09 15:41:23.632096600 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -26,14 +26,14 @@ import static javax.xml.xpath.XPathConstants.DOM_OBJECT_MODEL; import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactoryConfigurationException; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPBaseTest; import static org.testng.AssertJUnit.assertNotNull; import org.testng.annotations.Test; /** * Class containing the test cases for XPathFactory API. */ -public class XPathFactoryTest { +public class XPathFactoryTest extends JAXPBaseTest { /** * Valid URL for creating a XPath factory. */ @@ -54,21 +54,21 @@ /** * XPathFactory.newInstance(String uri) throws NPE if uri is null. + * + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test(expectedExceptions = NullPointerException.class) - private void testCheckXPathFactory02() { - try { - XPathFactory.newInstance(null); - } catch (XPathFactoryConfigurationException ex) { - failUnexpected(ex); - } + public void testCheckXPathFactory02() throws XPathFactoryConfigurationException { + XPathFactory.newInstance(null); } /** * XPathFactory.newInstance(String uri) throws XPFCE if uri is just a blank * string. * - * @throws XPathFactoryConfigurationException + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test(expectedExceptions = XPathFactoryConfigurationException.class) public void testCheckXPathFactory03() throws XPathFactoryConfigurationException { @@ -78,21 +78,21 @@ /** * Test for constructor - XPathFactory.newInstance(String uri) with valid * url - "http://java.sun.com/jaxp/xpath/dom". + * + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test - public void testCheckXPathFactory04() { - try { - assertNotNull(XPathFactory.newInstance(VALID_URL)); - } catch (XPathFactoryConfigurationException ex) { - failUnexpected(ex); - } + public void testCheckXPathFactory04() throws XPathFactoryConfigurationException { + assertNotNull(XPathFactory.newInstance(VALID_URL)); } /** * Test for constructor - XPathFactory.newInstance(String uri) with invalid * url - "http://java.sun.com/jaxp/xpath/dom1". * - * @throws XPathFactoryConfigurationException + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test(expectedExceptions = XPathFactoryConfigurationException.class) public void testCheckXPathFactory05() throws XPathFactoryConfigurationException { @@ -112,26 +112,24 @@ * Test for constructor - XPathFactory.newInstance(String uri) with valid * url - "http://java.sun.com/jaxp/xpath/dom" and creating XPath with * newXPath(). + * + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test - public void testCheckXPathFactory07() { - try { - assertNotNull(XPathFactory.newInstance(VALID_URL).newXPath()); - } catch (XPathFactoryConfigurationException ex) { - failUnexpected(ex); - } + public void testCheckXPathFactory07() throws XPathFactoryConfigurationException { + assertNotNull(XPathFactory.newInstance(VALID_URL).newXPath()); } /** * Test for constructor - XPathFactory.newInstance(String uri) with valid * uri - DOM_OBJECT_MODEL.toString(). + * + * @throws XPathFactoryConfigurationException If the specified object model + * is unavailable, or if there is a configuration error. */ @Test - public void testCheckXPathFactory08() { - try { - assertNotNull(XPathFactory.newInstance(DOM_OBJECT_MODEL)); - } catch (XPathFactoryConfigurationException ex) { - failUnexpected(ex); - } + public void testCheckXPathFactory08() throws XPathFactoryConfigurationException { + assertNotNull(XPathFactory.newInstance(DOM_OBJECT_MODEL)); } } --- old/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFunctionResolverTest.java 2015-01-09 15:41:24.055097259 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathFunctionResolverTest.java 2015-01-09 15:41:23.979097141 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -26,7 +26,7 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -34,7 +34,7 @@ /** * Class containing the test cases for XPathFunctionResolver. */ -public class XPathFunctionResolverTest { +public class XPathFunctionResolverTest extends JAXPBaseTest { /** * A XPath for evaluation environment and expressions. */ @@ -54,26 +54,22 @@ /** * Test for resolveFunction(QName functionName,int arity). evaluate will * continue as long as functionName is meaningful. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPathFunctionResolver01() { - try { - assertEquals(xpath.evaluate("round(1.7)", (Object)null), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathFunctionResolver01() throws XPathExpressionException { + assertEquals(xpath.evaluate("round(1.7)", (Object)null), "2"); } /** * Test for resolveFunction(QName functionName,int arity); evaluate throws * NPE if functionName is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPathFunctionResolver02() { - try { - assertEquals(xpath.evaluate(null, "5"), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPathFunctionResolver02() throws XPathExpressionException { + assertEquals(xpath.evaluate(null, "5"), "2"); } } --- old/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathTest.java 2015-01-09 15:41:24.433097848 -0800 +++ new/test/javax/xml/jaxp/functional/javax/xml/xpath/ptests/XPathTest.java 2015-01-09 15:41:24.355097727 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,7 +23,7 @@ package javax.xml.xpath.ptests; -import java.io.IOException; +import java.io.FilePermission; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; @@ -33,7 +33,6 @@ import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import static javax.xml.xpath.XPathConstants.BOOLEAN; import static javax.xml.xpath.XPathConstants.NODE; @@ -43,7 +42,7 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import static javax.xml.xpath.ptests.XPathTestConst.XML_DIR; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; @@ -53,12 +52,11 @@ import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; /** * Class containing the test cases for XPath API. */ -public class XPathTest { +public class XPathTest extends JAXPFileReadOnlyBaseTest { /** * Document object for testing XML file. */ @@ -91,13 +89,11 @@ /** * Create Document object and XPath object for every time - * @throws ParserConfigurationException If the factory class cannot be - * loaded, instantiated - * @throws SAXException If any parse errors occur. - * @throws IOException If operation on xml file failed. + * @throws Exception If any errors occur. */ @BeforeTest - public void setup() throws ParserConfigurationException, SAXException, IOException { + public void setup() throws Exception { + setPermissions(new FilePermission(XML_DIR + "-", "read")); document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(XML_PATH.toFile()); xpath = XPathFactory.newInstance().newXPath(); } @@ -105,62 +101,54 @@ /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item, QName returnType) which return type is String. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath01() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, STRING), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath01() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, STRING), "6"); } /** * Test for XPath.compile(java.lang.String expression) and then * evaluate(java.lang.Object item, QName returnType). + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath02() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_A).evaluate(document, STRING), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath02() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_A).evaluate(document, STRING), "6"); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item) when the third argument is left off of the XPath.evaluate method, * all expressions are evaluated to a String value. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath03() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath03() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document), "6"); } /** * Test for XPath.compile(java.lang.String expression). If expression is * null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath04() { - try { - xpath.compile(null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath04() throws XPathExpressionException { + xpath.compile(null); } /** * Test for XPath.compile(java.lang.String expression). If expression cannot * be compiled junk characters, should throw XPathExpressionException. - * - * @throws XPathExpressionException + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = XPathExpressionException.class) public void testCheckXPath05() throws XPathExpressionException { @@ -170,8 +158,8 @@ /** * Test for XPath.compile(java.lang.String expression). If expression is * blank, should throw XPathExpressionException - * - * @throws XPathExpressionException + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = XPathExpressionException.class) public void testCheckXPath06() throws XPathExpressionException { @@ -181,55 +169,46 @@ /** * Test for XPath.compile(java.lang.String expression). The expression * cannot be evaluated as this does not exist. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath07() { - try { - assertEquals(xpath.compile(EXPRESSION_NAME_B).evaluate(document, STRING), ""); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } - + public void testCheckXPath07() throws XPathExpressionException { + assertEquals(xpath.compile(EXPRESSION_NAME_B).evaluate(document, STRING), ""); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object - * item, QName returnType). If String expression is null, should throw NPE + * item, QName returnType). If String expression is null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath08() { - try { - xpath.evaluate(null, document, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath08() throws XPathExpressionException { + xpath.evaluate(null, document, STRING); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item, QName returnType). If item is null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath09() { - try { - xpath.evaluate(EXPRESSION_NAME_A, null, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath09() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, null, STRING); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item, QName returnType). If returnType is null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath10() { - try { - xpath.evaluate(EXPRESSION_NAME_A, document, null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath10() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, document, null); } /** @@ -237,23 +216,20 @@ * item, QName returnType). If a request is made to evaluate the expression * in the absence of a context item, simple expressions, such as "1+1", can * be evaluated. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath11() { - try { - assertEquals(xpath.evaluate("1+1", document, STRING), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath11() throws XPathExpressionException { + assertEquals(xpath.evaluate("1+1", document, STRING), "2"); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) throws XPathExpressionException if expression is a empty * string "". - * . - * - * @throws XPathExpressionException + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = XPathExpressionException.class) public void testCheckXPath12() throws XPathExpressionException { @@ -264,161 +240,141 @@ * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) throws IllegalArgumentException if returnType is not one of * the types defined in XPathConstants. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckXPath13() { - try { - xpath.evaluate(EXPRESSION_NAME_A, document, TEST_QNAME); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath13() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, document, TEST_QNAME); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) returns correct boolean value if returnType is Boolean. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath14() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, BOOLEAN), true); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath14() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, BOOLEAN), true); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) returns false as expression is not successful in evaluating * to any result if returnType is Boolean. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath15() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_B, document, BOOLEAN), false); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath15() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_B, document, BOOLEAN), false); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) returns correct number value if return type is Number. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath16() { - try { - assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, NUMBER), 6d); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath16() throws XPathExpressionException { + assertEquals(xpath.evaluate(EXPRESSION_NAME_A, document, NUMBER), 6d); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item, QName * returnType) returns correct string value if return type is Node. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath17() { - try { - assertEquals(((Attr)xpath.evaluate(EXPRESSION_NAME_A, document, NODE)).getValue(), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath17() throws XPathExpressionException { + assertEquals(((Attr)xpath.evaluate(EXPRESSION_NAME_A, document, NODE)).getValue(), "6"); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item, QName returnType). If return type is NodeList,the evaluated value * equals to "6" as expected. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath18() { - try { - NodeList nodeList = (NodeList)xpath.evaluate(EXPRESSION_NAME_A, document, NODESET); - assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath18() throws XPathExpressionException { + NodeList nodeList = (NodeList)xpath.evaluate(EXPRESSION_NAME_A, document, NODESET); + assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item). If expression is null, should throw NPE. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath19() { - try { - xpath.evaluate(null, document); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath19() throws XPathExpressionException { + xpath.evaluate(null, document); } /** * Test for XPath.evaluate(java.lang.String expression, java.lang.Object * item). If a request is made to evaluate the expression in the absence of * a context item, simple expressions, such as "1+1", can be evaluated. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test - public void testCheckXPath20() { - try { - assertEquals(xpath.evaluate("1+1", document), "2"); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath20() throws XPathExpressionException { + assertEquals(xpath.evaluate("1+1", document), "2"); } /** * XPath.evaluate(java.lang.String expression, java.lang.Object item) throws * NPE if InputSource is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath21() { - try { - xpath.evaluate(EXPRESSION_NAME_A, null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath21() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, null); } /** * XPath.evaluate(java.lang.String expression, InputSource source) return * correct value by looking for Node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath22() { + @Test (groups = {"readLocalFiles"}) + public void testCheckXPath22() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is)), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source) throws * NPE if InputSource is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath23() { - try { - xpath.evaluate(EXPRESSION_NAME_A, null); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath23() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, null); } /** * XPath.evaluate(java.lang.String expression, InputSource source) throws * NPE if String expression is null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath24() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPath24() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(null, new InputSource(is)); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } @@ -426,112 +382,102 @@ * Test for XPath.evaluate(java.lang.String expression, InputSource source). * If expression is junk characters, expression cannot be evaluated, should * throw XPathExpressionException. - * - * @throws XPathExpressionException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPath25() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPath25() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate("-*&", new InputSource(is)); - } catch (IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source) throws * XPathExpressionException if expression is blank " ". - * - * @throws XPathExpressionException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPath26() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPath26() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(" ", new InputSource(is)); - } catch (IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) returns correct string value which return type is String. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath27() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath27() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), STRING), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) throws NPE if source is null. + * + * @throws XPathExpressionException If the expression cannot be evaluated. */ @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath28() { - try { - xpath.evaluate(EXPRESSION_NAME_A, null, STRING); - } catch (XPathExpressionException ex) { - failUnexpected(ex); - } + public void testCheckXPath28() throws XPathExpressionException { + xpath.evaluate(EXPRESSION_NAME_A, null, STRING); } /** * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) throws NPE if expression is null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath29() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPath29() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(null, new InputSource(is), STRING); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, - * QName returnType) throws NPE if returnType is null . + * QName returnType) throws NPE if returnType is null. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void testCheckXPath30() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void testCheckXPath30() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), null); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) throws XPathExpressionException if expression is junk characters. - * - * @throws XPathExpressionException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPath31() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPath31() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate("-*&", new InputSource(is), STRING); - } catch (IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, QName * returnType) throws XPathExpressionException if expression is blank " ". - * - * @throws XPathExpressionException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = XPathExpressionException.class) - public void testCheckXPath32() throws XPathExpressionException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = XPathExpressionException.class) + public void testCheckXPath32() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(" ", new InputSource(is), STRING); - } catch (IOException ex) { - failUnexpected(ex); } } @@ -539,84 +485,84 @@ * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) throws IllegalArgumentException if returnType is not * one of the types defined in XPathConstants. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckXPath33() { + @Test(groups = {"readLocalFiles"}, expectedExceptions = IllegalArgumentException.class) + public void testCheckXPath33() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), TEST_QNAME); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) return correct boolean value if return type is Boolean. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath34() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath34() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), BOOLEAN), true); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) return correct boolean value if return type is Boolean. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath35() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath35() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_B, new InputSource(is), BOOLEAN), false); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) return correct number value if return type is Number. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath36() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath36() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NUMBER), 6d); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) return correct string value if return type is Node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath37() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath37() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(((Attr)xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NODE)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * Test for XPath.evaluate(java.lang.String expression, InputSource source, * QName returnType) which return type is NodeList. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath38() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath38() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { NodeList nodeList = (NodeList)xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NODESET); assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } @@ -624,57 +570,57 @@ * Test for XPath.evaluate(java.lang.String expression, InputSource iSource, * QName returnType). If return type is Boolean, should return false as * expression is not successful in evaluating to any result. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath52() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath52() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_B, new InputSource(is), BOOLEAN), false); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource iSource, QName * returnType) returns correct number value which return type is Number. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath53() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath53() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NUMBER), 6d); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource iSource, QName * returnType) returns a node value if returnType is Node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath54() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath54() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { assertEquals(((Attr)xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NODE)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } /** * XPath.evaluate(java.lang.String expression, InputSource iSource, QName * returnType) returns a node list if returnType is NodeList. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckXPath55() { + @Test(groups = {"readLocalFiles"}) + public void testCheckXPath55() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { NodeList nodeList = (NodeList)xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is), NODESET); assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); - } catch (XPathExpressionException | IOException ex) { - failUnexpected(ex); } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttrImplTest.java 2015-01-09 15:41:24.807098431 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttrImplTest.java 2015-01-09 15:41:24.722098299 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -22,6 +22,7 @@ */ package org.xml.sax.ptests; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import org.testng.annotations.Test; @@ -30,7 +31,7 @@ /** * Class containing the test cases for AttributesImpl API. */ -public class AttrImplTest { +public class AttrImplTest extends JAXPBaseTest { private static final String CAR_URI = "http://www.cars.com/xml"; private static final String CAR_LOCALNAME = "part"; --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesNSTest.java 2015-01-09 15:41:25.168098994 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesNSTest.java 2015-01-09 15:41:25.091098874 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,20 +23,13 @@ package org.xml.sax.ptests; import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -45,39 +38,29 @@ * ContentHandler has Attributes as one of its arguments. Attributes * pertaining to an element are taken into this argument and various methods * of Attributes interfaces are tested. This program uses Namespace processing - * with namespaces in xml file. This program does not use Validation + * with namespaces in XML file. This program does not use Validation */ -public class AttributesNSTest { +public class AttributesNSTest extends JAXPFileBaseTest { /** * Test for Attribute Interface's setter/getter. + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "AttributesNS.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "AttributesNS.out"; String goldFile = GOLDEN_DIR + "AttributesNSGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - // http://www.saxproject.com/?selected=namespaces namespace-prefixes - //set to false to supress xmlns attributes - spf.setFeature("http://xml.org/sax/features/namespace-prefixes", - false); - SAXParser saxParser = spf.newSAXParser(); - MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile); - saxParser.parse(new File(xmlFile), myAttrCHandler); - myAttrCHandler.flushAndClose(); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException | ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + // http://www.saxproject.com/?selected=namespaces namespace-prefixes + //set to false to supress xmlns attributes + spf.setFeature("http://xml.org/sax/features/namespace-prefixes", + false); + SAXParser saxParser = spf.newSAXParser(); + MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile); + saxParser.parse(new File(xmlFile), myAttrCHandler); + myAttrCHandler.flushAndClose(); + assertTrue(compareWithGold(goldFile, outputFile)); } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesTest.java 2015-01-09 15:41:25.511099529 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/AttributesTest.java 2015-01-09 15:41:25.436099412 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,20 +23,13 @@ package org.xml.sax.ptests; import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -48,37 +41,28 @@ * This program uses Namespace processing without any namepsaces in xml file. * This program uses Validation */ -public class AttributesTest { +public class AttributesTest extends JAXPFileBaseTest { /** * Unit test for Attributes interface. Prints all attributes into output * file. Check it with golden file. + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "Attributes.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "Attributes.out"; String goldFile = GOLDEN_DIR + "AttributesGF.out"; String xmlFile = XML_DIR + "family.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setFeature("http://xml.org/sax/features/namespace-prefixes", - true); - spf.setValidating(true); - SAXParser saxParser = spf.newSAXParser(); - MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile); - saxParser.parse(new File(xmlFile), myAttrCHandler); - myAttrCHandler.flushAndClose(); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException | ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setFeature("http://xml.org/sax/features/namespace-prefixes", + true); + spf.setValidating(true); + SAXParser saxParser = spf.newSAXParser(); + MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile); + saxParser.parse(new File(xmlFile), myAttrCHandler); + myAttrCHandler.flushAndClose(); + assertTrue(compareWithGold(goldFile, outputFile)); } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ContentHandlerTest.java 2015-01-09 15:41:25.859100071 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ContentHandlerTest.java 2015-01-09 15:41:25.782099951 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -26,24 +26,18 @@ import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -52,43 +46,34 @@ * transverses XML and print all visited node when XMLreader parses XML. Test * verifies output is same as the golden file. */ -public class ContentHandlerTest { +public class ContentHandlerTest extends JAXPFileBaseTest { /** * Content event handler visit all nodes to print to output file. + * + * @throws Exception If any errors occur. */ @Test - public void testcase01() { - String outputFile = CLASS_DIR + "Content.out"; + public void testcase01() throws Exception { + String outputFile = USER_DIR + "Content.out"; String goldFile = GOLDEN_DIR + "ContentGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try(FileInputStream instream = new FileInputStream(xmlFile)) { + try(FileInputStream instream = new FileInputStream(xmlFile); + MyContentHandler cHandler = new MyContentHandler(outputFile)) { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - ContentHandler cHandler = new MyContentHandler(outputFile); xmlReader.setContentHandler(cHandler); - InputSource is = new InputSource(instream); - xmlReader.parse(is); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch( IOException | SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + xmlReader.parse(new InputSource(instream)); } + assertTrue(compareWithGold(goldFile, outputFile)); } } /** * A content write out handler. */ -class MyContentHandler extends XMLFilterImpl { +class MyContentHandler extends XMLFilterImpl implements AutoCloseable { /** * Prefix to every exception. */ @@ -258,4 +243,14 @@ throw new SAXException(WRITE_ERROR, ex); } } + + /** + * Close the writer if it's initiated. + * @throws IOException if any IO error when close buffered writer. + */ + @Override + public void close() throws IOException { + if (bWriter != null) + bWriter.close(); + } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/DefaultHandlerTest.java 2015-01-09 15:41:26.201100604 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/DefaultHandlerTest.java 2015-01-09 15:41:26.126100487 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -26,15 +26,11 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.xml.sax.Attributes; @@ -42,7 +38,6 @@ import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -50,46 +45,32 @@ * XMLReader parse XML with default handler that transverses XML and * print all visited node. Test verifies output is same as the golden file. */ -public class DefaultHandlerTest { +public class DefaultHandlerTest extends JAXPFileBaseTest { /** * Test default handler that transverses XML and print all visited node. + * + * @throws Exception If any errors occur. */ @Test - public void testDefaultHandler() { - String outputFile = CLASS_DIR + "DefaultHandler.out"; + public void testDefaultHandler() throws Exception { + String outputFile = USER_DIR + "DefaultHandler.out"; String goldFile = GOLDEN_DIR + "DefaultHandlerGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxparser = spf.newSAXParser(); - - MyDefaultHandler handler = new MyDefaultHandler(outputFile); - File file = new File(xmlFile); - String Absolutepath = file.getAbsolutePath(); - String newAbsolutePath = Absolutepath; - if (File.separatorChar == '\\') - newAbsolutePath = Absolutepath.replace('\\', '/'); - String uri = "file:///" + newAbsolutePath; - saxparser.parse(uri, handler); - } catch (IOException | ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - // Need close the output file before we compare it with golden file. - try { - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser saxparser = spf.newSAXParser(); + + MyDefaultHandler handler = new MyDefaultHandler(outputFile); + File file = new File(xmlFile); + String Absolutepath = file.getAbsolutePath(); + String newAbsolutePath = Absolutepath; + if (File.separatorChar == '\\') + newAbsolutePath = Absolutepath.replace('\\', '/'); + saxparser.parse("file:///" + newAbsolutePath, handler); + + assertTrue(compareWithGold(goldFile, outputFile)); + } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/EHFatalTest.java 2015-01-09 15:41:26.552101151 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/EHFatalTest.java 2015-01-09 15:41:26.475101031 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -26,23 +26,19 @@ import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import org.testng.annotations.Test; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -50,14 +46,16 @@ * ErrorHandler unit test. Set a ErrorHandle to XMLReader. Capture fatal error * events in ErrorHandler. */ -public class EHFatalTest { +public class EHFatalTest extends JAXPFileBaseTest { /** * Error Handler to capture all error events to output file. Verifies the * output file is same as golden file. + * + * @throws Exception If any errors occur. */ @Test - public void testEHFatal() { - String outputFile = CLASS_DIR + "EHFatal.out"; + public void testEHFatal() throws Exception { + String outputFile = USER_DIR + "EHFatal.out"; String goldFile = GOLDEN_DIR + "EHFatalGF.out"; String xmlFile = XML_DIR + "invalid.xml"; @@ -68,25 +66,12 @@ xmlReader.setErrorHandler(eHandler); InputSource is = new InputSource(instream); xmlReader.parse(is); - } catch (IOException | ParserConfigurationException ex) { - failUnexpected(ex); - } catch (SAXException ex) { - System.out.println("This is expected:" + ex); + fail("Parse should throw SAXException"); + } catch (SAXException expected) { + // This is expected. } // Need close the output file before we compare it with golden file. - try { - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + assertTrue(compareWithGold(goldFile, outputFile)); } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSSupportTest.java 2015-01-09 15:41:26.902101697 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSSupportTest.java 2015-01-09 15:41:26.826101578 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,6 +23,7 @@ package org.xml.sax.ptests; import java.util.Enumeration; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import org.testng.annotations.Test; @@ -31,7 +32,7 @@ /** * Unit test cases for NamespaceSupport API */ -public class NSSupportTest { +public class NSSupportTest extends JAXPBaseTest { /** * Empty prefix name. */ --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ParserAdapterTest.java 2015-01-09 15:41:27.247102235 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ParserAdapterTest.java 2015-01-09 15:41:27.168102112 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,10 +23,8 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; @@ -35,7 +33,6 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.ParserAdapter; import org.xml.sax.helpers.XMLFilterImpl; @@ -47,7 +44,7 @@ * Unit test cases for ParserAdapter API. By default the only features recognized * are namespaces and namespace-prefixes. */ -public class ParserAdapterTest { +public class ParserAdapterTest extends JAXPFileReadOnlyBaseTest { /** * namespaces feature name. */ @@ -67,10 +64,9 @@ /** * Initiate ParserAdapter. - * @throws ParserConfigurationException - * @throws SAXException + * @throws Exception If any errors occur. */ - ParserAdapterTest() throws ParserConfigurationException, SAXException { + ParserAdapterTest() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); XMLReaderAdapter xmlReaderAdapter = new XMLReaderAdapter(xmlReader); @@ -151,129 +147,111 @@ /** * parserAdapter.getFeature(NAMESPACES) returns true be default. + * + * @exception Exception If any errors occur. */ @Test - public void getFeature01() { - try { - assertTrue(parserAdapter.getFeature(NAMESPACES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void getFeature01() throws Exception { + assertTrue(parserAdapter.getFeature(NAMESPACES)); } /** * parserAdapter.getFeature(NAMESPACE_PREFIXES) returns true be default. + * + * @exception Exception If any errors occur. */ @Test - public void getFeature02() { - try { - assertFalse(parserAdapter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void getFeature02() throws Exception { + assertFalse(parserAdapter.getFeature(NAMESPACE_PREFIXES)); } /** * SAXNotRecognizedException thrown when feature name is not known one. - * @throws org.xml.sax.SAXNotRecognizedException expected Exception + * + * @exception Exception If any errors occur. */ @Test(expectedExceptions = SAXNotRecognizedException.class) - public void getFeature03() throws SAXNotRecognizedException { - try { - parserAdapter.getFeature("no-meaning-feature"); - } catch (SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void getFeature03() throws Exception { + parserAdapter.getFeature("no-meaning-feature"); } /** * Obtain getFeature after it's set returns set value. + * + * @exception Exception If any errors occur. */ @Test - public void setFeature01() { - try { - parserAdapter.setFeature(NAMESPACES, false); - assertFalse(parserAdapter.getFeature(NAMESPACES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void setFeature01() throws Exception { + parserAdapter.setFeature(NAMESPACES, false); + assertFalse(parserAdapter.getFeature(NAMESPACES)); } /** * Obtain getFeature after it's set returns set value. + * + * @exception Exception If any errors occur. */ @Test - public void setFeature02() { - try { - parserAdapter.setFeature(NAMESPACE_PREFIXES, false); - assertFalse(parserAdapter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void setFeature02() throws Exception { + parserAdapter.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(parserAdapter.getFeature(NAMESPACE_PREFIXES)); } /** * Obtain getFeature after it's set returns set value. + * + * @exception Exception If any errors occur. */ @Test - public void setFeature03() { - try { - parserAdapter.setFeature(NAMESPACES, true); - assertTrue(parserAdapter.getFeature(NAMESPACES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void setFeature03() throws Exception { + parserAdapter.setFeature(NAMESPACES, true); + assertTrue(parserAdapter.getFeature(NAMESPACES)); } /** * Obtain getFeature after it's set returns set value. + * + * @exception Exception If any errors occur. */ @Test - public void setFeature04() { - try { - parserAdapter.setFeature(NAMESPACE_PREFIXES, true); - assertTrue(parserAdapter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXNotRecognizedException | SAXNotSupportedException ex) { - failUnexpected(ex); - } + public void setFeature04() throws Exception { + parserAdapter.setFeature(NAMESPACE_PREFIXES, true); + assertTrue(parserAdapter.getFeature(NAMESPACE_PREFIXES)); } /** - * NPE expected when parsing a null object by ParserAdapter. + * NPE expected when parsing a null object by ParserAdapter. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = NullPointerException.class) - public void parse01() { - try { - parserAdapter.parse((InputSource)null); - } catch (IOException | SAXException ex) { - failUnexpected(ex); - } + public void parse01() throws Exception { + parserAdapter.parse((InputSource)null); } /** * SAXException expected when parsing a wrong-formatter XML with ParserAdapter. - * @throws org.xml.sax.SAXException + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class) - public void parse02() throws SAXException { + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class) + public void parse02() throws Exception { try(FileInputStream fis = new FileInputStream(XML_DIR + "invalid.xml")) { InputSource is = new InputSource(fis); parserAdapter.parse(is); - } catch (IOException ex) { - failUnexpected(ex); } } /** * Parse a well-formatter XML with ParserAdapter. + * + * @throws Exception If any errors occur. */ - @Test - public void parse03() { + @Test(groups = {"readLocalFiles"}) + public void parse03() throws Exception { try(FileInputStream fis = new FileInputStream(XML_DIR + "correct.xml")) { InputSource is = new InputSource(fis); parserAdapter.parse(is); - } catch (IOException | SAXException ex) { - failUnexpected(ex); } } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ResolverTest.java 2015-01-09 15:41:27.598102782 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/ResolverTest.java 2015-01-09 15:41:27.520102660 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -26,21 +26,16 @@ import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -48,12 +43,14 @@ * Entity resolver should be invoked in XML parse. This test verifies parsing * process by checking the output with golden file. */ -public class ResolverTest { +public class ResolverTest extends JAXPFileBaseTest { /** - * Unit test for entityResolver setter. + * Unit test for entityResolver setter. + * + * @throws Exception If any errors occur. */ - public void testResolver() { - String outputFile = CLASS_DIR + "EntityResolver.out"; + public void testResolver() throws Exception { + String outputFile = USER_DIR + "EntityResolver.out"; String goldFile = GOLDEN_DIR + "EntityResolverGF.out"; String xmlFile = XML_DIR + "publish.xml"; @@ -64,23 +61,8 @@ xmlReader.setEntityResolver(eResolver); InputSource is = new InputSource(instream); xmlReader.parse(is); - } catch(IOException | SAXException | ParserConfigurationException ex ) { - failUnexpected(ex); - } - // Need close the output file before we compare it with golden file. - try { - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + } + assertTrue(compareWithGold(goldFile, outputFile)); } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/SAXParserNSTableTest.java 2015-01-09 15:41:27.999103407 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/SAXParserNSTableTest.java 2015-01-09 15:41:27.916103278 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,20 +23,12 @@ package org.xml.sax.ptests; import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -44,91 +36,64 @@ * This class contains the testcases to test SAXParser with regard to * Namespace Table defined at http://www.megginson.com/SAX/Java/namespaces.html */ -public class SAXParserNSTableTest { +public class SAXParserNSTableTest extends JAXPFileBaseTest { /** * namespace processing is enabled. namespace-prefix is also is enabled. * So it is a True-True combination. - * The test is to test SAXParser with these conditions + * The test is to test SAXParser with these conditions. + * + * @throws Exception If any errors occur. */ @Test - public void testWithTrueTrue() { - String outputFile = CLASS_DIR + "SPNSTableTT.out"; + public void testWithTrueTrue() throws Exception { + String outputFile = USER_DIR + "SPNSTableTT.out"; String goldFile = GOLDEN_DIR + "NSTableTTGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setFeature("http://xml.org/sax/features/namespace-prefixes", - true); - - SAXParser saxParser = spf.newSAXParser(); - saxParser.parse(new File(xmlFile), new MyNSContentHandler(outputFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setFeature("http://xml.org/sax/features/namespace-prefixes", + true); + try (MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + spf.newSAXParser().parse(new File(xmlFile), handler); } + assertTrue(compareWithGold(goldFile, outputFile)); + } /** * namespace processing is enabled. Hence namespace-prefix is - * expected to be automaically off. So it is a True-False combination. - * The test is to test SAXParser with these conditions + * expected to be automatically off. So it is a True-False combination. + * The test is to test SAXParser with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithTrueFalse() { - String outputFile = CLASS_DIR + "SPNSTableTF.out"; + public void testWithTrueFalse() throws Exception { + String outputFile = USER_DIR + "SPNSTableTF.out"; String goldFile = GOLDEN_DIR + "NSTableTFGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - saxParser.parse(new File(xmlFile), new MyNSContentHandler(outputFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + try (MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + spf.newSAXParser().parse(new File(xmlFile), handler); } + assertTrue(compareWithGold(goldFile, outputFile)); } /** * namespace processing is not enabled. Hence namespace-prefix is - * expected to be automaically on. So it is a False-True combination. - * The test is to test SAXParser with these conditions + * expected to be automatically on. So it is a False-True combination. + * The test is to test SAXParser with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithFalseTrue() { - String outputFile = CLASS_DIR + "SPNSTableFT.out"; + public void testWithFalseTrue() throws Exception { + String outputFile = USER_DIR + "SPNSTableFT.out"; String goldFile = GOLDEN_DIR + "NSTableFTGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - saxParser.parse(new File(xmlFile), new MyNSContentHandler(outputFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + try (MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + spf.newSAXParser().parse(new File(xmlFile), handler); } + assertTrue(compareWithGold(goldFile, outputFile)); } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterCBTest.java 2015-01-09 15:41:28.357103965 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterCBTest.java 2015-01-09 15:41:28.283103850 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -26,14 +26,10 @@ import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.xml.sax.Attributes; import org.xml.sax.InputSource; @@ -42,7 +38,6 @@ import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -50,45 +45,34 @@ * Set parent of XMLFilter to XMLReader. Parsing on XML file will invoke XMLFilter * to write to output file. Test verifies output is same as the golden file. */ -public class XMLFilterCBTest { - public void testXMLFilterCB() { - String outputFile = CLASS_DIR + "XMLFilter.out"; +public class XMLFilterCBTest extends JAXPFileBaseTest { + /** + * Test XMLFilter working with XML reader. + * + * @throws Exception If any errors occur. + */ + public void testXMLFilterCB() throws Exception { + String outputFile = USER_DIR + "XMLFilter.out"; String goldFile = GOLDEN_DIR + "XMLFilterGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; - try (FileInputStream fis = new FileInputStream(xmlFile)){ + try (FileInputStream fis = new FileInputStream(xmlFile); + MyXMLFilter myXmlFilter = new MyXMLFilter(outputFile)){ SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - MyXMLFilter myXmlFilter = new MyXMLFilter(outputFile); myXmlFilter.setParent(xmlReader); - InputSource is = new InputSource(fis); - myXmlFilter.parse(is); - } catch( SAXException | IOException | ParserConfigurationException ex) { - failUnexpected(ex); + myXmlFilter.parse(new InputSource(fis)); } // Need close the output file before we compare it with golden file. - try { - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } + assertTrue(compareWithGold(goldFile, outputFile)); } } /** * Writer XMLFiler which write all tags to output file when event happens. */ -class MyXMLFilter extends XMLFilterImpl{ +class MyXMLFilter extends XMLFilterImpl implements AutoCloseable { /** * FileWriter to write string to output file. */ @@ -278,4 +262,14 @@ throw new SAXException(ex); } } + + /** + * Close writer handler. + * @throws IOException if any I/O error when close writer handler. + */ + @Override + public void close() throws IOException { + if (bWriter != null) + bWriter.close(); + } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterTest.java 2015-01-09 15:41:28.706104509 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLFilterTest.java 2015-01-09 15:41:28.629104389 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,18 +23,14 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -42,7 +38,7 @@ /** * Unit test for XMLFilter. */ -public class XMLFilterTest { +public class XMLFilterTest extends JAXPFileReadOnlyBaseTest { /** * name spaces constant. */ @@ -129,139 +125,114 @@ /** * By default true is expected get namespaces feature. - * @throws SAXException + * + * @throws Exception If any errors occur. */ @Test - public void getFeature01() throws SAXException { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlFilter.setParent(xmlReader); - assertTrue(xmlFilter.getFeature(NAMESPACES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void getFeature01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlFilter.setParent(xmlReader); + assertTrue(xmlFilter.getFeature(NAMESPACES)); } /** * By default false is expected get namespaces-prefix feature. + * + * @throws Exception If any errors occur. */ @Test - public void getFeature02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlFilter.setParent(xmlReader); - assertFalse(xmlFilter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void getFeature02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlFilter.setParent(spf.newSAXParser().getXMLReader()); + assertFalse(xmlFilter.getFeature(NAMESPACE_PREFIXES)); } /** * SAXNotRecognizedException is expected when get a feature by an invalid * feature name. - * @throws org.xml.sax.SAXNotRecognizedException If the feature - * value can't be assigned or retrieved from the parent. - * @throws org.xml.sax.SAXNotSupportedException When the - * parent recognizes the feature name but - * cannot determine its value at this time. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXNotRecognizedException.class) - public void getFeature03() throws SAXNotRecognizedException, - SAXNotSupportedException { + public void getFeature03() throws Exception { new XMLFilterImpl().getFeature("no-meaning-feature"); } /** * Set namespaces feature to a value to XMLFilter. it's expected same when * obtain it again. + * + * @throws Exception If any errors occur. */ @Test - public void setFeature01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlFilter.setParent(xmlReader); - xmlFilter.setFeature(NAMESPACES, false); - assertFalse(xmlFilter.getFeature(NAMESPACES)); - xmlFilter.setFeature(NAMESPACES, true); - assertTrue(xmlFilter.getFeature(NAMESPACES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void setFeature01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlFilter.setParent(spf.newSAXParser().getXMLReader()); + xmlFilter.setFeature(NAMESPACES, false); + assertFalse(xmlFilter.getFeature(NAMESPACES)); + xmlFilter.setFeature(NAMESPACES, true); + assertTrue(xmlFilter.getFeature(NAMESPACES)); } /** * Set namespaces-prefix feature to a value to XMLFilter. it's expected same * when obtain it again. + * + * @throws Exception If any errors occur. */ @Test - public void setFeature02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlFilter.setParent(xmlReader); - xmlFilter.setFeature(NAMESPACE_PREFIXES, false); - assertFalse(xmlFilter.getFeature(NAMESPACE_PREFIXES)); - xmlFilter.setFeature(NAMESPACE_PREFIXES, true); - assertTrue(xmlFilter.getFeature(NAMESPACE_PREFIXES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void setFeature02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlFilter.setParent(spf.newSAXParser().getXMLReader()); + xmlFilter.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(xmlFilter.getFeature(NAMESPACE_PREFIXES)); + xmlFilter.setFeature(NAMESPACE_PREFIXES, true); + assertTrue(xmlFilter.getFeature(NAMESPACE_PREFIXES)); } /** * NullPointerException is expected when parse a null InputSource. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = NullPointerException.class) - public void parse01() { - try { - new XMLFilterImpl().parse((InputSource)null); - } catch (IOException | SAXException ex) { - failUnexpected(ex); - } + public void parse01() throws Exception { + new XMLFilterImpl().parse((InputSource)null); } /** * SAXException is expected when parsing a invalid formatted XML file. - * @throws org.xml.sax.SAXException when parse a incorrect formatted XML - * file. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void parse02() throws SAXException { - XMLFilterImpl xmlFilter = new XMLFilterImpl(); + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void parse02() throws Exception { try(FileInputStream fis = new FileInputStream(XML_DIR + "invalid.xml")) { - InputSource is = new InputSource(fis); - xmlFilter.parse(is); - } catch (IOException ex) { - failUnexpected(ex); - } + new XMLFilterImpl().parse(new InputSource(fis)); + } } /** * No exception when parse a normal XML file. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = NullPointerException.class) - public void parse03() { - XMLFilterImpl xmlFilter = new XMLFilterImpl(); + @Test(groups = {"readLocalFiles"}, expectedExceptions = NullPointerException.class) + public void parse03() throws Exception { try(FileInputStream fis = new FileInputStream(XML_DIR + "correct2.xml")) { - InputSource is = new InputSource(fis); - xmlFilter.parse(is); - } catch (IOException | SAXException ex) { - failUnexpected(ex); + new XMLFilterImpl().parse(new InputSource(fis)); } } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderAdapterTest.java 2015-01-09 15:41:29.112105142 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderAdapterTest.java 2015-01-09 15:41:28.995104960 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,10 +23,9 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; +import java.io.FilePermission; import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; @@ -40,7 +39,7 @@ /** * Class containing the test cases for XMLReaderAdapter API */ -public class XMLReaderAdapterTest { +public class XMLReaderAdapterTest extends JAXPBaseTest { /** * http://xml.org/sax/features/namespace-prefixes property name. */ @@ -58,60 +57,51 @@ } /** - * To test the constructor that uses XMLReader + * To test the constructor that uses XMLReader. + * + * @throws Exception If any errors occur. */ @Test - public void constructor02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - assertNotNull(new XMLReaderAdapter(xmlReader)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void constructor02() throws Exception { + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + assertNotNull(new XMLReaderAdapter(xmlReader)); } /** * To test the parse method. The specification says that this method * will throw an exception if the embedded XMLReader does not support * the http://xml.org/sax/features/namespace-prefixes property. + * + * @throws Exception If any errors occur. */ @Test - public void nsfeature01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - if (!xmlReader.getFeature(NM_PREFIXES_PROPERTY)) { - xmlReader.setFeature(NM_PREFIXES_PROPERTY, true); - } - - assertTrue(xmlReader.getFeature(NM_PREFIXES_PROPERTY)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); + public void nsfeature01() throws Exception { + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + if (!xmlReader.getFeature(NM_PREFIXES_PROPERTY)) { + xmlReader.setFeature(NM_PREFIXES_PROPERTY, true); } + assertTrue(xmlReader.getFeature(NM_PREFIXES_PROPERTY)); } /** * To test the parse method. The specification says that this method * will throw an exception if the embedded XMLReader does not support * the http://xml.org/sax/features/namespace-prefixes property. + * + * @throws Exception If any errors occur. */ @Test - public void parse01() { + public void parse01() throws Exception { + setPermissions(new FilePermission(XML_DIR + "/-", "read")); try (FileInputStream fis = new FileInputStream(XML_DIR + "namespace1.xml")) { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); if (!xmlReader.getFeature(NM_PREFIXES_PROPERTY)) { xmlReader.setFeature(NM_PREFIXES_PROPERTY, true); } XMLReaderAdapter xmlRA = new XMLReaderAdapter(xmlReader); - - InputSource is = new InputSource(fis); xmlRA.setDocumentHandler(new HandlerBase()); - xmlRA.parse(is); - } catch (IOException | SAXException | ParserConfigurationException ex) { - failUnexpected(ex); + xmlRA.parse(new InputSource(fis)); } + setPermissions(); } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderFactoryTest.java 2015-01-09 15:41:29.478105713 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderFactoryTest.java 2015-01-09 15:41:29.400105591 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -22,6 +22,7 @@ */ package org.xml.sax.ptests; +import jaxp.library.JAXPBaseTest; import static org.testng.Assert.assertNotNull; import org.testng.annotations.Test; import org.xml.sax.SAXException; @@ -30,7 +31,7 @@ /** * Unit test for XMLReaderFactory.createXMLReader API. */ -public class XMLReaderFactoryTest { +public class XMLReaderFactoryTest extends JAXPBaseTest { /** * No exception expected when create XMLReader by default. * @throws org.xml.sax.SAXException when xml reader creation failed. @@ -48,12 +49,7 @@ */ @Test public void createReader02() throws SAXException { - //Disable this test because this is only work for apache implementation. - /*System.setProperty("org.xml.sax.driver", - "org.apache.xerces.parsers.SAXParser"); - assertNotNull(XMLReaderFactory. - createXMLReader("org.apache.xerces.parsers.SAXParser"));*/ - System.setProperty("org.xml.sax.driver", + setSystemProperty("org.xml.sax.driver", "com.sun.org.apache.xerces.internal.parsers.SAXParser"); assertNotNull(XMLReaderFactory. createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser")); --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderNSTableTest.java 2015-01-09 15:41:29.832106265 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderNSTableTest.java 2015-01-09 15:41:29.757106148 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,17 +23,14 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertTrue; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; import org.xml.sax.XMLReader; -import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR; import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR; import static org.xml.sax.ptests.SAXTestConst.XML_DIR; @@ -41,7 +38,7 @@ * Namespace Table defined at * http://www.megginson.com/SAX/Java/namespaces.html */ -public class XMLReaderNSTableTest { +public class XMLReaderNSTableTest extends JAXPFileBaseTest { /** * XML file that used to be parsed. */ @@ -55,71 +52,70 @@ /** * namespace processing is enabled. namespace-prefix is also is enabled. * So it is a True-True combination. - * The test is to test XMLReader with these conditions + * The test is to test XMLReader with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithTrueTrue() { - String outputFile = CLASS_DIR + "XRNSTableTT.out"; + public void testWithTrueTrue() throws Exception { + String outputFile = USER_DIR + "XRNSTableTT.out"; String goldFile = GOLDEN_DIR + "NSTableTTGF.out"; - - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - - XMLReader xmlReader = saxParser.getXMLReader(); - xmlReader.setFeature(NAMESPACE_PREFIXES, true); - - xmlReader.setContentHandler(new MyNSContentHandler(outputFile)); - xmlReader.parse(new InputSource(new FileInputStream(xmlFile))); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); + + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(NAMESPACE_PREFIXES, true); + + try (FileInputStream fis = new FileInputStream(xmlFile); + MyNSContentHandler handler = new MyNSContentHandler(outputFile);) { + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(fis)); } + assertTrue(compareWithGold(goldFile, outputFile)); } /** * Namespace processing is enabled. Hence namespace-prefix is - * expected to be automaically off. So it is a True-False combination. - * The test is to test XMLReader with these conditions + * expected to be automatically off. So it is a True-False combination. + * The test is to test XMLReader with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithTrueFalse() { - String outputFile = CLASS_DIR + "XRNSTableTF.out"; + public void testWithTrueFalse() throws Exception { + String outputFile = USER_DIR + "XRNSTableTF.out"; String goldFile = GOLDEN_DIR + "NSTableTFGF.out"; - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - XMLReader xmlReader = saxParser.getXMLReader(); - - xmlReader.setContentHandler(new MyNSContentHandler(outputFile)); - xmlReader.parse(new InputSource(new FileInputStream(xmlFile))); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser saxParser = spf.newSAXParser(); + XMLReader xmlReader = saxParser.getXMLReader(); + + try (FileInputStream fis = new FileInputStream(xmlFile); + MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(fis)); } + assertTrue(compareWithGold(goldFile, outputFile)); } /** * namespace processing is not enabled. Hence namespace-prefix is * expected to be automaically on. So it is a False-True combination. - * The test is to test XMLReader with these conditions + * The test is to test XMLReader with these conditions. + * + * @throws Exception If any errors occur. */ - public void testWithFalseTrue() { - String outputFile = CLASS_DIR + "XRNSTableFT.out"; + public void testWithFalseTrue()throws Exception { + String outputFile = USER_DIR + "XRNSTableFT.out"; String goldFile = GOLDEN_DIR + "NSTableFTGF.out"; - - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - XMLReader xmlReader = saxParser.getXMLReader(); - - xmlReader.setContentHandler(new MyNSContentHandler(outputFile)); - xmlReader.parse(new InputSource(new FileInputStream(xmlFile))); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException ex) { - failUnexpected(ex); - } + + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + try (FileInputStream fis = new FileInputStream(xmlFile); + MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { + xmlReader.setContentHandler(handler); + xmlReader.parse(new InputSource(fis)); + } + assertTrue(compareWithGold(goldFile, outputFile)); } } --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderTest.java 2015-01-09 15:41:30.183106812 -0800 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/XMLReaderTest.java 2015-01-09 15:41:30.107106693 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,10 +23,9 @@ package org.xml.sax.ptests; import java.io.FileInputStream; -import java.io.IOException; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; +import jaxp.library.JAXPFileReadOnlyBaseTest; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; @@ -45,42 +44,43 @@ /** * Class containing the test cases for SAXParser API */ -public class XMLReaderTest { +public class XMLReaderTest extends JAXPFileReadOnlyBaseTest { + /** * XML namespaces. */ - private static final String NAMESPACES = - "http://xml.org/sax/features/namespaces"; + private static final String NAMESPACES + = "http://xml.org/sax/features/namespaces"; /** * XML namespaces prefixes. */ - private static final String NAMESPACE_PREFIXES = - "http://xml.org/sax/features/namespace-prefixes"; + private static final String NAMESPACE_PREFIXES + = "http://xml.org/sax/features/namespace-prefixes"; /** * A string intern name. */ - private static final String STRING_INTERNING = - "http://xml.org/sax/features/string-interning"; + private static final String STRING_INTERNING + = "http://xml.org/sax/features/string-interning"; /** * Validation name. */ - private static final String VALIDATION = - "http://xml.org/sax/features/validation"; + private static final String VALIDATION + = "http://xml.org/sax/features/validation"; /** * A general external entities name */ - private static final String EXTERNAL_G_ENTITIES = - "http://xml.org/sax/features/external-general-entities"; + private static final String EXTERNAL_G_ENTITIES + = "http://xml.org/sax/features/external-general-entities"; /** * A external parameter entities name */ - private static final String EXTERNAL_P_ENTITIES = - "http://xml.org/sax/features/external-parameter-entities"; + private static final String EXTERNAL_P_ENTITIES + = "http://xml.org/sax/features/external-parameter-entities"; /** * XML DOM node name. @@ -95,526 +95,444 @@ /** * Declare handler name */ - private static final String DECL_HANDLER = - "http://xml.org/sax/properties/declaration-handler"; + private static final String DECL_HANDLER + = "http://xml.org/sax/properties/declaration-handler"; /** * Lexical handler name */ - private static final String LEXICAL_HANDLER = - "http://xml.org/sax/properties/lexical-handler"; + private static final String LEXICAL_HANDLER + = "http://xml.org/sax/properties/lexical-handler"; /** * According to the SAX2 specs, All XMLReaders are required to recognize the - * http://xml.org/sax/features/namespaces feature names. - * This test case is to test this. + * http://xml.org/sax/features/namespaces feature names. This test case is + * to test this. + * + * @throws Exception If any errors occur. */ @Test - public void featureNS01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertFalse(xmlReader.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNS01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertFalse(xmlReader.getFeature(NAMESPACES)); } /** * According to the SAX2 specs, All XMLReaders are required to recognize the - * http://xml.org/sax/features/namespaces feature names. - * This test case is to test this. + * http://xml.org/sax/features/namespaces feature names. This test case is + * to test this. + * + * @throws Exception If any errors occur. */ @Test - public void featureNS02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNS02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(NAMESPACES)); } /** * Obtain http://xml.org/sax/features/namespaces feature name after it's * just set. Expect it's same as set value. + * + * @throws Exception If any errors occur. */ @Test - public void featureNS03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setFeature(NAMESPACES, true); - assertTrue(xmlReader.getFeature(NAMESPACES)); - xmlReader.setFeature(NAMESPACES, false); - assertFalse(xmlReader.getFeature(NAMESPACES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNS03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(NAMESPACES, true); + assertTrue(xmlReader.getFeature(NAMESPACES)); + xmlReader.setFeature(NAMESPACES, false); + assertFalse(xmlReader.getFeature(NAMESPACES)); } /** * According to the SAX2 specs, All XMLReaders are required to recognize the - * http://xml.org/sax/features/namespace-prefixes feature names. - * This test case is to test this. + * http://xml.org/sax/features/namespace-prefixes feature names. This test + * case is to test this. + * + * @throws Exception If any errors occur. */ @Test - public void featureNSP01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); - - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNSP01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); } /** * According to the SAX2 specs, All XMLReaders are required to recognize the - * http://xml.org/sax/features/namespace-prefixes feature names. - * This test case is to test this. + * http://xml.org/sax/features/namespace-prefixes feature names. This test + * case is to test this. + * + * @throws Exception If any errors occur. */ @Test - public void featureNSP02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNSP02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); } /** * Obtain http://xml.org/sax/features/namespaces-prefixes feature name after * it's just set. Expect it's same as set value. + * + * @throws Exception If any errors occur. */ @Test - public void featureNSP03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setFeature(NAMESPACE_PREFIXES, true); - assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); - xmlReader.setFeature(NAMESPACE_PREFIXES, false); - assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } + public void featureNSP03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(NAMESPACE_PREFIXES, true); + assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); + xmlReader.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); } /** * getFeature returns true if a feature has not been preset when namespace * awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureSI01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(STRING_INTERNING)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureSI01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(STRING_INTERNING)); } /** * getFeature with validation feature name returns the value that * setValidation set. + * + * @throws Exception If any errors occur. */ @Test - public void featureV01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertFalse(spf.newSAXParser().getXMLReader().getFeature(VALIDATION)); - spf.setValidating(true); - assertTrue(spf.newSAXParser().getXMLReader().getFeature(VALIDATION)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureV01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertFalse(spf.newSAXParser().getXMLReader().getFeature(VALIDATION)); + spf.setValidating(true); + assertTrue(spf.newSAXParser().getXMLReader().getFeature(VALIDATION)); } /** - * getFeature returns the value that a feature has been preset as when + * getFeature returns the value that a feature has been preset as when * namespace awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureV02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - - xmlReader.setFeature(VALIDATION, true); - assertTrue(xmlReader.getFeature(VALIDATION)); - - xmlReader.setFeature(VALIDATION, false); - assertFalse(xmlReader.getFeature(VALIDATION)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureV02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + + xmlReader.setFeature(VALIDATION, true); + assertTrue(xmlReader.getFeature(VALIDATION)); + xmlReader.setFeature(VALIDATION, false); + assertFalse(xmlReader.getFeature(VALIDATION)); } /** * getFeature returns true if a feature has not been preset when namespace * awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureEGE01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(EXTERNAL_G_ENTITIES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureEGE01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(EXTERNAL_G_ENTITIES)); } /** - * getFeature returns false if a feature has been preset as false when + * getFeature returns false if a feature has been preset as false when * namespace awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureEGE02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setFeature(EXTERNAL_G_ENTITIES, false); - assertFalse(xmlReader.getFeature(EXTERNAL_G_ENTITIES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureEGE02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(EXTERNAL_G_ENTITIES, false); + assertFalse(xmlReader.getFeature(EXTERNAL_G_ENTITIES)); } /** * getFeature returns true if a feature has not been preset when namespace * awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureEPE01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertTrue(xmlReader.getFeature(EXTERNAL_P_ENTITIES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureEPE01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(EXTERNAL_P_ENTITIES)); } /** - * getFeature returns false if a feature has been preset as false when + * getFeature returns false if a feature has been preset as false when * namespace awareness is set. + * + * @throws Exception If any errors occur. */ @Test - public void featureEPE02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setFeature(EXTERNAL_P_ENTITIES, false); - assertFalse(xmlReader.getFeature(EXTERNAL_P_ENTITIES)); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureEPE02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setFeature(EXTERNAL_P_ENTITIES, false); + assertFalse(xmlReader.getFeature(EXTERNAL_P_ENTITIES)); } /** * getFeature with a unknown feature name throws SAXNotRecognizedException. - * @throws SAXNotRecognizedException If the feature value can't be assigned - * or retrieved. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXNotRecognizedException.class) - public void featureNE01() throws SAXNotRecognizedException { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - boolean noMeaningFeature = xmlReader.getFeature("no-meaning-feature"); - } catch(SAXNotRecognizedException ex) { - throw ex; - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void featureNE01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().getFeature("no-meaning-feature"); } /** * No exception expected when set entity resolver as simple entity resolver. + * + * @throws Exception If any errors occur. */ @Test - public void entity01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlReader.setEntityResolver(xmlFilter); - assertNotNull(xmlReader.getEntityResolver()); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void entity01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlReader.setEntityResolver(xmlFilter); + assertEquals(xmlReader.getEntityResolver(), xmlFilter); } /** * No NPE expected when set entity resolver as null. + * + * @throws Exception If any errors occur. */ @Test - public void entity02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setEntityResolver(null); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void entity02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().setEntityResolver(null); } /** * No exception expected when set DTD handler as simple DTD handler. + * + * @throws Exception If any errors occur. */ @Test - public void dtdhandler01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlReader.setDTDHandler(xmlFilter); - assertNotNull(xmlReader.getDTDHandler()); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void dtdhandler01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlReader.setDTDHandler(xmlFilter); + assertEquals(xmlReader.getDTDHandler(), xmlFilter); } /** * No NPE expected when set DTD handler as null. + * + * @throws Exception If any errors occur. */ @Test - public void dtdhandler02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setDTDHandler(null); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void dtdhandler02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().setDTDHandler(null); } /** * No exception expected when set content handler as simple content handler. + * + * @throws Exception If any errors occur. */ @Test - public void contenthandler01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - XMLFilterImpl xmlFilter = new XMLFilterImpl(); - xmlReader.setContentHandler(xmlFilter); - assertNotNull(xmlReader.getContentHandler()); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void contenthandler01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + XMLFilterImpl xmlFilter = new XMLFilterImpl(); + xmlReader.setContentHandler(xmlFilter); + assertEquals(xmlReader.getContentHandler(), xmlFilter); } /** * No NPE expected when set content handler as null. + * + * @throws Exception If any errors occur. */ @Test - public void contenthandler02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setContentHandler(null); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void contenthandler02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().setContentHandler(null); } /** * No exception expected when set content handler as simple error handler. + * + * @throws Exception If any errors occur. */ @Test - public void errorhandler01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setErrorHandler(new XMLFilterImpl()); - assertNotNull(xmlReader.getErrorHandler()); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void errorhandler01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setErrorHandler(new XMLFilterImpl()); + assertNotNull(xmlReader.getErrorHandler()); } /** * No NPE expected when set error handler as null. + * + * @throws Exception If any errors occur. */ @Test - public void errorhandler02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.setErrorHandler(null); - } catch (SAXException | ParserConfigurationException ex) { - failUnexpected(ex); - } + public void errorhandler02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.setErrorHandler(null); } /** * Parse a null input source throw NPE. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = NullPointerException.class) - public void parse01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.parse((InputSource)null); - } catch (SAXException | ParserConfigurationException | IOException ex) { - failUnexpected(ex); - } + public void parse01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.newSAXParser().getXMLReader().parse((InputSource) null); } /** * Unit test for parse a error-formatted file. SAXException is expected. - * @throws org.xml.sax.SAXException parsing failed. + * + * @throws Exception If any errors occur. */ - @Test(expectedExceptions = SAXException.class) - public void parse02() throws SAXException { - try (FileInputStream fis = new FileInputStream(XML_DIR + "invalid.xml")){ + @Test(groups = {"readLocalFiles"}, expectedExceptions = SAXException.class) + public void parse02() throws Exception { + try (FileInputStream fis = new FileInputStream(XML_DIR + "invalid.xml")) { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - InputSource is = new InputSource(fis); - xmlReader.parse(is); - } catch (ParserConfigurationException | IOException ex) { - failUnexpected(ex); + spf.newSAXParser().getXMLReader().parse(new InputSource(fis)); } } /** * Unit test for parse a well-formatted file. No exception is expected. + * + * @throws Exception If any errors occur. */ - @Test - public void parse03(){ + @Test(groups = {"readLocalFiles"}) + public void parse03() throws Exception { try (FileInputStream fis = new FileInputStream(XML_DIR + "correct2.xml")) { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - InputSource is = new InputSource(fis); - xmlReader.parse(is); - } catch (IOException | SAXException | ParserConfigurationException ex) { - failUnexpected(ex); + spf.newSAXParser().getXMLReader().parse(new InputSource(fis)); } } /** - * Modified by IBM - * Xerces does not support this feature and it is not mandatory - * @throws org.xml.sax.SAXNotSupportedException + * Modified by IBM Xerces does not support this feature and it is not + * mandatory. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXNotSupportedException.class) - public void xrProperty01() throws SAXNotSupportedException { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - xmlReader.getProperty(XML_STRING); - } catch(SAXNotSupportedException ex) { - throw ex; - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + xmlReader.getProperty(XML_STRING); } /** * SAXNotSupportedException thrown if property name is known but no value * assigned to this property. - * @throws org.xml.sax.SAXNotSupportedException when XMLReader recognizes - * the property name but cannot determine its value at this time. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXNotSupportedException.class) - public void xrProperty02() throws SAXNotSupportedException { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertNull(xmlReader.getProperty(DOM_NODE)); - } catch (SAXNotSupportedException ex) { - throw ex; - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertNull(xmlReader.getProperty(DOM_NODE)); } - /** * XMLReader.getProperty returns null if LEXICAL_HANDLER wasn't set. + * + * @throws Exception If any errors occur. */ @Test - public void xrProperty03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertNull(xmlReader.getProperty(LEXICAL_HANDLER)); - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertNull(xmlReader.getProperty(LEXICAL_HANDLER)); } /** * XMLReader.getProperty returns null if DECL_HANDLER wasn't set. + * + * @throws Exception If any errors occur. */ @Test - public void xrProperty04() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - assertNull(xmlReader.getProperty(DECL_HANDLER)); - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty04() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertNull(xmlReader.getProperty(DECL_HANDLER)); } /** * XMLReader.setProperty/getProperty for LEXICAL_HANDLER unit test. + * + * @throws Exception If any errors occur. */ @Test - public void xrProperty05() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - MyLexicalHandler myLexicalHandler = new MyLexicalHandler(); - xmlReader.setProperty(LEXICAL_HANDLER, myLexicalHandler); - assertNotNull(xmlReader.getProperty(LEXICAL_HANDLER)); - } catch (SAXException | ParserConfigurationException ex){ - failUnexpected(ex); - } + public void xrProperty05() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + MyLexicalHandler myLexicalHandler = new MyLexicalHandler(); + xmlReader.setProperty(LEXICAL_HANDLER, myLexicalHandler); + assertNotNull(xmlReader.getProperty(LEXICAL_HANDLER)); } /** * XMLReader.setProperty/getProperty for DECL_HANDLER unit test. + * + * @throws Exception If any errors occur. */ @Test - public void xrProperty06() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - XMLReader xmlReader = spf.newSAXParser().getXMLReader(); - MyDeclHandler myDeclHandler = new MyDeclHandler(); - xmlReader.setProperty(DECL_HANDLER, myDeclHandler); - assertNotNull(xmlReader.getProperty(DECL_HANDLER)); - } catch (ParserConfigurationException | SAXException ex){ - failUnexpected(ex); - } + public void xrProperty06() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + MyDeclHandler myDeclHandler = new MyDeclHandler(); + xmlReader.setProperty(DECL_HANDLER, myDeclHandler); + assertNotNull(xmlReader.getProperty(DECL_HANDLER)); } } @@ -622,6 +540,7 @@ * Simple LexicalHandler that skips every lexical event. */ class MyLexicalHandler implements LexicalHandler { + /** * Report an XML comment anywhere in the document. * @@ -667,8 +586,10 @@ * Report the start of DTD declarations, if any. * * @param name The document type name. - * @param publicId The declared public identifier for the external DTD subset. - * @param systemId The declared system identifier for the external DTD subset. + * @param publicId The declared public identifier for the external DTD + * subset. + * @param systemId The declared system identifier for the external DTD + * subset. */ @Override public void startDTD(String name, String publicId, String systemId) { @@ -688,16 +609,17 @@ * Simple DeclHandler that skips every DTD declaration event. */ class MyDeclHandler implements DeclHandler { + /** * Report an attribute type declaration. + * * @param eName The name of the associated element. * @param aName The name of the attribute. * @param type A string representing the attribute type. * @param mode A string representing the attribute defaulting mode - * ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if - * none of these applies. - * @param value A string representing the attribute's default value, - * or null if there is none. + * ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if none of these applies. + * @param value A string representing the attribute's default value, or null + * if there is none. */ @Override public void attributeDecl(String eName, String aName, String type, @@ -706,6 +628,7 @@ /** * Report an element type declaration. + * * @param name The element type name. * @param model The content model as a normalized string. */ @@ -715,10 +638,11 @@ /** * Report a parsed external entity declaration. - * @param name The name of the entity. If it is a parameter - * entity, the name will begin with '%'. - * @param publicId The entity's public identifier, or null if none - * was given. + * + * @param name The name of the entity. If it is a parameter entity, the name + * will begin with '%'. + * @param publicId The entity's public identifier, or null if none was + * given. * @param systemId The entity's system identifier. */ @Override @@ -728,8 +652,9 @@ /** * Report an internal entity declaration. - * @param name The name of the entity. If it is a parameter - * entity, the name will begin with '%'. + * + * @param name The name of the entity. If it is a parameter entity, the name + * will begin with '%'. * @param value The replacement text of the entity. */ @Override --- old/test/javax/xml/jaxp/functional/test/auctionportal/AuctionController.java 2015-01-09 15:41:30.544107375 -0800 +++ new/test/javax/xml/jaxp/functional/test/auctionportal/AuctionController.java 2015-01-09 15:41:30.467107255 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -27,23 +27,18 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; - import java.io.File; import java.io.FileInputStream; -import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.nio.file.Paths; import java.util.GregorianCalendar; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; - -import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.dom.DOMResult; @@ -51,8 +46,8 @@ import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; +import jaxp.library.JAXPFileReadOnlyBaseTest; import static jaxp.library.JAXPTestUtilities.bomStream; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import org.testng.annotations.Test; import org.w3c.dom.Attr; import org.w3c.dom.DOMConfiguration; @@ -63,173 +58,160 @@ import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; -import org.xml.sax.SAXException; import static test.auctionportal.HiBidConstants.PORTAL_ACCOUNT_NS; import static test.auctionportal.HiBidConstants.XML_DIR; /** * This is the user controller class for the Auction portal HiBid.com. */ -public class AuctionController { +public class AuctionController extends JAXPFileReadOnlyBaseTest { /** * Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927 * DOMConfiguration.setParameter("well-formed",true) throws an exception. + * + * @throws Exception If any errors occur. */ - @Test - public void testCreateNewItem2Sell() { + @Test(groups = {"readLocalFiles"}) + public void testCreateNewItem2Sell() throws Exception { String xmlFile = XML_DIR + "novelsInvalid.xml"; - try { - Document document = DocumentBuilderFactory.newInstance() - .newDocumentBuilder().parse(xmlFile); - - document.getDomConfig().setParameter("well-formed", true); - - DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); - DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); - MyDOMOutput domOutput = new MyDOMOutput(); - domOutput.setByteStream(System.out); - LSSerializer writer = impl.createLSSerializer(); - writer.write(document, domOutput); - } catch (ParserConfigurationException | SAXException | IOException - | ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException e) { - failUnexpected(e); - } + Document document = DocumentBuilderFactory.newInstance() + .newDocumentBuilder().parse(xmlFile); + + document.getDomConfig().setParameter("well-formed", true); + + DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); + DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + MyDOMOutput domOutput = new MyDOMOutput(); + domOutput.setByteStream(System.out); + LSSerializer writer = impl.createLSSerializer(); + writer.write(document, domOutput); } /** * Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132 * test throws DOM Level 1 node error. + * + * @throws Exception If any errors occur. */ - @Test - public void testCreateNewItem2SellRetry() { + @Test(groups = {"readLocalFiles"}) + public void testCreateNewItem2SellRetry() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - Document document = dbf.newDocumentBuilder().parse(xmlFile); - - DOMConfiguration domConfig = document.getDomConfig(); - MyDOMErrorHandler errHandler = new MyDOMErrorHandler(); - domConfig.setParameter("error-handler", errHandler); - - DOMImplementationLS impl = - (DOMImplementationLS) DOMImplementationRegistry.newInstance() - .getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); - MyDOMOutput domoutput = new MyDOMOutput(); - - domoutput.setByteStream(System.out); - writer.write(document, domoutput); - - document.normalizeDocument(); - writer.write(document, domoutput); - assertFalse(errHandler.isError()); - } catch (ParserConfigurationException | SAXException | IOException - | ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException e) { - failUnexpected(e); - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + Document document = dbf.newDocumentBuilder().parse(xmlFile); + + DOMConfiguration domConfig = document.getDomConfig(); + MyDOMErrorHandler errHandler = new MyDOMErrorHandler(); + domConfig.setParameter("error-handler", errHandler); + + DOMImplementationLS impl = + (DOMImplementationLS) DOMImplementationRegistry.newInstance() + .getDOMImplementation("LS"); + LSSerializer writer = impl.createLSSerializer(); + MyDOMOutput domoutput = new MyDOMOutput(); + + domoutput.setByteStream(System.out); + writer.write(document, domoutput); + + document.normalizeDocument(); + writer.write(document, domoutput); + assertFalse(errHandler.isError()); } /** * Check if setting the attribute to be of type ID works. This will affect * the Attr.isID method according to the spec. + * + * @throws Exception If any errors occur. */ - @Test - public void testCreateID() { + @Test(groups = {"readLocalFiles"}) + public void testCreateID() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); - Document document = dbf.newDocumentBuilder().parse(xmlFile); - Element account = (Element)document - .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); - - account.setIdAttributeNS(PORTAL_ACCOUNT_NS, "accountID", true); - Attr aID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); - assertTrue(aID.isId()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + Document document = dbf.newDocumentBuilder().parse(xmlFile); + Element account = (Element)document + .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); + + account.setIdAttributeNS(PORTAL_ACCOUNT_NS, "accountID", true); + Attr aID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); + assertTrue(aID.isId()); } /** * Check the user data on the node. + * + * @throws Exception If any errors occur. */ - @Test - public void testCheckingUserData() { + @Test(groups = {"readLocalFiles"}) + public void testCheckingUserData() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(xmlFile); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document document = docBuilder.parse(xmlFile); - Element account = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); - assertEquals(account.getNodeName(), "acc:Account"); - Element firstName = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); - assertEquals(firstName.getNodeName(), "FirstName"); - - Document doc1 = docBuilder.newDocument(); - Element someName = doc1.createElement("newelem"); - - someName.setUserData("mykey", "dd", - (operation, key, data, src, dst) -> { - System.err.println("In UserDataHandler" + key); - System.out.println("In UserDataHandler"); - }); - Element impAccount = (Element)document.importNode(someName, true); - assertEquals(impAccount.getNodeName(), "newelem"); - document.normalizeDocument(); - String data = (someName.getUserData("mykey")).toString(); - assertEquals(data, "dd"); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + Element account = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); + assertEquals(account.getNodeName(), "acc:Account"); + Element firstName = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); + assertEquals(firstName.getNodeName(), "FirstName"); + + Document doc1 = docBuilder.newDocument(); + Element someName = doc1.createElement("newelem"); + + someName.setUserData("mykey", "dd", + (operation, key, data, src, dst) -> { + System.err.println("In UserDataHandler" + key); + System.out.println("In UserDataHandler"); + }); + Element impAccount = (Element)document.importNode(someName, true); + assertEquals(impAccount.getNodeName(), "newelem"); + document.normalizeDocument(); + String data = (someName.getUserData("mykey")).toString(); + assertEquals(data, "dd"); } /** * Check the UTF-16 XMLEncoding xml file. + * + * @throws Exception If any errors occur. * @see movies.xml */ - @Test - public void testCheckingEncoding() { + @Test(groups = {"readLocalFiles"}) + public void testCheckingEncoding() throws Exception { // Note since movies.xml is UTF-16 encoding. We're not using stanard XML // file suffix. String xmlFile = XML_DIR + "movies.xml.data"; - //try (FileInputStream is = new FileInputStream(xmlFile)) { - try { + try (InputStream source = bomStream("UTF-16", xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - InputStream source = bomStream("UTF-16", xmlFile); Document document = dbf.newDocumentBuilder().parse(source); assertEquals(document.getXmlEncoding(), "UTF-16"); assertEquals(document.getXmlStandalone(), true); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); } } /** * Check validation API features. A schema which is including in Bug 4909119 * used to be testing for the functionalities. + * + * @throws Exception If any errors occur. * @see userDetails.xsd */ - @Test - public void testGetOwnerInfo() { + @Test(groups = {"readLocalFiles"}) + public void testGetOwnerInfo() throws Exception { String schemaFile = XML_DIR + "userDetails.xsd"; String xmlFile = XML_DIR + "userDetails.xml"; - - try { + + try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); @@ -244,27 +226,27 @@ DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(eh); - Document document = docBuilder.parse(new FileInputStream(xmlFile)); + Document document = docBuilder.parse(fis); DOMResult dResult = new DOMResult(); DOMSource domSource = new DOMSource(document); validator.validate(domSource, dResult); assertFalse(eh.isAnyError()); - } catch (SAXException | ParserConfigurationException | IOException e) { - failUnexpected(e); } } /** * Check grammar caching with imported schemas. + * + * @throws Exception If any errors occur. * @see coins.xsd * @see coinsImportMe.xsd */ - @Test - public void testGetOwnerItemList() { + @Test(groups = {"readLocalFiles"}) + public void testGetOwnerItemList() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; - try { + try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); @@ -278,11 +260,9 @@ validator.setErrorHandler(eh); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new FileInputStream(xmlFile)); + Document document = docBuilder.parse(fis); validator.validate(new DOMSource(document), new DOMResult()); assertFalse(eh.isAnyError()); - } catch (SAXException | ParserConfigurationException | IOException e) { - failUnexpected(e); } } @@ -291,96 +271,88 @@ * Check for the same imported schemas but will use SAXParserFactory and try * parsing using the SAXParser. SCHEMA_SOURCE attribute is using for this * test. + * + * @throws Exception If any errors occur. * @see coins.xsd * @see coinsImportMe.xsd */ - @Test - public void testGetOwnerItemList1() { + @Test(groups = {"readLocalFiles"}) + public void testGetOwnerItemList1() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; - - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setValidating(true); - - SAXParser sp = spf.newSAXParser(); - sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile); - - MyErrorHandler eh = new MyErrorHandler(); - sp.parse(new File(xmlFile), eh); - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setValidating(true); + + SAXParser sp = spf.newSAXParser(); + sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile); + + MyErrorHandler eh = new MyErrorHandler(); + sp.parse(new File(xmlFile), eh); + assertFalse(eh.isAnyError()); } /** * Check usage of javax.xml.datatype.Duration class. + * + * @throws Exception If any errors occur. */ - @Test - public void testGetItemDuration() { + @Test(groups = {"readLocalFiles"}) + public void testGetItemDuration() throws Exception { String xmlFile = XML_DIR + "itemsDuration.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - Document document = dbf.newDocumentBuilder().parse(xmlFile); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + Document document = dbf.newDocumentBuilder().parse(xmlFile); - Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0); + Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0); - NodeList childList = durationElement.getChildNodes(); + NodeList childList = durationElement.getChildNodes(); - for (int i = 0; i < childList.getLength(); i++) { - System.out.println("child " + i + childList.item(i)); - } - - Duration duration = DatatypeFactory.newInstance().newDuration("P365D"); - Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue()); - assertFalse(sellDuration.isShorterThan(duration)); - assertFalse(sellDuration.isLongerThan(duration)); - assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365)); - assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration); - - Duration myDuration = sellDuration.add(duration); - assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)), - DatatypeFactory.newInstance().newDuration("P730D")); - } catch (ParserConfigurationException | DatatypeConfigurationException - | SAXException | IOException e) { - failUnexpected(e); + for (int i = 0; i < childList.getLength(); i++) { + System.out.println("child " + i + childList.item(i)); } + + Duration duration = DatatypeFactory.newInstance().newDuration("P365D"); + Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue()); + assertFalse(sellDuration.isShorterThan(duration)); + assertFalse(sellDuration.isLongerThan(duration)); + assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365)); + assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration); + + Duration myDuration = sellDuration.add(duration); + assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)), + DatatypeFactory.newInstance().newDuration("P730D")); } /** * Check usage of TypeInfo interface introduced in DOM L3. + * + * @throws Exception If any errors occur. */ - @Test - public void testGetTypeInfo() { + @Test(groups = {"readLocalFiles"}) + public void testGetTypeInfo() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(true); - dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - docBuilder.setErrorHandler(new MyErrorHandler()); - - Document document = docBuilder.parse(xmlFile); - Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0); - TypeInfo typeInfo = userId.getSchemaTypeInfo(); - assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger")); - assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI)); - - Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0); - TypeInfo roletypeInfo = role.getSchemaTypeInfo(); - assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell")); - assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS)); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(true); + dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + docBuilder.setErrorHandler(new MyErrorHandler()); + + Document document = docBuilder.parse(xmlFile); + Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0); + TypeInfo typeInfo = userId.getSchemaTypeInfo(); + assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger")); + assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI)); + + Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0); + TypeInfo roletypeInfo = role.getSchemaTypeInfo(); + assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell")); + assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS)); } } --- old/test/javax/xml/jaxp/functional/test/auctionportal/AuctionItemRepository.java 2015-01-09 15:41:30.905107937 -0800 +++ new/test/javax/xml/jaxp/functional/test/auctionportal/AuctionItemRepository.java 2015-01-09 15:41:30.828107817 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -30,39 +30,31 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.IOException; +import java.io.FilePermission; import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; -import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareDocumentWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertFalse; - import org.testng.annotations.Test; import org.w3c.dom.Document; -import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; -import static test.auctionportal.HiBidConstants.CLASS_DIR; import static test.auctionportal.HiBidConstants.GOLDEN_DIR; import static test.auctionportal.HiBidConstants.XML_DIR; /** * This is a test class for the Auction portal HiBid.com. */ -public class AuctionItemRepository { +public class AuctionItemRepository extends JAXPFileBaseTest { /** * XML file for parsing. */ @@ -78,94 +70,92 @@ * document that has more than two levels of entity expansion is parsed or * not. Previous system property was changed to jdk.xml.entityExpansionLimit * see http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html. + * + * @throws Exception If any errors occur. */ @Test - public void testEntityExpansionSAXPos() { - try { - SAXParserFactory factory = SAXParserFactory.newInstance(); - // Secure processing will limit XML processing to conform to - // implementation limits. - factory.setFeature(FEATURE_SECURE_PROCESSING, true); - // Set entityExpansionLimit as 2 should expect fatalError - System.setProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(128000)); - SAXParser parser = factory.newSAXParser(); - - MyErrorHandler fatalHandler = new MyErrorHandler(); - parser.parse(new File(ENTITY_XML), fatalHandler); - assertFalse(fatalHandler.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + public void testEntityExpansionSAXPos() throws Exception { + SAXParserFactory factory = SAXParserFactory.newInstance(); + // Secure processing will limit XML processing to conform to + // implementation limits. + factory.setFeature(FEATURE_SECURE_PROCESSING, true); + // Set entityExpansionLimit as 2 should expect fatalError + setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(128000)); + SAXParser parser = factory.newSAXParser(); + + MyErrorHandler fatalHandler = new MyErrorHandler(); + setPermissions(new FilePermission(ENTITY_XML, "read")); + parser.parse(new File(ENTITY_XML), fatalHandler); + assertFalse(fatalHandler.isAnyError()); } /** * Setting the EntityExpansion Limit to 2 and checks if the XML * document that has more than two levels of entity expansion is parsed or * not. Previous system property was changed to jdk.xml.entityExpansionLimit * see http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXParseException.class) - public void testEntityExpansionSAXNeg() throws SAXParseException { - // - try { - SAXParserFactory factory = SAXParserFactory.newInstance(); - // Secure processing will limit XML processing to conform to - // implementation limits. - factory.setFeature(FEATURE_SECURE_PROCESSING, true); - // Set entityExpansionLimit as 2 should expect SAXParseException - System.setProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2)); - SAXParser parser = factory.newSAXParser(); - - MyErrorHandler fatalHandler = new MyErrorHandler(); - parser.parse(new File(ENTITY_XML), fatalHandler); - } catch (SAXParseException e) { - throw e; - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + public void testEntityExpansionSAXNeg() throws Exception { + SAXParserFactory factory = SAXParserFactory.newInstance(); + // Secure processing will limit XML processing to conform to + // implementation limits. + factory.setFeature(FEATURE_SECURE_PROCESSING, true); + // Set entityExpansionLimit as 2 should expect SAXParseException. + setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2)); + + SAXParser parser = factory.newSAXParser(); + MyErrorHandler fatalHandler = new MyErrorHandler(); + setPermissions(new FilePermission(ENTITY_XML, "read")); + parser.parse(new File(ENTITY_XML), fatalHandler); } /** * Testing set MaxOccursLimit to 10000 in the secure processing enabled for * SAXParserFactory. + * + * @throws Exception If any errors occur. */ @Test - public void testMaxOccurLimitPos() { + public void testMaxOccurLimitPos() throws Exception { String schema_file = XML_DIR + "toys.xsd"; String xml_file = XML_DIR + "toys.xml"; - + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setValidating(true); + factory.setFeature(FEATURE_SECURE_PROCESSING, true); + setSystemProperty(SP_MAX_OCCUR_LIMIT, String.valueOf(10000)); + SAXParser parser = factory.newSAXParser(); + parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + setPermissions(new FilePermission(XML_DIR + "-", "read")); + parser.setProperty(JAXP_SCHEMA_SOURCE, new File(schema_file)); try (InputStream is = new FileInputStream(xml_file)) { - SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setValidating(true); - factory.setFeature(FEATURE_SECURE_PROCESSING, true); - System.setProperty(SP_MAX_OCCUR_LIMIT, String.valueOf(10000)); - SAXParser parser = factory.newSAXParser(); - parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - parser.setProperty(JAXP_SCHEMA_SOURCE, new File(schema_file)); MyErrorHandler eh = new MyErrorHandler(); parser.parse(is, eh); assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); } } /** * Use a DocumentBuilder to create a DOM object and see if Secure Processing * feature affects the entity expansion. + * + * @throws Exception If any errors occur. */ @Test - public void testEntityExpansionDOMPos() { + public void testEntityExpansionDOMPos() throws Exception { + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(FEATURE_SECURE_PROCESSING, true); + setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(10000)); + DocumentBuilder dBuilder = dfactory.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + dBuilder.setErrorHandler(eh); try { - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setFeature(FEATURE_SECURE_PROCESSING, true); - System.setProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(10000)); - DocumentBuilder dBuilder = dfactory.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - dBuilder.setErrorHandler(eh); + setPermissions(new FilePermission(ENTITY_XML, "read")); dBuilder.parse(ENTITY_XML); assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); + } finally { + setPermissions(); } } @@ -173,310 +163,209 @@ * Use a DocumentBuilder to create a DOM object and see how does the Secure * Processing feature and entityExpansionLimit value affects output. * Negative test that when entityExpansionLimit is too small. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXParseException.class) - public void testEntityExpansionDOMNeg() throws SAXParseException { - try { - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setFeature(FEATURE_SECURE_PROCESSING, true); - System.setProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2)); - DocumentBuilder dBuilder = dfactory.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - dBuilder.setErrorHandler(eh); - dBuilder.parse(ENTITY_XML); - } catch (SAXParseException e) { - throw e; - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } + public void testEntityExpansionDOMNeg() throws Exception { + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(FEATURE_SECURE_PROCESSING, true); + setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2)); + DocumentBuilder dBuilder = dfactory.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + dBuilder.setErrorHandler(eh); + setPermissions(new FilePermission(ENTITY_XML, "read")); + dBuilder.parse(ENTITY_XML); } /** * Test xi:include with a SAXParserFactory. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeSAXPos() { - String resultFile = CLASS_DIR + "doc_xinclude.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeSAXPos() throws Exception { + String resultFile = USER_DIR + "doc_xinclude.out"; String goldFile = GOLDEN_DIR + "doc_xincludeGold.xml"; String xmlFile = XML_DIR + "doc_xinclude.xml"; - - try { - try(FileOutputStream fos = new FileOutputStream(resultFile)) { - XInclHandler xh = new XInclHandler(fos, null); - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setXIncludeAware(true); - spf.setFeature(FEATURE_NAME, true); - spf.newSAXParser().parse(new File(xmlFile), xh); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + + try(FileOutputStream fos = new FileOutputStream(resultFile)) { + XInclHandler xh = new XInclHandler(fos, null); + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setXIncludeAware(true); + spf.setFeature(FEATURE_NAME, true); + spf.newSAXParser().parse(new File(xmlFile), xh); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test the simple case of including a document using xi:include using a * DocumentBuilder. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeDOMPos() { - String resultFile = CLASS_DIR + "doc_xincludeDOM.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeDOMPos() throws Exception { + String resultFile = USER_DIR + "doc_xincludeDOM.out"; String goldFile = GOLDEN_DIR + "doc_xincludeGold.xml"; String xmlFile = XML_DIR + "doc_xinclude.xml"; - try { - 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)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + 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)); } /** * Test the simple case of including a document using xi:include within a * xi:fallback using a DocumentBuilder. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeFallbackDOMPos() { - String resultFile = CLASS_DIR + "doc_fallbackDOM.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeFallbackDOMPos() throws Exception { + String resultFile = USER_DIR + "doc_fallbackDOM.out"; String goldFile = GOLDEN_DIR + "doc_fallbackGold.xml"; String xmlFile = XML_DIR + "doc_fallback.xml"; - try{ - 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)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + 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)); } /** * 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 - public void testXIncludeFallbackTextPos() { - String resultFile = CLASS_DIR + "doc_fallback_text.out"; + @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{ - 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)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + 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)); } /** * Test the XPointer element() framework with XInclude. + * + * @throws Exception If any errors occur. */ - @Test - public void testXpointerElementPos() { - String resultFile = CLASS_DIR + "doc_xpointer_element.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXpointerElementPos() throws Exception { + String resultFile = USER_DIR + "doc_xpointer_element.out"; String goldFile = GOLDEN_DIR + "doc_xpointerGold.xml"; String xmlFile = XML_DIR + "doc_xpointer_element.xml"; - - try{ - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setXIncludeAware(true); - dbf.setNamespaceAware(true); - - DocumentBuilder db = dbf.newDocumentBuilder(); - - TransformerFactory.newInstance().newTransformer() - .transform(new DOMSource(db.parse(new File(xmlFile))), - new StreamResult(fos)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setXIncludeAware(true); + dbf.setNamespaceAware(true); + + DocumentBuilder db = dbf.newDocumentBuilder(); + + TransformerFactory.newInstance().newTransformer() + .transform(new DOMSource(db.parse(new File(xmlFile))), + new StreamResult(fos)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test the XPointer framework with a SAX object. + * + * @throws Exception If any errors occur. */ - @Test - public void testXPointerPos() { - String resultFile = CLASS_DIR + "doc_xpointer.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXPointerPos() throws Exception { + String resultFile = USER_DIR + "doc_xpointer.out"; String goldFile = GOLDEN_DIR + "doc_xpointerGold.xml"; String xmlFile = XML_DIR + "doc_xpointer.xml"; - - try{ - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setXIncludeAware(true); - spf.setFeature(FEATURE_NAME, true); - // parse the file - spf.newSAXParser().parse(new File(xmlFile), new XInclHandler(fos, null)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setXIncludeAware(true); + spf.setFeature(FEATURE_NAME, true); + // parse the file + spf.newSAXParser().parse(new File(xmlFile), new XInclHandler(fos, null)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test if xi:include may reference the doc containing the include if the * parse type is text. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeLoopPos() { - String resultFile = CLASS_DIR + "doc_xinc_loops.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeLoopPos() throws Exception { + String resultFile = USER_DIR + "doc_xinc_loops.out"; String goldFile = GOLDEN_DIR + "doc_xinc_loopGold.xml"; String xmlFile = XML_DIR + "doc_xinc_loops.xml"; - try{ - try (FileOutputStream fos = new FileOutputStream(resultFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setXIncludeAware(true); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document doc = db.parse(new File(xmlFile)); - doc.normalizeDocument(); - doc.setXmlStandalone(true); - - TransformerFactory.newInstance().newTransformer() - .transform(new DOMSource(doc), new StreamResult(fos)); - } - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + try (FileOutputStream fos = new FileOutputStream(resultFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setXIncludeAware(true); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new File(xmlFile)); + doc.normalizeDocument(); + doc.setXmlStandalone(true); + + TransformerFactory.newInstance().newTransformer() + .transform(new DOMSource(doc), new StreamResult(fos)); } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } /** * Test if two non nested xi:include elements can include the same document * with an xi:include statement. + * + * @throws Exception If any errors occur. */ - @Test - public void testXIncludeNestedPos() { - String resultFile = CLASS_DIR + "schedule.out"; + @Test(groups = {"readWriteLocalFiles"}) + public void testXIncludeNestedPos() throws Exception { + String resultFile = USER_DIR + "schedule.out"; String goldFile = GOLDEN_DIR + "scheduleGold.xml"; String xmlFile = XML_DIR + "schedule.xml"; - - try{ - 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)); - } catch (ParserConfigurationException | SAXException | IOException - | TransformerException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } + + 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)); } } --- old/test/javax/xml/jaxp/functional/test/auctionportal/UserController.java 2015-01-09 15:41:31.265108499 -0800 +++ new/test/javax/xml/jaxp/functional/test/auctionportal/UserController.java 2015-01-09 15:41:31.190108382 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -25,21 +25,17 @@ import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_LANGUAGE; import static org.testng.Assert.assertFalse; import java.io.FileOutputStream; -import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; import static jaxp.library.JAXPTestUtilities.compareDocumentWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; - import org.testng.annotations.Test; import org.w3c.dom.Attr; import org.w3c.dom.Document; @@ -50,8 +46,6 @@ import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSParser; import org.w3c.dom.ls.LSSerializer; -import org.xml.sax.SAXException; -import static test.auctionportal.HiBidConstants.CLASS_DIR; import static test.auctionportal.HiBidConstants.GOLDEN_DIR; import static test.auctionportal.HiBidConstants.PORTAL_ACCOUNT_NS; import static test.auctionportal.HiBidConstants.XML_DIR; @@ -59,141 +53,127 @@ /** * This is the user controller class for the Auction portal HiBid.com. */ -public class UserController { +public class UserController extends JAXPFileBaseTest { /** * Checking when creating an XML document using DOM Level 2 validating * it without having a schema source or a schema location It must throw a * sax parse exception. + * + * @throws Exception If any errors occur. */ @Test - public void testCreateNewUser() { - String resultFile = CLASS_DIR + "accountInfoOut.xml"; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(true); - - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - docBuilder.setErrorHandler(eh); - - Document document = docBuilder.newDocument(); - - Element account = document.createElementNS(PORTAL_ACCOUNT_NS, "acc:Account"); - Attr accountID = document.createAttributeNS(PORTAL_ACCOUNT_NS, "acc:accountID"); - account.setAttributeNode(accountID); - - account.appendChild(document.createElement("FirstName")); - account.appendChild(document.createElementNS(PORTAL_ACCOUNT_NS, "acc:LastName")); - account.appendChild(document.createElement("UserID")); - - DOMImplementationLS impl - = (DOMImplementationLS) DOMImplementationRegistry - .newInstance().getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); - LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); - FileOutputStream output = new FileOutputStream(resultFile); + public void testCreateNewUser() throws Exception { + String resultFile = USER_DIR + "accountInfoOut.xml"; + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(true); + + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + docBuilder.setErrorHandler(eh); + + Document document = docBuilder.newDocument(); + + Element account = document.createElementNS(PORTAL_ACCOUNT_NS, "acc:Account"); + Attr accountID = document.createAttributeNS(PORTAL_ACCOUNT_NS, "acc:accountID"); + account.setAttributeNode(accountID); + + account.appendChild(document.createElement("FirstName")); + account.appendChild(document.createElementNS(PORTAL_ACCOUNT_NS, "acc:LastName")); + account.appendChild(document.createElement("UserID")); + + DOMImplementationLS impl + = (DOMImplementationLS) DOMImplementationRegistry + .newInstance().getDOMImplementation("LS"); + LSSerializer writer = impl.createLSSerializer(); + LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); + try(FileOutputStream output = new FileOutputStream(resultFile)) { MyDOMOutput domOutput = new MyDOMOutput(); - domOutput.setByteStream(output); writer.write(account, domOutput); docBuilder.parse(resultFile); - - assertTrue(eh.isAnyError()); - } catch (ParserConfigurationException | ClassNotFoundException | - InstantiationException | IllegalAccessException - | ClassCastException | SAXException | IOException e) { - failUnexpected(e); } + assertTrue(eh.isAnyError()); } /** * Checking conflicting namespaces and use renameNode and normalizeDocument. * @see accountInfo.xml + * + * @throws Exception If any errors occur. */ @Test - public void testAddUser() { - String resultFile = CLASS_DIR + "accountRole.out"; + public void testAddUser() throws Exception { + String resultFile = USER_DIR + "accountRole.out"; String xmlFile = XML_DIR + "accountInfo.xml"; - - try { - // Copy schema for outputfile - Files.copy(Paths.get(XML_DIR, "accountInfo.xsd"), - Paths.get(CLASS_DIR, "accountInfo.xsd"), - StandardCopyOption.REPLACE_EXISTING); - MyErrorHandler eh = new MyErrorHandler(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - - dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - dbf.setNamespaceAware(true); - dbf.setValidating(true); - - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - docBuilder.setErrorHandler(eh); - - Document document = docBuilder.parse(xmlFile); - Element sell = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Sell").item(0); - Element role = (Element) sell.getParentNode(); - - Element buy = (Element) document.renameNode(sell, PORTAL_ACCOUNT_NS, "acc:Buy"); - role.appendChild(buy); - - DOMImplementationLS impl - = (DOMImplementationLS) DOMImplementationRegistry - .newInstance().getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); + + // Copy schema for outputfile + Files.copy(Paths.get(XML_DIR, "accountInfo.xsd"), + Paths.get(USER_DIR, "accountInfo.xsd"), + StandardCopyOption.REPLACE_EXISTING); + MyErrorHandler eh = new MyErrorHandler(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + + dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + dbf.setNamespaceAware(true); + dbf.setValidating(true); + + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + docBuilder.setErrorHandler(eh); + + Document document = docBuilder.parse(xmlFile); + Element sell = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Sell").item(0); + Element role = (Element) sell.getParentNode(); + + Element buy = (Element) document.renameNode(sell, PORTAL_ACCOUNT_NS, "acc:Buy"); + role.appendChild(buy); + + DOMImplementationLS impl + = (DOMImplementationLS) DOMImplementationRegistry + .newInstance().getDOMImplementation("LS"); + LSSerializer writer = impl.createLSSerializer(); - try(FileOutputStream output = new FileOutputStream(resultFile)) { - MyDOMOutput mydomoutput = new MyDOMOutput(); - mydomoutput.setByteStream(output); - writer.write(document, mydomoutput); - } - - docBuilder.parse(resultFile); - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException - | ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException e) { - failUnexpected(e); + try(FileOutputStream output = new FileOutputStream(resultFile)) { + MyDOMOutput mydomoutput = new MyDOMOutput(); + mydomoutput.setByteStream(output); + writer.write(document, mydomoutput); } + + docBuilder.parse(resultFile); + assertFalse(eh.isAnyError()); } /** * Checking Text content in XML file. * @see accountInfo.xml + * + * @throws Exception If any errors occur. */ - @Test - public void testMoreUserInfo() { + @Test(groups = {"readLocalFiles"}) + public void testMoreUserInfo() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - try { - System.out.println("Checking additional user info"); + dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + dbf.setNamespaceAware(true); + dbf.setValidating(true); + + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + docBuilder.setErrorHandler(eh); + + Document document = docBuilder.parse(xmlFile); + Element account = (Element)document + .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); + String textContent = account.getTextContent(); + assertTrue(textContent.trim().regionMatches(0, "Rachel", 0, 6)); + assertEquals(textContent, "RachelGreen744"); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + Attr accountID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); + assertTrue(accountID.getTextContent().trim().equals("1")); - dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - dbf.setNamespaceAware(true); - dbf.setValidating(true); - - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - docBuilder.setErrorHandler(eh); - - Document document = docBuilder.parse(xmlFile); - Element account = (Element)document - .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); - String textContent = account.getTextContent(); - assertTrue(textContent.trim().regionMatches(0, "Rachel", 0, 6)); - assertEquals(textContent, "RachelGreen744"); - - Attr accountID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); - assertTrue(accountID.getTextContent().trim().equals("1")); - - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + assertFalse(eh.isAnyError()); } /** @@ -204,83 +184,73 @@ * into an XML file which is validated by the schema This covers Row 5 * for the table * http://javaweb.sfbay/~jsuttor/JSR206/jsr-206-html/ch03s05.html. Filed - * bug 4893745 because there was a difference in behavior + * bug 4893745 because there was a difference in behavior. + * + * @throws Exception If any errors occur. */ @Test - public void testCreateUserAccount() { - System.out.println("Creating user account"); + public void testCreateUserAccount() throws Exception { String userXmlFile = XML_DIR + "userInfo.xml"; String accountXmlFile = XML_DIR + "accountInfo.xml"; + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(true); + + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + docBuilder.setErrorHandler(eh); + + Document document = docBuilder.parse(userXmlFile); + Element user = (Element) document.getElementsByTagName("FirstName").item(0); + // Set schema after parsing userInfo.xml. Otherwise it will conflict + // with DTD validation. + dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + DocumentBuilder docBuilder1 = dbf.newDocumentBuilder(); + docBuilder1.setErrorHandler(eh); + Document accDocument = docBuilder1.parse(accountXmlFile); + + Element firstName = (Element) accDocument + .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); + Element adoptedAccount = (Element) accDocument.adoptNode(user); + + Element parent = (Element) firstName.getParentNode(); + parent.replaceChild(adoptedAccount, firstName); + + DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); + DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + LSSerializer writer = impl.createLSSerializer(); - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(true); - - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - docBuilder.setErrorHandler(eh); - - Document document = docBuilder.parse(userXmlFile); - Element user = (Element) document.getElementsByTagName("FirstName").item(0); - // Set schema after parsing userInfo.xml. Otherwise it will conflict - // with DTD validation. - dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); - DocumentBuilder docBuilder1 = dbf.newDocumentBuilder(); - docBuilder1.setErrorHandler(eh); - Document accDocument = docBuilder1.parse(accountXmlFile); - - Element firstName = (Element) accDocument - .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); - Element adoptedAccount = (Element) accDocument.adoptNode(user); + MyDOMOutput mydomoutput = new MyDOMOutput(); + mydomoutput.setByteStream(System.out); - Element parent = (Element) firstName.getParentNode(); - parent.replaceChild(adoptedAccount, firstName); + writer.write(document, mydomoutput); + writer.write(accDocument, mydomoutput); - DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); - DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); - LSSerializer writer = impl.createLSSerializer(); - - MyDOMOutput mydomoutput = new MyDOMOutput(); - mydomoutput.setByteStream(System.out); - - writer.write(document, mydomoutput); - writer.write(accDocument, mydomoutput); - - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException - | ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException e) { - failUnexpected(e); - } + assertFalse(eh.isAnyError()); } /** * Checking for Row 8 from the schema table when setting the schemaSource * without the schemaLanguage must report an error. + * + * @throws Exception If any errors occur. */ @Test(expectedExceptions = IllegalArgumentException.class) - public void testUserError() throws IllegalArgumentException { - System.out.println("Creating an error in user account"); - + public void testUserError() throws Exception { String xmlFile = XML_DIR + "userInfo.xml"; String schema = "http://java.sun.com/xml/jaxp/properties/schemaSource"; String schemaValue = "http://dummy.com/dummy.xsd"; - - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setValidating(true); - dbf.setAttribute(schema, schemaValue); - - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - MyErrorHandler eh = new MyErrorHandler(); - docBuilder.setErrorHandler(eh); - Document document = docBuilder.parse(xmlFile); - assertFalse(eh.isAnyError()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(true); + dbf.setAttribute(schema, schemaValue); + + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + MyErrorHandler eh = new MyErrorHandler(); + docBuilder.setErrorHandler(eh); + docBuilder.parse(xmlFile); + assertFalse(eh.isAnyError()); } /** @@ -288,10 +258,12 @@ * @see screenName.xml has prefix of * userName is bound to "http://hibid.com/user" namespace normalization * will create a namespace of prefix us and attach userEmail. + * + * @throws Exception If any errors occur. */ @Test - public void testCheckScreenNameExists() { - String resultFile = CLASS_DIR + "screenName.out"; + public void testCheckScreenNameExists() throws Exception { + String resultFile = USER_DIR + "screenName.out"; String xmlFile = XML_DIR + "screenName.xml"; String goldFile = GOLDEN_DIR + "screenNameGold.xml"; @@ -318,21 +290,7 @@ MyDOMOutput domoutput = new MyDOMOutput(); domoutput.setByteStream(output); writer.write(document, domoutput); - - assertTrue(compareDocumentWithGold(goldFile, resultFile)); - } catch (ClassNotFoundException | InstantiationException - | IllegalAccessException | ClassCastException | IOException - | ParserConfigurationException | SAXException e) { - failUnexpected(e); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if (Files.exists(resultPath)) { - Files.delete(resultPath); - } - } catch (IOException ex) { - failCleanup(ex, resultFile); - } } + assertTrue(compareDocumentWithGold(goldFile, resultFile)); } } --- old/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/MyContentHandler.java 2015-01-09 15:41:31.604109027 -0800 +++ new/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/MyContentHandler.java 2015-01-09 15:41:31.529108910 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 --- old/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/TransformerTestConst.java 2015-01-09 15:41:31.933109540 -0800 +++ new/test/javax/xml/jaxp/libs/javax/xml/transform/ptests/TransformerTestConst.java 2015-01-09 15:41:31.856109420 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,40 +23,22 @@ package javax.xml.transform.ptests; import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; /** * This is the Base test class provide basic support for JAXP functional test */ public class TransformerTestConst { /** - * Current test directory. + * XML source file directory. */ - public static final String CLASS_DIR - = System.getProperty("test.classes", ".") + FILE_SEP; + public static final String XML_DIR = getPathByClassName(TransformerTestConst.class, + ".." + FILE_SEP + "xmlfiles"); + /** - * Package name that separates by slash. + * Golden validation files directory. */ - public static final String PACKAGE_NAME = FILE_SEP + - TransformerTestConst.class.getPackage().getName().replaceAll("[.]", FILE_SEP); - - /** - * Test base directory. Every package has its own test package directory. - */ - public static final String BASE_DIR - = System.getProperty("test.src", USER_DIR).replaceAll("\\" + System.getProperty("file.separator"), "/") - + PACKAGE_NAME + FILE_SEP + ".."; - - /** - * Source XML file directory. - */ - public static final String XML_DIR = BASE_DIR + FILE_SEP + "xmlfiles" + FILE_SEP; - - /** - * Golden output file directory. We pre-define all expected output in golden - * output file. Test verifies whether the standard output is same as content - * of golden file. - */ - public static final String GOLDEN_DIR = XML_DIR + FILE_SEP + "out" + FILE_SEP; + public static final String GOLDEN_DIR = getPathByClassName(TransformerTestConst.class, + ".." + FILE_SEP + "xmlfiles" + FILE_SEP + "out"); } --- old/test/javax/xml/jaxp/libs/javax/xml/xpath/ptests/XPathTestConst.java 2015-01-09 15:41:32.289110095 -0800 +++ new/test/javax/xml/jaxp/libs/javax/xml/xpath/ptests/XPathTestConst.java 2015-01-09 15:41:32.213109977 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,27 +23,15 @@ package javax.xml.xpath.ptests; import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; /** * This is the Base test class provide basic support for XPath functional test */ public class XPathTestConst { /** - * Package name that separates by slash. + * XML source file directory. */ - public static final String PACKAGE_NAME = FILE_SEP + - XPathTestConst.class.getPackage().getName().replaceAll("[.]", FILE_SEP); - - /** - * Test base directory. Every package has its own test package directory. - */ - public static final String BASE_DIR - = System.getProperty("test.src", USER_DIR).replaceAll("\\" + System.getProperty("file.separator"), "/") - + PACKAGE_NAME + FILE_SEP + ".."; - - /** - * Source XML file directory. - */ - public static final String XML_DIR = BASE_DIR + FILE_SEP + "xmlfiles" + FILE_SEP; + public static final String XML_DIR = getPathByClassName(XPathTestConst.class, + ".." + FILE_SEP + "xmlfiles"); } --- old/test/javax/xml/jaxp/libs/jaxp/library/JAXPTestUtilities.java 2015-01-09 15:41:32.659110672 -0800 +++ new/test/javax/xml/jaxp/libs/jaxp/library/JAXPTestUtilities.java 2015-01-09 15:41:32.551110504 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2015, 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 @@ -23,21 +23,34 @@ package jaxp.library; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.StringWriter; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; import static org.testng.Assert.fail; import org.w3c.dom.Document; +import org.w3c.dom.Node; import org.xml.sax.SAXException; /** @@ -59,16 +72,19 @@ * Windows platform. */ public static final String FILE_SEP = "/"; - + /** - * User home. + * Current test directory. */ - public static final String USER_DIR = System.getProperty("user.dir", "."); + public static final String USER_DIR = + System.getProperty("user.dir", ".") + FILE_SEP;; /** - * TEMP file directory. + * A map storing every test's current test file pointer. File number should + * be incremental and it's a thread-safe reading on this file number. */ - public static final String TEMP_DIR = System.getProperty("java.io.tmpdir", "."); + private static final ConcurrentHashMap currentFileNumber + = new ConcurrentHashMap<>(); /** * BOM table for storing BOM header. @@ -88,36 +104,84 @@ /** * Compare contents of golden file with test output file line by line. - * return true if they're identical. + * return true if they're identical. * @param goldfile Golden output file name * @param outputfile Test output file name * @return true if two files are identical. * false if two files are not identical. - * @throws IOException if an I/O error occurs reading from the file or a - * malformed or unmappable byte sequence is read + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read. */ public static boolean compareWithGold(String goldfile, String outputfile) throws IOException { + return compareWithGold(goldfile, outputfile, StandardCharsets.UTF_8); + } + + /** + * Compare contents of golden file with test output file line by line. + * return true if they're identical. + * @param goldfile Golden output file name. + * @param outputfile Test output file name. + * @param cs the charset to use for decoding. + * @return true if two files are identical. + * false if two files are not identical. + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read. + */ + public static boolean compareWithGold(String goldfile, String outputfile, + Charset cs) throws IOException { return Files.readAllLines(Paths.get(goldfile)). - equals(Files.readAllLines(Paths.get(outputfile))); + equals(Files.readAllLines(Paths.get(outputfile), cs)); + } + + /** + * Compare contents of golden file with test output list line by line. + * return true if they're identical. + * @param goldfile Golden output file name. + * @param lines test output list. + * @return true if file's content is identical to given list. + * false if file's content is not identical to given list. + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read + */ + public static boolean compareLinesWithGold(String goldfile, List lines) + throws IOException { + return Files.readAllLines(Paths.get(goldfile)).equals(lines); + } + + /** + * Compare contents of golden file with a test output string. + * return true if they're identical. + * @param goldfile Golden output file name. + * @param string test string. + * @return true if file's content is identical to given string. + * false if file's content is not identical to given string. + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read + */ + public static boolean compareStringWithGold(String goldfile, String string) + throws IOException { + return Files.readAllLines(Paths.get(goldfile)).stream().collect( + Collectors.joining(System.getProperty("line.separator"))) + .equals(string); } /** * Compare contents of golden file with test output file by their document - * representation. - * Here we ignore the white space and comments. return true if they're - * lexical identical. + * representation. + * Here we ignore the white space and comments. return true if they're + * lexical identical. * @param goldfile Golden output file name. * @param resultFile Test output file name. * @return true if two file's document representation are identical. * false if two file's document representation are not identical. - * @throws javax.xml.parsers.ParserConfigurationException if the + * @throws javax.xml.parsers.ParserConfigurationException if the * implementation is not available or cannot be instantiated. * @throws SAXException If any parse errors occur. - * @throws IOException if an I/O error occurs reading from the file or a - * malformed or unmappable byte sequence is read . + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read . */ - public static boolean compareDocumentWithGold(String goldfile, String resultFile) + public static boolean compareDocumentWithGold(String goldfile, String resultFile) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); @@ -132,19 +196,48 @@ resultD.normalizeDocument(); return goldD.isEqualNode(resultD); } + /** - * Convert stream to ByteArrayInputStream by given character set. + * Compare contents of golden file with the serialization represent by given + * DOM node. + * Here we ignore the white space and comments. return true if they're + * lexical identical. + * @param goldfile Golden output file name. + * @param node A DOM node instance. + * @return true if file's content is identical to given node's serialization + * represent. + * false if file's content is not identical to given node's + * serialization represent. + * @throws TransformerException If an unrecoverable error occurs during the + * course of the transformation.. + * @throws IOException if an I/O error occurs reading from the file or a + * malformed or unmappable byte sequence is read . + */ + public static boolean compareSerializeDOMWithGold(String goldfile, Node node) + throws TransformerException, IOException { + TransformerFactory factory = TransformerFactory.newInstance(); + // Use identity transformer to serialize + Transformer identityTransformer = factory.newTransformer(); + StringWriter sw = new StringWriter(); + StreamResult streamResult = new StreamResult(sw); + DOMSource nodeSource = new DOMSource(node); + identityTransformer.transform(nodeSource, streamResult); + return compareStringWithGold(goldfile, sw.toString()); + } + + /** + * Convert stream to ByteArrayInputStream by given character set. * @param charset target character set. * @param file a file that contains no BOM head content. * @return a ByteArrayInputStream contains BOM heads and bytes in original * stream - * @throws IOException I/O operation failed or unsupported character set. + * @throws IOException I/O operation failed or unsupported character set. */ public static InputStream bomStream(String charset, String file) throws IOException { String localCharset = charset; if (charset.equals("UTF-16") || charset.equals("UTF-32")) { - localCharset + localCharset += ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN ? "BE" : "LE"; } if (!bom.containsKey(localCharset)) @@ -158,10 +251,40 @@ bb.put(content); return new ByteArrayInputStream(bb.array()); } + + /** + * Worker method to detect common absolute URLs. + * + * @param s String path\filename or URL (or any, really) + * @return true if s starts with a common URI scheme (namely + * the ones found in the examples of RFC2396); false otherwise + */ + protected static boolean isCommonURL(String s) { + if (null == s) + return false; + return Pattern.compile("^(file:|http:|ftp:|gopher:|mailto:|news:|telnet:)") + .matcher(s).matches(); + } + + /** + * Utility method to translate a String filename to URL. + * + * If the name starts with a common URI scheme (namely the ones + * found in the examples of RFC2396), then simply return the + * name as-is (the assumption is that it's already a URL). + * Otherwise we attempt (cheaply) to convert to a file:/ URL. + * + * @param filename local path/filename of a file. + * @return a file:/ URL if filename represent a file, the same string if + * it appears to already be a URL. + */ + public static String filenameToURL(String filename) { + return Paths.get(filename).toUri().toASCIIString(); + } /** * Prints error message if an exception is thrown - * @param ex The exception is thrown by test. + * @param ex The exception is thrown by test. */ public static void failUnexpected(Throwable ex) { fail(ERROR_MSG_HEADER, ex); @@ -169,10 +292,44 @@ /** * Prints error message if an exception is thrown when clean up a file. - * @param ex The exception is thrown in cleaning up a file. - * @param name Cleaning up file name. + * @param ex The exception is thrown in cleaning up a file. + * @param name Cleaning up file name. */ public static void failCleanup(IOException ex, String name) { fail(String.format(ERROR_MSG_CLEANUP, name), ex); } + + /** + * Retrieve next test output file name. This method is a thread-safe method. + * @param clazz test class. + * @return next test output file name. + */ + public static String getNextFile(Class clazz) { + int nextNumber = currentFileNumber.contains(clazz) + ? currentFileNumber.get(clazz) + 1 : 1; + Integer i = currentFileNumber.putIfAbsent(clazz, nextNumber); + if (i != null && i != nextNumber) { + do { + nextNumber = currentFileNumber.get(clazz) + 1; + } while (currentFileNumber.replace(clazz, nextNumber -1, nextNumber)); + } + return USER_DIR + clazz.getName() + nextNumber + ".out"; + } + + /** + * Acquire a full path string by given class name and relative path string. + * @param clazz Class name for the test. + * @param relativeDir relative path between java source file and expected + * path. + * @return a string represents the full path of accessing path. + */ + public static String getPathByClassName(Class clazz, String relativeDir) { + String packageName = FILE_SEP + + clazz.getPackage().getName().replaceAll("[.]", FILE_SEP); + String javaSourcePath = System.getProperty("test.src").replaceAll("\\" + File.separator, FILE_SEP) + + packageName + FILE_SEP; + String normalizedPath = Paths.get(javaSourcePath, relativeDir).normalize(). + toAbsolutePath().toString(); + return normalizedPath.replace("\\", FILE_SEP) + FILE_SEP; + } } --- old/test/javax/xml/jaxp/libs/org/xml/sax/ptests/SAXTestConst.java 2015-01-09 15:41:33.012111223 -0800 +++ new/test/javax/xml/jaxp/libs/org/xml/sax/ptests/SAXTestConst.java 2015-01-09 15:41:32.935111102 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -23,7 +23,7 @@ package org.xml.sax.ptests; import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; /** * This is the Base test class provide basic support for JAXP SAX functional @@ -32,33 +32,15 @@ */ public class SAXTestConst { /** - * Current test directory. + * XML source file directory. */ - public static final String CLASS_DIR - = System.getProperty("test.classes", ".") + FILE_SEP; + public static final String XML_DIR = getPathByClassName(SAXTestConst.class, + ".." + FILE_SEP + "xmlfiles"); + /** - * Package name that separates by slash. + * Golden validation files directory. */ - public static final String PACKAGE_NAME = FILE_SEP + - SAXTestConst.class.getPackage().getName().replaceAll("[.]", FILE_SEP); - - /** - * Test base directory. Every package has its own test package directory. - */ - public static final String BASE_DIR - = System.getProperty("test.src", USER_DIR).replaceAll("\\" + System.getProperty("file.separator"), "/") - + PACKAGE_NAME + FILE_SEP + ".."; - - /** - * Source XML file directory. - */ - public static final String XML_DIR = BASE_DIR + FILE_SEP + "xmlfiles" + FILE_SEP; - - /** - * Golden output file directory. We pre-define all expected output in golden - * output file. Test verifies whether the standard output is same as content - * of golden file. - */ - public static final String GOLDEN_DIR = XML_DIR + FILE_SEP + "out" + FILE_SEP; + public static final String GOLDEN_DIR = getPathByClassName(SAXTestConst.class, + ".." + FILE_SEP + "xmlfiles" + FILE_SEP + "out"); } --- old/test/javax/xml/jaxp/libs/test/auctionportal/HiBidConstants.java 2015-01-09 15:41:33.360111765 -0800 +++ new/test/javax/xml/jaxp/libs/test/auctionportal/HiBidConstants.java 2015-01-09 15:41:33.283111645 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, 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 @@ -22,44 +22,21 @@ */ package test.auctionportal; -import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; /** * This is the Base test class provide basic support for Auction portal test. */ public class HiBidConstants { /** - * Current test directory. + * XML source file directory. */ - public static final String CLASS_DIR - = System.getProperty("test.classes", ".") + FILE_SEP; + public static final String XML_DIR = getPathByClassName(HiBidConstants.class, "content"); /** - * Package name that separates by slash. + * Golden validation files directory. */ - public static final String PACKAGE_NAME = FILE_SEP + - HiBidConstants.class.getPackage().getName().replaceAll("[.]", FILE_SEP); - - - /** - * Java source directory. - */ - public static final String SRC_DIR = System.getProperty("test.src", USER_DIR) - .replaceAll("\\" + System.getProperty("file.separator"), "/") - + PACKAGE_NAME + FILE_SEP; - - /** - * Source XML file directory. - */ - public static final String XML_DIR = SRC_DIR + "content" + FILE_SEP; - - /** - * Golden output file directory. - * We pre-define all expected output in golden output file. Test verifies - * whether the standard output is same as content of golden file. - */ - public static final String GOLDEN_DIR = SRC_DIR + "golden" + FILE_SEP; + public static final String GOLDEN_DIR = getPathByClassName(HiBidConstants.class, "golden"); /** * Name space for account operation. --- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory01.java 2015-01-09 15:41:33.742112361 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,451 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.parsers.ptests; - -import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * This checks the methods of DocumentBuilderFactoryImpl - */ -public class DocumentBuilderFactory01 { - /** - * Testcase to test the default functionality of schema support method. - */ - @Test - public void testCheckSchemaSupport1() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - dbf.setNamespaceAware(true); - dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "test.xml")); - assertFalse(eh.errorOccured); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the default functionality of schema support method. In - * this case the schema source property is set. - */ - @Test - public void testCheckSchemaSupport2() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - dbf.setNamespaceAware(true); - dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); - dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", new InputSource(new FileInputStream( - new File(TestUtils.XML_DIR, "test.xsd")))); - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "test1.xml")); - assertFalse(eh.errorOccured); - } catch (IllegalArgumentException | ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - - } - - /** - * Testcase to test the default functionality of schema support method. In - * this case the schema source property is set. - */ - @Test - public void testCheckSchemaSupport3() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setValidating(true); - spf.setNamespaceAware(true); - SAXParser sp = spf.newSAXParser(); - sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); - sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", - new InputSource(new FileInputStream(new File(TestUtils.XML_DIR, "test.xsd")))); - DefaultHandler dh = new DefaultHandler(); - sp.parse(new File(TestUtils.XML_DIR, "test1.xml"), dh); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the default functionality of newInstance method. To test - * the isCoalescing method and setCoalescing This checks to see if the CDATA - * and text nodes got combined In that case it will print "<xml>This - * is not parsed</xml> yet". - */ - @Test - public void testCheckDocumentBuilderFactory02() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setCoalescing(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory01.xml")); - Element e = (Element) doc.getElementsByTagName("html").item(0); - NodeList nl = e.getChildNodes(); - assertEquals(nl.item(0).getNodeValue().trim(), "This is not parsed yet"); - } catch (IOException | SAXException | ParserConfigurationException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the isIgnoringComments. By default it is false. - */ - @Test - public void testCheckDocumentBuilderFactory03() { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - assertFalse(dbf.isIgnoringComments()); - } - - /** - * Testcase to test the isValidating. By default it is false, set it to true - * and then use a document which is not valid. It should throw a warning or - * an error at least. The test passes in case retval 0 is set in the error - * method . - */ - @Test - public void testCheckDocumentBuilderFactory04() { - try { - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory05.xml")); - assertTrue(eh.errorOccured); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the setValidating. By default it is false, use a - * document which is not valid. It should not throw a warning or an error. - * The test passes in case the retval equals 1 . - */ - @Test - public void testCheckDocumentBuilderFactory16() { - try { - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory05.xml")); - assertFalse(eh.errorOccured); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - - } - - /** - * Testcase to test the setValidating. By default it is false, use a - * document which is valid. It should not throw a warning or an error. The - * test passes in case the retval equals 1. - */ - @Test - public void testCheckDocumentBuilderFactory17() { - try { - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory04.xml")); - assertFalse(eh.errorOccured); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - - } - - /** - * To test the isExpandEntityReferences. By default it is true. - */ - @Test - public void testCheckDocumentBuilderFactory05() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory02.xml"))); - Element e = (Element) doc.getElementsByTagName("title").item(0); - NodeList nl = e.getChildNodes(); - assertTrue(dbf.isExpandEntityReferences()); - assertEquals(nl.item(0).getNodeValue().trim().charAt(0), 'W'); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the default functionality of setValidating method. The - * xml file has a DTD which has namespaces defined. The parser takes care to - * check if the namespaces using elements and defined attributes are there - * or not. - */ - @Test - public void testCheckDocumentBuilderFactory06() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - MyErrorHandler eh = MyErrorHandler.newInstance(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory04.xml")); - assertTrue(doc instanceof Document); - assertFalse(eh.errorOccured); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - - } - - /** - * Testcase to test the setExpandEntityReferences. - */ - @Test - public void testCheckDocumentBuilderFactory07() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setExpandEntityReferences(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory02.xml"))); - Element e = (Element) doc.getElementsByTagName("title").item(0); - NodeList nl = e.getChildNodes(); - assertTrue(dbf.isExpandEntityReferences()); - assertEquals(nl.item(0).getNodeValue().trim().charAt(0), 'W'); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the setExpandEntityReferences. - */ - @Test - public void testCheckDocumentBuilderFactory08() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setExpandEntityReferences(false); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory02.xml"))); - Element e = (Element) doc.getElementsByTagName("title").item(0); - NodeList nl = e.getChildNodes(); - assertNull(nl.item(0).getNodeValue()); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the setIgnoringComments. By default it is set to false. - * explicitly setting it to false, it recognizes the comment which is in - * Element Node Hence the Element's child node is not null. - */ - @Test - public void testCheckDocumentBuilderFactory09() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setIgnoringComments(false); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory07.xml"))); - Element e = (Element) doc.getElementsByTagName("body").item(0); - NodeList nl = e.getChildNodes(); - assertNotNull(nl.item(0).getNodeValue()); - } catch (ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - - } - - /** - * This tests for the parse(InputSource). - */ - @Test - public void testCheckDocumentBuilderFactory10() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new InputSource(new BufferedReader(new FileReader(new File(TestUtils.XML_DIR, "DocumentBuilderFactory07.xml"))))); - assertTrue(doc instanceof Document); - } catch (IllegalArgumentException | ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse InputStream with SystemID as a second parameter. - */ - @Test - public void testCheckDocumentBuilderFactory11() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "dbf10import.xsl")), new File(TestUtils.XML_DIR).toURI() - .toASCIIString()); - assertTrue(doc instanceof Document); - } catch (IllegalArgumentException | ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse InputStream with empty SystemID as a second - * parameter. - */ - @Test - public void testCheckDocumentBuilderFactory12() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "dbf10import.xsl")), " "); - assertTrue(doc instanceof Document); - } catch (IllegalArgumentException | ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse(uri). - */ - @Test - public void testCheckDocumentBuilderFactory13() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new File(TestUtils.XML_DIR + FILE_SEP + "dbf10import.xsl").toURI().toASCIIString()); - assertTrue(doc instanceof Document); - } catch (IllegalArgumentException | ParserConfigurationException | IOException | SAXException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse (uri) with empty string as parameter should - * throw Sax Exception. - * - * @throws SAXException - * If any parse errors occur. - */ - @Test(expectedExceptions = SAXException.class) - public void testCheckDocumentBuilderFactory14() throws SAXException { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - docBuilder.parse(""); - } catch (ParserConfigurationException | IOException e) { - failUnexpected(e); - } - } - - /** - * This tests for the parse (uri) with null uri as parameter should throw - * IllegalArgumentException. - * - */ - @Test(expectedExceptions = IllegalArgumentException.class) - public void testCheckDocumentBuilderFactory15() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - String uri = null; - docBuilder.parse(uri); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - } - - /** - * Testcase to test the setIgnoringComments. By default it is set to false, - * setting this to true, It does not recognize the comment, Here the - * nodelist has a length 0 because the ignoring comments is true. - */ - @Test - public void testCheckIgnoringComments() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setIgnoringComments(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory08.xml"))); - Element e = (Element) doc.getElementsByTagName("body").item(0); - NodeList nl = e.getChildNodes(); - assertEquals(nl.getLength(), 0); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - - } - - /** - * Testcase to test the default behaviour of setIgnoringComments. By default - * it is set to false, this is similar to case 9 but not setIgnoringComments - * explicitly, it does not recognize the comment. - */ - @Test - public void testCheckIgnoringComments1() { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document doc = docBuilder.parse(new FileInputStream(new File(TestUtils.XML_DIR, "DocumentBuilderFactory07.xml"))); - Element e = (Element) doc.getElementsByTagName("body").item(0); - NodeList nl = e.getChildNodes(); - assertFalse(dbf.isIgnoringComments()); - assertNotNull(nl.item(0).getNodeValue()); - } catch (ParserConfigurationException | SAXException | IOException e) { - failUnexpected(e); - } - } -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactoryTest.java 2015-01-09 15:41:33.621112172 -0800 @@ -0,0 +1,462 @@ +/* + * Copyright (c) 1999, 2015, 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 javax.xml.parsers.ptests; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FilePermission; +import java.io.FileReader; +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import static javax.xml.parsers.ptests.ParserTestConst.GOLDEN_DIR; +import static javax.xml.parsers.ptests.ParserTestConst.XML_DIR; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.SAXResult; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * This checks the methods of DocumentBuilderFactoryImpl. + */ +public class DocumentBuilderFactoryTest extends JAXPFileBaseTest { + /** + * Test the default functionality of schema support method. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckSchemaSupport1() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + dbf.setNamespaceAware(true); + dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", + W3C_XML_SCHEMA_NS_URI); + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "test.xml")); + assertFalse(eh.isErrorOccured()); + } + + /** + * Test the default functionality of schema support method. In + * this case the schema source property is set. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckSchemaSupport2() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "test.xsd"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + dbf.setNamespaceAware(true); + dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", + W3C_XML_SCHEMA_NS_URI); + dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", + new InputSource(fis)); + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "test1.xml")); + assertFalse(eh.isErrorOccured()); + } + } + + /** + * Test the default functionality of schema support method. In + * this case the schema source property is set. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckSchemaSupport3() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "test.xsd"))) { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setValidating(true); + spf.setNamespaceAware(true); + SAXParser sp = spf.newSAXParser(); + sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", + W3C_XML_SCHEMA_NS_URI); + sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", + new InputSource(fis)); + DefaultHandler dh = new DefaultHandler(); + // Not expect any unrecoverable error here. + sp.parse(new File(XML_DIR, "test1.xml"), dh); + } + } + + /** + * Test the default functionality of newInstance method. To test + * the isCoalescing method and setCoalescing This checks to see if the CDATA + * and text nodes got combined In that case it will print "<xml>This + * is not parsed</xml> yet". + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory02() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setCoalescing(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(new File(XML_DIR, "DocumentBuilderFactory01.xml")); + Element e = (Element) doc.getElementsByTagName("html").item(0); + NodeList nl = e.getChildNodes(); + assertEquals(nl.getLength(), 1); + } + + /** + * Test the isIgnoringComments. By default it is false. + */ + @Test + public void testCheckDocumentBuilderFactory03() { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + assertFalse(dbf.isIgnoringComments()); + } + + /** + * Test the isValidating. By default it is false, set it to true and then + * use a document which is not valid. It should throw a warning or + * an error at least. The test passes in case retval 0 is set in the error + * method . + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory04() throws Exception { + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "DocumentBuilderFactory05.xml")); + assertTrue(eh.isErrorOccured()); + } + + /** + * Test the setValidating. By default it is false, use a + * document which is not valid. It should not throw a warning or an error. + * The test passes in case the return value equals 1. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory16() throws Exception { + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "DocumentBuilderFactory05.xml")); + assertFalse(eh.isErrorOccured()); + } + + /** + * Test the setValidating. By default it is false, use a + * document which is valid. It should not throw a warning or an error. The + * test passes in case the return value equals 1. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory17() throws Exception { + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + db.parse(new File(XML_DIR, "DocumentBuilderFactory04.xml")); + assertFalse(eh.isErrorOccured()); + } + + /** + * Test the isExpandEntityReferences. By default it is true. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory05() throws Exception { + try(FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory02.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("title").item(0); + NodeList nl = e.getChildNodes(); + assertTrue(dbf.isExpandEntityReferences()); + assertEquals(nl.item(0).getNodeValue().trim().charAt(0), 'W'); + } + } + + /** + * Test the default functionality of setValidating method. The + * XML file has a DTD which has namespaces defined. The parser takes care to + * check if the namespaces using elements and defined attributes are there + * or not. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory06() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + MyErrorHandler eh = MyErrorHandler.newInstance(); + db.setErrorHandler(eh); + Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory04.xml")); + assertTrue(doc instanceof Document); + assertFalse(eh.isErrorOccured()); + } + + /** + * Test the setExpandEntityReferences. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory07() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory02.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setExpandEntityReferences(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("title").item(0); + NodeList nl = e.getChildNodes(); + assertTrue(dbf.isExpandEntityReferences()); + assertEquals(nl.item(0).getNodeValue().trim().charAt(0), 'W'); + } + } + + /** + * Test the setExpandEntityReferences. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory08() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory02.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setExpandEntityReferences(false); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("title").item(0); + NodeList nl = e.getChildNodes(); + assertNull(nl.item(0).getNodeValue()); + } + } + + /** + * Test the setIgnoringComments. By default it is set to false. + * explicitly setting it to false, it recognizes the comment which is in + * Element Node Hence the Element's child node is not null. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory09() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory07.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setIgnoringComments(false); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("body").item(0); + NodeList nl = e.getChildNodes(); + assertNotNull(nl.item(0).getNodeValue()); + } + } + + /** + * This tests for the parse(InputSource). + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory10() throws Exception { + try (BufferedReader br = new BufferedReader(new FileReader(new File( + XML_DIR, "DocumentBuilderFactory07.xml")))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(new InputSource(br)); + assertNotNull(doc); + } + } + + /** + * This tests for the parse InputStream with SystemID as a second parameter. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory11() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "dbf10import.xsl"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis, new File(XML_DIR).toURI() + .toASCIIString()); + assertNotNull(doc); + } + } + + /** + * This tests for the parse InputStream with empty SystemID as a second + * parameter. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory12() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "dbf10import.xsl"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis, " "); + assertNotNull(doc); + } + } + + /** + * This tests for the parse(uri). + * @throws Exception If any errors occur. + */ + @Test + public void testCheckDocumentBuilderFactory13() throws Exception { + // Accesing default working directory. + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir + "/*", "read")); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(new File(XML_DIR + "dbf10import.xsl") + .toURI().toASCIIString()); + assertNotNull(doc); + } + + /** + * This tests for the parse(uri) with empty string as parameter should + * throw Sax Exception. + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = SAXException.class) + public void testCheckDocumentBuilderFactory14() throws Exception { + // Accesing default working directory. + String workingDir = getSystemProperty("user.dir"); + setPermissions(new FilePermission(workingDir, "read")); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + docBuilder.parse(""); + } + + /** + * This tests for the parse (uri) with null uri as parameter should throw + * IllegalArgumentException. + * @throws Exception If any errors occur. + * + */ + @Test(expectedExceptions = IllegalArgumentException.class) + public void testCheckDocumentBuilderFactory15() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + String uri = null; + docBuilder.parse(uri); + } + + /** + * Test the setIgnoringComments. By default it is set to false, + * setting this to true, It does not recognize the comment, Here the + * nodelist has a length 0 because the ignoring comments is true. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckIgnoringComments() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory08.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setIgnoringComments(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("body").item(0); + NodeList nl = e.getChildNodes(); + assertEquals(nl.getLength(), 0); + } + } + + /** + * Test the default behaviour of setIgnoringComments. By default + * it is set to false, this is similar to case 9 but not setIgnoringComments + * explicitly, it does not recognize the comment. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckIgnoringComments1() throws Exception { + try (FileInputStream fis = new FileInputStream(new File( + XML_DIR, "DocumentBuilderFactory07.xml"))) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document doc = docBuilder.parse(fis); + Element e = (Element) doc.getElementsByTagName("body").item(0); + NodeList nl = e.getChildNodes(); + assertFalse(dbf.isIgnoringComments()); + assertNotNull(nl.item(0).getNodeValue()); + } + } + + /** + * Test for the isIgnoringElementContentWhitespace and the + * setIgnoringElementContentWhitespace. The xml file has all kinds of + * whitespace,tab and newline characters, it uses the MyNSContentHandler + * which does not invoke the characters callback when this + * setIgnoringElementContentWhitespace is set to true. + * @throws Exception If any errors occur. + */ + @Test + public void testCheckElementContentWhitespace() throws Exception { + String goldFile = GOLDEN_DIR + "dbfactory02GF.out"; + String outputFile = USER_DIR + "dbfactory02.out"; + MyErrorHandler eh = MyErrorHandler.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + assertFalse(dbf.isIgnoringElementContentWhitespace()); + dbf.setIgnoringElementContentWhitespace(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(eh); + Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml")); + assertFalse(eh.isErrorOccured()); + DOMSource domSource = new DOMSource(doc); + TransformerFactory tfactory = TransformerFactory.newInstance(); + Transformer transformer = tfactory.newTransformer(); + SAXResult saxResult = new SAXResult(); + try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) { + saxResult.setHandler(handler); + transformer.transform(domSource, saxResult); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } +} \ No newline at end of file --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/DOMResultTest01.java 2015-01-09 15:41:34.118112947 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMResult; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXSource; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.w3c.dom.Attr; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * DOM parse on test file to be compared with golden output file. No Exception - * is expected. - */ -public class DOMResultTest01 { - /** - * Unit test for simple DOM parsing. - */ - @Test - public void testcase01() { - String resultFile = CLASS_DIR + "domresult01.out"; - String goldFile = GOLDEN_DIR + "domresult01GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory) TransformerFactory.newInstance(); - SAXSource saxSource = new SAXSource(new InputSource(xsltFile)); - TransformerHandler handler - = saxTFactory.newTransformerHandler(saxSource); - - DOMResult result = new DOMResult(); - - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - - Node node = result.getNode(); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writeNodes(node, writer); - } - assertTrue(compareWithGold(goldFile, resultFile)); - } catch (SAXException | TransformerConfigurationException - | IllegalArgumentException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path resultPath = Paths.get(resultFile); - if(Files.exists(resultPath)) - Files.delete(resultPath); - } catch (IOException ex) { - failCleanup(ex, resultFile); - } - } - } - - /** - * Prints all node names, attributes to file - * @param node a node that need to be recursively access. - * @param bWriter file writer. - * @throws IOException if writing file failed. - */ - private void writeNodes(Node node, BufferedWriter bWriter) throws IOException { - String str = "Node: " + node.getNodeName(); - bWriter.write( str, 0,str.length()); - bWriter.newLine(); - - NamedNodeMap nnm = node.getAttributes(); - if (nnm != null && nnm.getLength() > 0) - for (int i=0; i 0) + for (int i=0; i { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(new File(xslFile)); - DOMSource domSource = new DOMSource(document); - StreamSource streamSource = new StreamSource(new FileInputStream(xmlFile)); - - File streamResultFile = new File(CLASS_DIR + file); - StreamResult streamResult = new StreamResult(streamResultFile); - - Transformer transformer = TransformerFactory.newInstance().newTransformer(domSource); - transformer.setOutputProperties(transformProperties); - transformer.transform(streamSource, streamResult); - } catch (SAXException | IOException | ParserConfigurationException - | TransformerException ex) { - failUnexpected(ex); - } - }); - } -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/StreamResultTest.java 2015-01-09 15:41:35.120114509 -0800 @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2003, 2015, 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 javax.xml.transform.ptests; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.Properties; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.failUnexpected; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +/** + * Test a StreamResult using a file name that contains URL characters that need + * to be encoded. + */ +public class StreamResultTest extends JAXPFileBaseTest { + /** + * Unit test for StreamResult. + */ + @Test + public void testcase01() { + // Set Transformer properties + Properties transformProperties = new Properties(); + transformProperties.put("method", "xml"); + transformProperties.put("encoding", "UTF-8"); + transformProperties.put("omit-xml-declaration", "yes"); + transformProperties.put("{http://xml.apache.org/xslt}indent-amount", "0"); + transformProperties.put("indent", "no"); + transformProperties.put("standalone", "no"); + transformProperties.put("version", "1.0"); + transformProperties.put("media-type", "text/xml"); + + String[] fileNames = { + "StreamResult01.out", + "StreamResult 02.out", + "StreamResult#03.out" + }; + + String xslFile = XML_DIR + "cities.xsl"; + String xmlFile = XML_DIR + "cities.xml"; + + Arrays.stream(fileNames).forEach(file -> { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(xslFile)); + DOMSource domSource = new DOMSource(document); + StreamSource streamSource = new StreamSource(new FileInputStream(xmlFile)); + + File streamResultFile = new File(USER_DIR + file); + StreamResult streamResult = new StreamResult(streamResultFile); + + Transformer transformer = TransformerFactory.newInstance().newTransformer(domSource); + transformer.setOutputProperties(transformProperties); + transformer.transform(streamSource, streamResult); + } catch (SAXException | IOException | ParserConfigurationException + | TransformerException ex) { + failUnexpected(ex); + } + }); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/dtm/TestDTM.java 2015-01-09 15:41:35.476115064 -0800 @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.dtm; + +import com.sun.org.apache.xml.internal.dtm.DTM; +import java.io.FilePermission; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import jaxp.library.JAXPBaseTest; +import static jaxp.library.JAXPTestUtilities.compareLinesWithGold; +import static org.apache.qetest.dtm.QeDtmConst.GOLDEN_DIR; +import static org.apache.qetest.dtm.QeDtmConst.TYPENAME; +import static org.apache.qetest.dtm.QeDtmConst.generateDTM; +import org.testng.annotations.Test; + +/** + * Loads an XML document from a file (or, if no filename is supplied, + * an internal string), then dumps its contents. Replaces the old + * version, which was specific to the ultra-compressed implementation. + * (Which, by the way, we probably ought to revisit as part of our ongoing + * speed/size performance evaluation.) + */ +public class TestDTM extends JAXPBaseTest { + /** + * Create AxisIterator and walk CHILD axis. Dump every walked node and + * compare with expected golden file. + * + * @throws IOException if any I/O operation error. + */ + @Test + public void test() throws IOException { + setPermissions(new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.utils"), + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xpath.internal.objects")); + String goldFile = GOLDEN_DIR + "DTM_testcase1.out"; + + // Create dtm and generate initial context + DTM dtm = generateDTM(); + + // DTM -- which will always be true for a node obtained this way, but + // won't be true for "shared" DTMs used to hold XSLT variables + int rootNode = dtm.getDocument(); + List lines = new ArrayList<>(); + lines.add("DOCUMENT PROPERTIES:"); + lines.add("DocURI=\"" + dtm.getDocumentBaseURI() + "\" \"SystemID=\"" + + dtm.getDocumentSystemIdentifier(rootNode) + "\""); + lines.add("StandAlone=\"" + dtm.getDocumentStandalone(rootNode) + + "\" DocVersion=\"" + dtm.getDocumentVersion(rootNode) + "\""); + lines.add(""); + lines.add("DOCUMENT DATA:"); + // Simple test: Recursively dump the DTM's content. + // We'll want to replace this with more serious examples + lines.add("DOCUMENT DATA:"); + + recursiveDumpNode(dtm, rootNode, lines); + setPermissions(new FilePermission(goldFile, "read")); + compareLinesWithGold(goldFile, lines); + } + + /** + * Format node info to a string list. + * @param dtm DTM instance. + * @param nodeHandle node handle that represent node will be dumped. + * @param indent a format indention. + * @return + */ + private List getNodeInfo(DTM dtm, int nodeHandle, String indent) { + List nodeLines = new ArrayList<>(); + String value = dtm.getNodeValue(nodeHandle); + String vq = (value == null) ? "" : "\""; + + // Skip outputing of text nodes. In most cases they clutter the output, + // besides I'm only interested in the elemental structure of the dtm. + nodeLines.add(indent + nodeHandle + ": " + + TYPENAME[dtm.getNodeType(nodeHandle)] + " " + + dtm.getNodeNameX(nodeHandle) + " : " + + dtm.getNodeName(nodeHandle) + "\"" + + " E-Type=" + dtm.getExpandedTypeID(nodeHandle) + + " Level=" + dtm.getLevel(nodeHandle) + + " Value=" + vq + value + vq); + + nodeLines.add(indent + "\tPrefix= " + "\"" + dtm.getPrefix(nodeHandle) + "\"" + + " Name= " + "\"" + dtm.getLocalName(nodeHandle) + "\"" + + " URI= " + "\"" + dtm.getNamespaceURI(nodeHandle) + "\"" + + " Parent=" + dtm.getParent(nodeHandle) + + " 1stChild=" + dtm.getFirstChild(nodeHandle) + + " NextSib=" + dtm.getNextSibling(nodeHandle)); + return nodeLines; + } + + /** + * Recursively access every children of the node. Dump every information of + * every node to given string list. + * @param dtm DTM instance. + * @param nodeHandle node handle that will be accessed. + * @param lines a string list that recursive accessed node information will + * be dumped. + */ + private void recursiveDumpNode(DTM dtm, int nodeHandle, List lines) { + // ITERATE over siblings + while (DTM.NULL != nodeHandle) { + lines.addAll(getNodeInfo(dtm, nodeHandle, "")); + + // List the namespaces, if any. Include only node's local + // namespaces, not inherited + int kid = dtm.getFirstNamespaceNode(nodeHandle, false); + if (kid != DTM.NULL) { + lines.add("\tNAMESPACES:"); + //builder.append("\n\tNAMESPACES:"); + for (; kid != DTM.NULL; kid = dtm.getNextNamespaceNode(nodeHandle, kid, false)) { + lines.addAll(getNodeInfo(dtm, kid, "\t")); + } + } + + // List the attributes, if any + kid = dtm.getFirstAttribute(nodeHandle); + if (kid != DTM.NULL) { + lines.add("\tATTRIBUTES:"); + for (; kid != DTM.NULL; kid = dtm.getNextSibling(kid)) { + lines.addAll(getNodeInfo(dtm, kid, "\t")); + } + } + + // Recurse into the children, if any + recursiveDumpNode(dtm, dtm.getFirstChild(nodeHandle), lines); + nodeHandle = dtm.getNextSibling(nodeHandle); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/dtm/TestDTMIter.java 2015-01-09 15:41:35.738115473 -0800 @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.dtm; + +import com.sun.org.apache.xml.internal.dtm.Axis; +import com.sun.org.apache.xml.internal.dtm.DTM; +import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator; +import java.io.IOException; +import jaxp.library.JAXPBaseTest; +import static org.apache.qetest.dtm.QeDtmConst.generateDTM; +import static org.apache.qetest.dtm.QeDtmConst.getNodeName; +import static org.testng.Assert.assertEquals; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +/** + * + * Test for Axis Iterator walking. + */ +public class TestDTMIter extends JAXPBaseTest { + /** + * DTM instance. + */ + private final DTM dtm; + + /* + * Intiate by creating DTM instance and generate initial context. + * + */ + public TestDTMIter() { + dtm = generateDTM(); + } + + /** + * A data provider that provide validation parameters and expected lines. + * + * @return an two dimensional array that provide axis type and expected + * lines. + */ + @DataProvider + public Object[][] iterProvider() { + final Object[][] chkChild = new Object[][] { + { 65542, "COMMENT", "#comment", 3, " Default test document " }, + { 65543, "PROCESSING_INSTRUCTION", "api", 3, "a1=\"yes\" a2=\"no\"" }, + { 65544, "ELEMENT", "A", 3, null }, + { 65554, "ELEMENT", "Aa", 3, null }, + { 65555, "ELEMENT", "Ab", 3, null }, + { 65556, "ELEMENT", "Ac", 3, null }, + { 65558, "ELEMENT", "Ad", 3, null } + }; + + final Object[][] chkParent = new Object[][]{ + {65537, "ELEMENT", "Document", 2, null} + }; + + Object[][] chkSelf = new Object[][]{ + {65558, "ELEMENT", "Ad", 3, null} + }; + + final Object[][] chkNamespace = new Object[][]{ + {65538, "NAMESPACE", "xmlns:xml", 3, "http://www.w3.org/XML/1998/namespace"}, + {65539, "NAMESPACE", "xmlns:d", 3, "www.d.com"}, + {65559, "NAMESPACE", "xmlns:Ad", 4, "www.Ad.com"}, + {65560, "NAMESPACE", "xmlns:y", 4, "www.y.com"}, + {65561, "NAMESPACE", "xmlns:z", 4, "www.z.com"} + }; + + final Object[][] chkPreceding = new Object[][]{ + { 65542, "COMMENT", "#comment", 3, " Default test document "}, + { 65543, "PROCESSING_INSTRUCTION", "api", 3, "a1=\"yes\" a2=\"no\""}, + { 65544, "ELEMENT", "A", 3, null}, + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null}, + { 65554, "ELEMENT", "Aa", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65556, "ELEMENT", "Ac", 3, null}, + { 65557, "ELEMENT", "Ac1", 4, null} + }; + + final Object[][] chkPrecedingsibling = new Object[][]{ + {65542, "COMMENT", "#comment", 3, " Default test document "}, + {65543, "PROCESSING_INSTRUCTION", "api", 3, "a1=\"yes\" a2=\"no\""}, + {65544, "ELEMENT", "A", 3, null}, + {65554, "ELEMENT", "Aa", 3, null}, + {65555, "ELEMENT", "Ab", 3, null}, + {65556, "ELEMENT", "Ac", 3, null} + }; + + final Object[][] chkFollowing = new Object[][]{ + { 65554, "ELEMENT", "Aa", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65556, "ELEMENT", "Ac", 3, null}, + { 65557, "ELEMENT", "Ac1", 4, null}, + { 65558, "ELEMENT", "Ad", 3, null}, + { 65562, "ELEMENT", "Ad1", 4, null} + }; + + final Object[][] checkFollowingSibling = new Object[][]{ + { 65554, "ELEMENT", "Aa", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65556, "ELEMENT", "Ac", 3, null}, + { 65558, "ELEMENT", "Ad", 3, null}, + }; + + final Object[][] checkDescendant = new Object[][]{ + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null} + }; + + final Object[][] checkDescendantSelf = new Object[][]{ + { 65544, "ELEMENT", "A", 3, null}, + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null} + }; + + final Object[][] checkAncestor = new Object[][]{ + { 65536, "DOCUMENT", "#document", 1, null}, + { 65537, "ELEMENT", "Document", 2, null}, + { 65544, "ELEMENT", "A", 3, null}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null} + }; + + final Object[][] checkAncestorSelf = new Object[][]{ + { 65536, "DOCUMENT", "#document", 1, null}, + { 65537, "ELEMENT", "Document", 2, null}, + { 65544, "ELEMENT", "A", 3, null}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null} + }; + return new Object[][]{ + {65537, Axis.CHILD, "Document", false, chkChild}, + {65558, Axis.PARENT, "Ad", false, chkParent}, + {65558, Axis.SELF, "Ad", false, chkSelf}, + {65558, Axis.NAMESPACE, "Ad", false, chkNamespace}, + {65558, Axis.PRECEDING, "Ad", true, chkPreceding}, + {65558, Axis.PRECEDINGSIBLING, "Ad", true, chkPrecedingsibling}, + {65558, Axis.FOLLOWING, "Ad", false, chkFollowing}, + {65558, Axis.FOLLOWINGSIBLING, "Ad", false, checkFollowingSibling}, + {65544, Axis.DESCENDANT, "A", false, checkDescendant}, + {65544, Axis.DESCENDANTORSELF, "A", false, checkDescendantSelf} , + {65550, Axis.ANCESTOR, "F", true, checkAncestor}, + {65550, Axis.ANCESTORORSELF, "F", true, checkAncestorSelf} + }; + } + + /** + * Walk all kind of AxisIterator and checking API as expected. + * + * @param startNode node id to get AxisIterator. + * @param axisType Axis type. + * @param expectedName expected node name. + * @param reversable expected boolean value for checking if the AxisIterator + * is revertible. + * @param expectedLines an two dimensional array that will be validate + * traversal of AxisIterator + * @throws IOException if any I/O operation error. + */ + @Test(dataProvider = "iterProvider") + public void test(int startNode, int axisType, String expectedName, + boolean reversable, Object[][] expectedLines) throws IOException { + // This permission is special for the testing. + setPermissions( + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.utils"), + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xpath.internal.objects")); + + // Get a Iterator by given Axis type. + DTMAxisIterator iter = dtm.getAxisIterator(axisType); + iter.setStartNode(startNode); + + // Print out info about the axis + assertEquals(dtm.getNodeName(startNode), expectedName); + assertEquals(iter.isReverse(), reversable); + + // Iterate the axis and write node info to output file + int line = 0; + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next(), line++) { + assertEquals(itNode, expectedLines[line][0]); + assertEquals(getNodeName(dtm, itNode), expectedLines[line][1]); + assertEquals(dtm.getNodeName(itNode), expectedLines[line][2]); + Integer expectedLevel = (Integer)expectedLines[line][3]; + assertEquals(dtm.getLevel(itNode), expectedLevel.shortValue()); + assertEquals(dtm.getNodeValue(itNode), expectedLines[line][4]); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/dtm/TestDTMIterDeep.java 2015-01-09 15:41:35.998115878 -0800 @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.dtm; + +import com.sun.org.apache.xml.internal.dtm.Axis; +import com.sun.org.apache.xml.internal.dtm.DTM; +import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator; +import java.io.FilePermission; +import java.util.ArrayList; +import java.util.List; +import jaxp.library.JAXPBaseTest; +import static org.apache.qetest.dtm.QeDtmConst.XML_DIR; +import static org.apache.qetest.dtm.QeDtmConst.createDTM; +import static org.testng.Assert.assertEquals; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +/** + * Basic API test for DTMAxisIterator. Iterator on different Axis type. + * + */ +public class TestDTMIterDeep extends JAXPBaseTest { + /** + * Iterator on different Axis type. + * + * @param axisType axis type. + * @param expectedLastNode expected last node we will validate. + * @param expectedTotal expected total node number we will validate. + */ + @Test(dataProvider = "axisProvider") + public void test(int axisType, int expectedLastNode, int expectedTotal) { + setPermissions(new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.utils"), + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xpath.internal.objects"), + new FilePermission(System.getProperty("test.src") + "/-", "read")); + String deepFile = XML_DIR + "xtestdata/elem10kdeep.xml"; + List lines = new ArrayList<>(); + lines.add("Axis is " + Axis.getNames(axisType).toUpperCase()); + DTM dtm = createDTM(0, deepFile, lines); + + // Get various nodes to use as context nodes. + int DNode = dtm.getFirstChild(dtm.getDocument()); + assertEquals(dtm.getNodeName(dtm.getFirstChild(DNode)), "e1"); + + // Get an iterator for Descendant:: axis. + DTMAxisIterator iter = dtm.getAxisIterator(axisType); + iter.setStartNode(DNode); + int lastNode = 0; + int numOfNodes = 0; + for (int atNode = iter.next(); DTM.NULL != atNode; atNode = iter.next()) { + lastNode = atNode; + numOfNodes = numOfNodes + 1; // Need to know that we Iterated the whole tree + } + assertEquals(lastNode, expectedLastNode); + assertEquals(numOfNodes, expectedTotal); + } + + /** + * Axis types for testing. + * @return an array contains axis type and its expected number. + */ + @DataProvider + public Object[][] axisProvider(){ + return new Object[][]{ + {Axis.DESCENDANT, 75538, 10000}, + {Axis.DESCENDANTORSELF, 75538, 10001}, + {Axis.ANCESTOR, 65536, 1}, + {Axis.ANCESTORORSELF, 65537, 2}, + }; + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/dtm/TestDTMIterator.java 2015-01-09 15:41:36.259116285 -0800 @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.dtm; + +import com.sun.org.apache.xml.internal.dtm.Axis; +import com.sun.org.apache.xml.internal.dtm.DTM; +import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator; +import com.sun.org.apache.xml.internal.dtm.DTMManager; +import com.sun.org.apache.xml.internal.dtm.DTMWSFilter; +import com.sun.org.apache.xml.internal.dtm.ref.DTMManagerDefault; +import com.sun.org.apache.xpath.internal.objects.XMLStringFactoryImpl; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.apache.qetest.dtm.QeDtmConst.GOLDEN_DIR; +import static org.apache.qetest.dtm.QeDtmConst.TYPENAME; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; + +/** + * + * Loads an XML document from a file (or, if no filename is supplied, + * an internal string), then dumps its contents. Replaces the old + * version, which was specific to the ultra-compressed implementation. + */ +public class TestDTMIterator extends JAXPFileBaseTest { + /** + * Test DTMIterator on a well-formed XML string. Checking on expected output. + * @throws IOException if any error on File I/O operation. + */ + @Test + public void test() throws IOException { + setPermissions(new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.utils"), + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xpath.internal.objects")); + String goldFile = GOLDEN_DIR + "TestDTMIterator.out"; + + String defaultSource = "\n" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + + try(StringReader sw = new StringReader(defaultSource)) { + Source source = new StreamSource(sw); + + // Get a DTM manager, and ask it to load the DTM "uniquely", + // with no whitespace filtering, nonincremental, but _with_ + // indexing (a fairly common case, and avoids the special + // mode used for RTF DTMs). + // For testing with some of David Marston's files I do want to strip whitespace. + DTMManager manager = DTMManagerDefault.newInstance(new XMLStringFactoryImpl()); + DTM dtm = manager.getDTM(source, true, (e, d) -> DTMWSFilter.STRIP, false, true); + + // Get various nodes to use as context nodes. + int dtmRoot = dtm.getDocument(); // #document + int DNode = dtm.getFirstChild(dtmRoot); // + int CNode = dtm.getFirstChild(DNode); // + int PINode = dtm.getNextSibling(CNode); // + int ANode = dtm.getNextSibling(PINode); // + int lastNode = 0; + + // Get a Iterator for CHILD:: axis. + DTMAxisIterator iter = dtm.getAxisIterator(Axis.CHILD); + iter.setStartNode(DNode); + + String outputFile = getNextFile(this.getClass()); + + try(PrintWriter pw = new PrintWriter(outputFile)) { + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + lastNode = itNode; + } + + // Get iterator for PARENT:: Axis + iter = dtm.getAxisIterator(Axis.PARENT); + iter.setStartNode(lastNode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + } + + // Get iterator for SELF:: Axis + iter = dtm.getAxisIterator(Axis.SELF); + iter.setStartNode(lastNode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + } + + // Get iterator for NAMESPACE:: Axis + iter = dtm.getAxisIterator(Axis.NAMESPACE); + iter.setStartNode(lastNode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + } + + // Get iterator for PRECEDING:: Axis + iter = dtm.getAxisIterator(Axis.PRECEDING); + iter.setStartNode(lastNode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + } + + // Get iterator for PRECEDINGSIBLING:: Axis + iter = dtm.getAxisIterator(Axis.PRECEDINGSIBLING); + iter.setStartNode(lastNode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + } + + // Get iterator for FOLLOWING:: Axis + iter = dtm.getAxisIterator(Axis.FOLLOWING); + iter.setStartNode(ANode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + } + + // Get iterator for FOLLOWINGSIBLING:: Axis + iter = dtm.getAxisIterator(Axis.FOLLOWINGSIBLING); + iter.setStartNode(ANode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + } + + // Get a iterator for DESCENDANT:: axis. + iter = dtm.getAxisIterator(Axis.DESCENDANT); + iter.setStartNode(ANode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + lastNode = itNode; + } + + // Get iterator for DESCENDANTORSELF:: Axis + iter = dtm.getAxisIterator(Axis.DESCENDANTORSELF); + iter.setStartNode(ANode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + lastNode = itNode; + } + + // The output from Ancestor and Ancestor-or-self is the topic + // of Bugzilla 7886 + // Get iterator for ANCESTOR:: Axis + iter = dtm.getAxisIterator(Axis.ANCESTOR); + iter.setStartNode(lastNode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + } + + // Get iterator for ANCESTORORSELF:: Axis + iter = dtm.getAxisIterator(Axis.ANCESTORORSELF); + iter.setStartNode(lastNode); + + // Iterate the axis and print out node info. + for (int itNode = iter.next(); DTM.NULL != itNode; + itNode = iter.next()) { + printNode(dtm, itNode, " ", pw); + } + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + } + + /** + * Print a node info by given node handle. + * @param dtm DTM instance. + * @param nodeHandle node handle. + * @param indent a format indention. + */ + private void printNode(DTM dtm, int nodeHandle, String indent, PrintWriter pw) { + // Briefly display this node + // Don't bother displaying namespaces or attrs; we do that at the + // next level up. + // %REVIEW% Add namespace info, type info, ... + + // Formatting hack -- suppress quotes when value is null, to distinguish + // it from "null". + String value = dtm.getNodeValue(nodeHandle); + String vq = (value == null) ? "" : "\""; + + // Skip outputing of text nodes. In most cases they clutter the output, + // besides I'm only interested in the elemental structure of the dtm. + if (!"TEXT".equals(TYPENAME[dtm.getNodeType(nodeHandle)])) { + pw.println(indent + + +nodeHandle + ": " + + TYPENAME[dtm.getNodeType(nodeHandle)] + " " + + dtm.getNodeName(nodeHandle) + " " + + " Level=" + dtm.getLevel(nodeHandle) + " " + + "\tValue=" + vq + value + vq + ); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/dtm/TestDTMTrav.java 2015-01-09 15:41:36.535116716 -0800 @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.dtm; + +import com.sun.org.apache.xml.internal.dtm.Axis; +import com.sun.org.apache.xml.internal.dtm.DTM; +import com.sun.org.apache.xml.internal.dtm.DTMAxisTraverser; +import java.io.IOException; +import jaxp.library.JAXPBaseTest; +import static org.apache.qetest.dtm.QeDtmConst.generateDTM; +import static org.apache.qetest.dtm.QeDtmConst.getNodeName; +import static org.testng.Assert.assertEquals; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +/** + * + * Test for Axis Traverser walking. + */ +public class TestDTMTrav extends JAXPBaseTest { + /** + * DTM instance. + */ + private final DTM dtm; + + /* + * Intiate by creating DTM instance and generate initial context. + * + */ + public TestDTMTrav() { + dtm = generateDTM(); + } + + /** + * A provider that provides validation parameters and expected lines. + * + * @return an two dimensional array that provide axis type and expected + * lines. + */ + @DataProvider + public Object[][] travProvider(){ + final Object[][] chkChild = new Object[][] { + { 65542, "COMMENT", "#comment", 3, " Default test document " }, + { 65543, "PROCESSING_INSTRUCTION", "api", 3, "a1=\"yes\" a2=\"no\"" }, + { 65544, "ELEMENT", "A", 3, null }, + { 65554, "ELEMENT", "Aa", 3, null }, + { 65555, "ELEMENT", "Ab", 3, null }, + { 65556, "ELEMENT", "Ac", 3, null }, + { 65558, "ELEMENT", "Ad", 3, null } + }; + + final Object[][] chkParent = new Object[][]{ + {65537, "ELEMENT", "Document", 2, null} + }; + + Object[][] chkSelf = new Object[][]{ + {65558, "ELEMENT", "Ad", 3, null} + }; + + final Object[][] chkNamespace = new Object[][]{ + {65538, "NAMESPACE", "xmlns:xml", 3, "http://www.w3.org/XML/1998/namespace"}, + {65539, "NAMESPACE", "xmlns:d", 3, "www.d.com"}, + {65559, "NAMESPACE", "xmlns:Ad", 4, "www.Ad.com"}, + {65560, "NAMESPACE", "xmlns:y", 4, "www.y.com"}, + {65561, "NAMESPACE", "xmlns:z", 4, "www.z.com"} + }; + + final Object[][] chkNamespaceDecls = new Object[][]{ + {65559, "NAMESPACE", "xmlns:Ad", 4, "www.Ad.com"}, + {65560, "NAMESPACE", "xmlns:y", 4, "www.y.com"}, + {65561, "NAMESPACE", "xmlns:z", 4, "www.z.com"} + }; + + final Object[][] chkPreceding = new Object[][]{ + { 65557, "ELEMENT", "Ac1", 4, null}, + { 65556, "ELEMENT", "Ac", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65554, "ELEMENT", "Aa", 3, null}, + { 65550, "ELEMENT", "F", 8, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65546, "ELEMENT", "B", 4, null}, + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65544, "ELEMENT", "A", 3, null}, + { 65543, "PROCESSING_INSTRUCTION", "api", 3, "a1=\"yes\" a2=\"no\""}, + { 65542, "COMMENT", "#comment", 3, " Default test document "}, + }; + + final Object[][] chkPrecedingsibling = new Object[][]{ + { 65556, "ELEMENT", "Ac", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65554, "ELEMENT", "Aa", 3, null}, + { 65544, "ELEMENT", "A", 3, null}, + { 65543, "PROCESSING_INSTRUCTION", "api", 3, "a1=\"yes\" a2=\"no\""}, + { 65542, "COMMENT", "#comment", 3, " Default test document "} + }; + + final Object[][] chkFollowing = new Object[][]{ + { 65554, "ELEMENT", "Aa", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65556, "ELEMENT", "Ac", 3, null}, + { 65557, "ELEMENT", "Ac1", 4, null}, + { 65558, "ELEMENT", "Ad", 3, null}, + { 65562, "ELEMENT", "Ad1", 4, null} + }; + + final Object[][] checkFollowingSibling = new Object[][]{ + { 65554, "ELEMENT", "Aa", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65556, "ELEMENT", "Ac", 3, null}, + { 65558, "ELEMENT", "Ad", 3, null}, + }; + + final Object[][] checkDescendant = new Object[][]{ + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null} + }; + + final Object[][] checkDescendantSelf = new Object[][]{ + { 65544, "ELEMENT", "A", 3, null}, + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null} + }; + + final Object[][] checkAncestor = new Object[][]{ + { 65549, "ELEMENT", "E", 7, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65546, "ELEMENT", "B", 4, null}, + { 65544, "ELEMENT", "A", 3, null}, + { 65537, "ELEMENT", "Document", 2, null}, + { 65536, "DOCUMENT", "#document", 1, null}, + }; + + final Object[][] checkAncestorSelf = new Object[][]{ + { 65550, "ELEMENT", "F", 8, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65546, "ELEMENT", "B", 4, null}, + { 65544, "ELEMENT", "A", 3, null}, + { 65537, "ELEMENT", "Document", 2, null}, + { 65536, "DOCUMENT", "#document", 1, null} + }; + + final Object[][] checkAllFromNode = new Object[][]{ + { 65550, "ELEMENT", "F", 8, null}, + { 65551, "NAMESPACE", "xmlns:f", 9, "www.f.com"}, + { 65552, "ATTRIBUTE", "a1", 9, "down"}, + { 65553, "ATTRIBUTE", "a2", 9, "up"} + }; + + final Object[][] checkAttribute = new Object[][]{ + { 65540, "ATTRIBUTE", "a1", 3, "hello"}, + { 65541, "ATTRIBUTE", "a2", 3, "goodbye"} + }; + + final Object[][] checkAll = new Object[][]{ + { 65536, "DOCUMENT", "#document", 1, null}, + { 65537, "ELEMENT", "Document", 2, null}, + { 65538, "NAMESPACE", "xmlns:xml", 3, "http://www.w3.org/XML/1998/namespace"}, + { 65539, "NAMESPACE", "xmlns:d", 3, "www.d.com"}, + { 65540, "ATTRIBUTE", "a1", 3, "hello"}, + { 65541, "ATTRIBUTE", "a2", 3, "goodbye"}, + { 65542, "COMMENT", "#comment", 3, " Default test document "}, + { 65543, "PROCESSING_INSTRUCTION", "api", 3, "a1=\"yes\" a2=\"no\""}, + { 65544, "ELEMENT", "A", 3, null}, + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null}, + { 65551, "NAMESPACE", "xmlns:f", 9, "www.f.com"}, + { 65552, "ATTRIBUTE", "a1", 9, "down"}, + { 65553, "ATTRIBUTE", "a2", 9, "up"}, + { 65554, "ELEMENT", "Aa", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65556, "ELEMENT", "Ac", 3, null}, + { 65557, "ELEMENT", "Ac1", 4, null}, + { 65558, "ELEMENT", "Ad", 3, null}, + { 65559, "NAMESPACE", "xmlns:Ad", 4, "www.Ad.com"}, + { 65560, "NAMESPACE", "xmlns:y", 4, "www.y.com"}, + { 65561, "NAMESPACE", "xmlns:z", 4, "www.z.com"}, + { 65562, "ELEMENT", "Ad1", 4, null} + }; + + final Object[][] checkDescentsFromRoot = new Object[][]{ + { 65537, "ELEMENT", "Document", 2, null}, + { 65542, "COMMENT", "#comment", 3, " Default test document "}, + { 65543, "PROCESSING_INSTRUCTION", "api", 3, "a1=\"yes\" a2=\"no\""}, + { 65544, "ELEMENT", "A", 3, null}, + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null}, + { 65554, "ELEMENT", "Aa", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65556, "ELEMENT", "Ac", 3, null}, + { 65557, "ELEMENT", "Ac1", 4, null}, + { 65558, "ELEMENT", "Ad", 3, null}, + { 65562, "ELEMENT", "Ad1", 4, null} + }; + + final Object[][] checkDescentsOrSelfFromRoot = new Object[][]{ + { 65536, "DOCUMENT", "#document", 1, null}, + { 65537, "ELEMENT", "Document", 2, null}, + { 65542, "COMMENT", "#comment", 3, " Default test document "}, + { 65543, "PROCESSING_INSTRUCTION", "api", 3, "a1=\"yes\" a2=\"no\""}, + { 65544, "ELEMENT", "A", 3, null}, + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null}, + { 65554, "ELEMENT", "Aa", 3, null}, + { 65555, "ELEMENT", "Ab", 3, null}, + { 65556, "ELEMENT", "Ac", 3, null}, + { 65557, "ELEMENT", "Ac1", 4, null}, + { 65558, "ELEMENT", "Ad", 3, null}, + { 65562, "ELEMENT", "Ad1", 4, null} + }; + + final Object[][] checkANodeAll = new Object[][]{ + { 65544, "ELEMENT", "A", 3, null}, + { 65545, "COMMENT", "#comment", 4, " A Subtree "}, + { 65546, "ELEMENT", "B", 4, null}, + { 65547, "ELEMENT", "C", 5, null}, + { 65548, "ELEMENT", "D", 6, null}, + { 65549, "ELEMENT", "E", 7, null}, + { 65550, "ELEMENT", "F", 8, null}, + { 65551, "NAMESPACE", "xmlns:f", 9, "www.f.com"}, + { 65552, "ATTRIBUTE", "a1", 9, "down"}, + { 65553, "ATTRIBUTE", "a2", 9, "up"} + }; + + final Object[][] checkCNodeAll = new Object[][]{ + { 65542, "COMMENT", "#comment", 3, " Default test document "} + }; + + return new Object[][]{ + {65537, Axis.CHILD, "Document", chkChild}, + {65558, Axis.PARENT, "Ad", chkParent}, + {65558, Axis.SELF, "Ad", chkSelf}, + {65558, Axis.NAMESPACE, "Ad", chkNamespace}, + {65558, Axis.NAMESPACEDECLS, "Ad", chkNamespaceDecls}, + {65558, Axis.PRECEDING, "Ad", chkPreceding}, + {65558, Axis.PRECEDINGSIBLING, "Ad", chkPrecedingsibling}, + {65558, Axis.FOLLOWING, "Ad", chkFollowing}, + {65558, Axis.FOLLOWINGSIBLING, "Ad", checkFollowingSibling}, + {65544, Axis.DESCENDANT, "A", checkDescendant}, + {65544, Axis.DESCENDANTORSELF, "A", checkDescendantSelf}, + {65550, Axis.ANCESTOR, "F", checkAncestor}, + {65550, Axis.ANCESTORORSELF, "F", checkAncestorSelf}, + {65550, Axis.ALLFROMNODE, "F", checkAllFromNode}, + {65537, Axis.ATTRIBUTE, "Document", checkAttribute}, + {65550, Axis.ALL, "F", checkAll}, + {65550, Axis.DESCENDANTSFROMROOT, "F", checkDescentsFromRoot}, + {65550, Axis.DESCENDANTSORSELFFROMROOT, "F", checkDescentsOrSelfFromRoot}, + {65544, Axis.ALLFROMNODE, "A", checkANodeAll}, + {65542, Axis.ALLFROMNODE, "#comment", checkCNodeAll} + }; + } + + /** + * Walk all kind of AxisTraversers and checking API as expected.. + * + * @param startNode node id to get AxisTraverser. + * @param axisType Axis type. + * @param expectedName expected node name. + * @param expectedLines an two dimensional array that will be validate + * traversal of AxisTraverser + * @throws IOException if any I/O operation error. + */ + @Test(dataProvider = "travProvider") + public void test(int startNode, int axisType, String expectedName, + Object[][] expectedLines) throws IOException { + // This permission is special for the testing. + setPermissions( + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.utils"), + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xpath.internal.objects")); + + // Get a Traverser by given axis type. + assertEquals(dtm.getNodeName(startNode), expectedName); + DTMAxisTraverser at = dtm.getAxisTraverser(axisType); + + int line = 0; + // Traverse the axis and validate API output. + for (int travNode = at.first(startNode); DTM.NULL != travNode; + travNode = at.next(startNode, travNode), line++) { + assertEquals(travNode, expectedLines[line][0]); + assertEquals(getNodeName(dtm, travNode), expectedLines[line][1]); + assertEquals(dtm.getNodeName(travNode), expectedLines[line][2]); + Integer expectedLevel = (Integer)expectedLines[line][3]; + assertEquals(dtm.getLevel(travNode), expectedLevel.shortValue()); + assertEquals(dtm.getNodeValue(travNode), expectedLines[line][4]); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/dtm/TestDTMTravDeep.java 2015-01-09 15:41:36.830117176 -0800 @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.dtm; + +import com.sun.org.apache.xml.internal.dtm.Axis; +import com.sun.org.apache.xml.internal.dtm.DTM; +import com.sun.org.apache.xml.internal.dtm.DTMAxisTraverser; +import java.io.FilePermission; +import java.util.ArrayList; +import java.util.List; +import jaxp.library.JAXPBaseTest; +import static org.apache.qetest.dtm.QeDtmConst.XML_DIR; +import static org.apache.qetest.dtm.QeDtmConst.createDTM; +import static org.testng.Assert.assertEquals; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +/** + * Basic API test for DTMAxisTraverser. Traverser on different Axis type. + * + */ +public class TestDTMTravDeep extends JAXPBaseTest { + /** + * Traverser on different Axis type. + * @param axisType axis type. + * @param expectedLastNode expected last node we will validate. + * @param expectedTotal expected total node number we will validate. + */ + @Test(dataProvider = "axisProvider") + public void test(int axisType, int expectedLastNode, int expectedTotal) { + setPermissions(new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.utils"), + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xpath.internal.objects"), + new FilePermission(System.getProperty("test.src") + "/-", "read")); + String deepFile = XML_DIR + "xtestdata/elem10kdeep.xml"; + + List lines = new ArrayList<>(); + lines.add("Axis is " + Axis.getNames(axisType).toUpperCase()); + DTM dtm = createDTM(0, deepFile, lines); + // Get various nodes to use as context nodes. + int dtmRoot = dtm.getDocument(); // #document + int DNode = dtm.getFirstChild(dtmRoot); // + // returns Traversal time, last node, number of nodes traversed + assertEquals(dtm.getNodeName(dtm.getFirstChild(DNode)), "e1"); + + // Get a iterator for Descendant:: axis. + DTMAxisTraverser trav = dtm.getAxisTraverser(Axis.DESCENDANT); + int lastNode = 0; + int numOfNodes = 0; + for (int atNode = trav.first(axisType); DTM.NULL != atNode; + atNode = trav.next(DNode, axisType)) { + lastNode = atNode; + numOfNodes = numOfNodes + 1; + } + assertEquals(lastNode, expectedLastNode); + assertEquals(numOfNodes, expectedTotal); + } + + /** + * Axis types for testing. + * @return an array contains axis type and its expected number. + */ + @DataProvider + public Object[][] axisProvider(){ + return new Object[][]{ + { Axis.DESCENDANT, 65536, 1}, + { Axis.DESCENDANTORSELF, 65536, 1}, + { Axis.ANCESTOR, 65536, 1}, + { Axis.ANCESTORORSELF, 65536, 1}, + }; + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/dtm/content/xtestdata/elem10kdeep.xml 2015-01-09 15:41:37.135117651 -0800 @@ -0,0 +1,2 @@ + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/dtm/golden/DTM_testcase1.out 2015-01-09 15:41:37.419118094 -0800 @@ -0,0 +1,106 @@ + *** DOCUMENT PROPERTIES: *** +DocURI="null" SystemID="null" +StandAlone="null" DocVersion="null" + + *** DOCUMENT DATA: *** +65536: DOCUMENT : #document" E-Type=9 Level=1 Value=null + Prefix= "" Name= "" URI= "null" Parent=-1 1stChild=65537 NextSib=-1 +65537: ELEMENT bdd:dummyDocument : bdd:dummyDocument" E-Type=14 Level=2 Value=null + Prefix= "bdd" Name= "dummyDocument" URI= "www.bdd.org" Parent=65536 1stChild=65541 NextSib=-1 + NAMESPACES: + 65538: NAMESPACE xml : xmlns:xml" E-Type=15 Level=3 Value="http://www.w3.org/XML/1998/namespace" + Prefix= "" Name= "xml" URI= "null" Parent=65537 1stChild=-1 NextSib=65539 + 65539: NAMESPACE bdd : xmlns:bdd" E-Type=16 Level=3 Value="www.bdd.org" + Prefix= "" Name= "bdd" URI= "null" Parent=65537 1stChild=-1 NextSib=65540 + ATTRIBUTES: + 65540: ATTRIBUTE version : version" E-Type=17 Level=3 Value="99" + Prefix= "" Name= "version" URI= "null" Parent=65537 1stChild=-1 NextSib=-1 +65541: COMMENT : #comment" E-Type=8 Level=3 Value=" Default test document " + Prefix= "" Name= "" URI= "null" Parent=65537 1stChild=-1 NextSib=65542 +65542: TEXT : #text" E-Type=3 Level=3 Value=" & " + Prefix= "" Name= "" URI= "null" Parent=65537 1stChild=-1 NextSib=65543 +65543: PROCESSING_INSTRUCTION api : api" E-Type=18 Level=3 Value="attrib1="yes" attrib2="no"" + Prefix= "" Name= "api" URI= "null" Parent=65537 1stChild=-1 NextSib=65544 +65544: ELEMENT A : A" E-Type=19 Level=3 Value=null + Prefix= "" Name= "A" URI= "null" Parent=65537 1stChild=65545 NextSib=65550 +65545: ELEMENT B : B" E-Type=20 Level=4 Value=null + Prefix= "" Name= "B" URI= "null" Parent=65544 1stChild=65549 NextSib=-1 + ATTRIBUTES: + 65546: ATTRIBUTE hat : hat" E-Type=21 Level=5 Value="new" + Prefix= "" Name= "hat" URI= "null" Parent=65545 1stChild=-1 NextSib=65547 + 65547: ATTRIBUTE car : car" E-Type=22 Level=5 Value="Honda" + Prefix= "" Name= "car" URI= "null" Parent=65545 1stChild=-1 NextSib=65548 + 65548: ATTRIBUTE dog : dog" E-Type=23 Level=5 Value="Boxer" + Prefix= "" Name= "dog" URI= "null" Parent=65545 1stChild=-1 NextSib=-1 +65549: TEXT : #text" E-Type=3 Level=5 Value="Life is good" + Prefix= "" Name= "" URI= "null" Parent=65545 1stChild=-1 NextSib=-1 +65550: ELEMENT C : C" E-Type=24 Level=3 Value=null + Prefix= "" Name= "C" URI= "null" Parent=65537 1stChild=65551 NextSib=65555 +65551: TEXT : #text" E-Type=3 Level=4 Value="My Anaconda" + Prefix= "" Name= "" URI= "null" Parent=65550 1stChild=-1 NextSib=65552 +65552: ELEMENT xyz:D : xyz:D" E-Type=25 Level=4 Value=null + Prefix= "xyz" Name= "D" URI= "www.xyz.org" Parent=65550 1stChild=-1 NextSib=65554 + NAMESPACES: + 65553: NAMESPACE xyz : xmlns:xyz" E-Type=26 Level=5 Value="www.xyz.org" + Prefix= "" Name= "xyz" URI= "null" Parent=65552 1stChild=-1 NextSib=-1 +65554: TEXT : #text" E-Type=3 Level=4 Value="Words" + Prefix= "" Name= "" URI= "null" Parent=65550 1stChild=-1 NextSib=-1 +65555: TEXT : #text" E-Type=3 Level=3 Value=" + Want a more interesting docuent, provide the URI on the command line! + " + Prefix= "" Name= "" URI= "null" Parent=65537 1stChild=-1 NextSib=65556 +65556: ELEMENT Sub-Doc : Sub-Doc" E-Type=27 Level=3 Value=null + Prefix= "" Name= "Sub-Doc" URI= "null" Parent=65537 1stChild=65560 NextSib=-1 + NAMESPACES: + 65557: NAMESPACE d : xmlns:d" E-Type=28 Level=4 Value="www.d.com" + Prefix= "" Name= "d" URI= "null" Parent=65556 1stChild=-1 NextSib=65558 + ATTRIBUTES: + 65558: ATTRIBUTE a1 : a1" E-Type=29 Level=4 Value="hello" + Prefix= "" Name= "a1" URI= "null" Parent=65556 1stChild=-1 NextSib=65559 + 65559: ATTRIBUTE a2 : a2" E-Type=30 Level=4 Value="goodbye" + Prefix= "" Name= "a2" URI= "null" Parent=65556 1stChild=-1 NextSib=-1 +65560: COMMENT : #comment" E-Type=8 Level=4 Value=" Default test Subdocument " + Prefix= "" Name= "" URI= "null" Parent=65556 1stChild=-1 NextSib=65561 +65561: PROCESSING_INSTRUCTION api : api" E-Type=18 Level=4 Value="a1="yes" a2="no"" + Prefix= "" Name= "api" URI= "null" Parent=65556 1stChild=-1 NextSib=65562 +65562: ELEMENT A : A" E-Type=19 Level=4 Value=null + Prefix= "" Name= "A" URI= "null" Parent=65556 1stChild=65563 NextSib=65572 +65563: COMMENT : #comment" E-Type=8 Level=5 Value=" A Subtree " + Prefix= "" Name= "" URI= "null" Parent=65562 1stChild=-1 NextSib=65564 +65564: ELEMENT B : B" E-Type=20 Level=5 Value=null + Prefix= "" Name= "B" URI= "null" Parent=65562 1stChild=65565 NextSib=-1 +65565: ELEMENT C : C" E-Type=24 Level=6 Value=null + Prefix= "" Name= "C" URI= "null" Parent=65564 1stChild=65566 NextSib=-1 +65566: ELEMENT D : D" E-Type=31 Level=7 Value=null + Prefix= "" Name= "D" URI= "null" Parent=65565 1stChild=65567 NextSib=-1 +65567: ELEMENT E : E" E-Type=32 Level=8 Value=null + Prefix= "" Name= "E" URI= "null" Parent=65566 1stChild=65568 NextSib=-1 +65568: ELEMENT f:F : f:F" E-Type=33 Level=9 Value=null + Prefix= "f" Name= "F" URI= "www.f.com" Parent=65567 1stChild=-1 NextSib=-1 + NAMESPACES: + 65569: NAMESPACE f : xmlns:f" E-Type=34 Level=10 Value="www.f.com" + Prefix= "" Name= "f" URI= "null" Parent=65568 1stChild=-1 NextSib=65570 + ATTRIBUTES: + 65570: ATTRIBUTE a1 : a1" E-Type=29 Level=10 Value="down" + Prefix= "" Name= "a1" URI= "null" Parent=65568 1stChild=-1 NextSib=65571 + 65571: ATTRIBUTE a2 : a2" E-Type=30 Level=10 Value="up" + Prefix= "" Name= "a2" URI= "null" Parent=65568 1stChild=-1 NextSib=-1 +65572: ELEMENT Aa : Aa" E-Type=35 Level=4 Value=null + Prefix= "" Name= "Aa" URI= "null" Parent=65556 1stChild=-1 NextSib=65573 +65573: ELEMENT Ab : Ab" E-Type=36 Level=4 Value=null + Prefix= "" Name= "Ab" URI= "null" Parent=65556 1stChild=-1 NextSib=65574 +65574: ELEMENT Ac : Ac" E-Type=37 Level=4 Value=null + Prefix= "" Name= "Ac" URI= "null" Parent=65556 1stChild=65575 NextSib=65576 +65575: ELEMENT Ac1 : Ac1" E-Type=38 Level=5 Value=null + Prefix= "" Name= "Ac1" URI= "null" Parent=65574 1stChild=-1 NextSib=-1 +65576: ELEMENT Ad:Ad : Ad:Ad" E-Type=39 Level=4 Value=null + Prefix= "Ad" Name= "Ad" URI= "www.Ad.com" Parent=65556 1stChild=65580 NextSib=-1 + NAMESPACES: + 65577: NAMESPACE Ad : xmlns:Ad" E-Type=40 Level=5 Value="www.Ad.com" + Prefix= "" Name= "Ad" URI= "null" Parent=65576 1stChild=-1 NextSib=65578 + 65578: NAMESPACE y : xmlns:y" E-Type=41 Level=5 Value="www.y.com" + Prefix= "" Name= "y" URI= "null" Parent=65576 1stChild=-1 NextSib=65579 + 65579: NAMESPACE z : xmlns:z" E-Type=42 Level=5 Value="www.z.com" + Prefix= "" Name= "z" URI= "null" Parent=65576 1stChild=-1 NextSib=-1 +65580: ELEMENT Ad1 : Ad1" E-Type=43 Level=5 Value=null + Prefix= "" Name= "Ad1" URI= "null" Parent=65576 1stChild=-1 NextSib=-1 --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/dtm/golden/TestDTMIterator.out 2015-01-09 15:41:37.716118557 -0800 @@ -0,0 +1,71 @@ + 65542: COMMENT #comment Level=3 Value=" Default test document " + 65543: PROCESSING_INSTRUCTION api Level=3 Value="a1="yes" a2="no"" + 65544: ELEMENT A Level=3 Value=null + 65554: ELEMENT Aa Level=3 Value=null + 65555: ELEMENT Ab Level=3 Value=null + 65556: ELEMENT Ac Level=3 Value=null + 65558: ELEMENT Ad Level=3 Value=null + 65537: ELEMENT Document Level=2 Value=null + 65558: ELEMENT Ad Level=3 Value=null + 65538: NAMESPACE xmlns:xml Level=3 Value="http://www.w3.org/XML/1998/namespace" + 65539: NAMESPACE xmlns:d Level=3 Value="www.d.com" + 65559: NAMESPACE xmlns:Ad Level=4 Value="www.Ad.com" + 65560: NAMESPACE xmlns:y Level=4 Value="www.y.com" + 65561: NAMESPACE xmlns:z Level=4 Value="www.z.com" + 65542: COMMENT #comment Level=3 Value=" Default test document " + 65543: PROCESSING_INSTRUCTION api Level=3 Value="a1="yes" a2="no"" + 65544: ELEMENT A Level=3 Value=null + 65545: COMMENT #comment Level=4 Value=" A Subtree " + 65546: ELEMENT B Level=4 Value=null + 65547: ELEMENT C Level=5 Value=null + 65548: ELEMENT D Level=6 Value=null + 65549: ELEMENT E Level=7 Value=null + 65550: ELEMENT F Level=8 Value=null + 65554: ELEMENT Aa Level=3 Value=null + 65555: ELEMENT Ab Level=3 Value=null + 65556: ELEMENT Ac Level=3 Value=null + 65557: ELEMENT Ac1 Level=4 Value=null + 65542: COMMENT #comment Level=3 Value=" Default test document " + 65543: PROCESSING_INSTRUCTION api Level=3 Value="a1="yes" a2="no"" + 65544: ELEMENT A Level=3 Value=null + 65554: ELEMENT Aa Level=3 Value=null + 65555: ELEMENT Ab Level=3 Value=null + 65556: ELEMENT Ac Level=3 Value=null + 65554: ELEMENT Aa Level=3 Value=null + 65555: ELEMENT Ab Level=3 Value=null + 65556: ELEMENT Ac Level=3 Value=null + 65557: ELEMENT Ac1 Level=4 Value=null + 65558: ELEMENT Ad Level=3 Value=null + 65562: ELEMENT Ad1 Level=4 Value=null + 65554: ELEMENT Aa Level=3 Value=null + 65555: ELEMENT Ab Level=3 Value=null + 65556: ELEMENT Ac Level=3 Value=null + 65558: ELEMENT Ad Level=3 Value=null + 65545: COMMENT #comment Level=4 Value=" A Subtree " + 65546: ELEMENT B Level=4 Value=null + 65547: ELEMENT C Level=5 Value=null + 65548: ELEMENT D Level=6 Value=null + 65549: ELEMENT E Level=7 Value=null + 65550: ELEMENT F Level=8 Value=null + 65544: ELEMENT A Level=3 Value=null + 65545: COMMENT #comment Level=4 Value=" A Subtree " + 65546: ELEMENT B Level=4 Value=null + 65547: ELEMENT C Level=5 Value=null + 65548: ELEMENT D Level=6 Value=null + 65549: ELEMENT E Level=7 Value=null + 65550: ELEMENT F Level=8 Value=null + 65536: DOCUMENT #document Level=1 Value=null + 65537: ELEMENT Document Level=2 Value=null + 65544: ELEMENT A Level=3 Value=null + 65546: ELEMENT B Level=4 Value=null + 65547: ELEMENT C Level=5 Value=null + 65548: ELEMENT D Level=6 Value=null + 65549: ELEMENT E Level=7 Value=null + 65536: DOCUMENT #document Level=1 Value=null + 65537: ELEMENT Document Level=2 Value=null + 65544: ELEMENT A Level=3 Value=null + 65546: ELEMENT B Level=4 Value=null + 65547: ELEMENT C Level=5 Value=null + 65548: ELEMENT D Level=6 Value=null + 65549: ELEMENT E Level=7 Value=null + 65550: ELEMENT F Level=8 Value=null \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/EmbeddedStylesheetTest.java 2015-01-09 15:41:37.971118955 -0800 @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import javax.xml.transform.Source; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static org.testng.Assert.assertNull; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class EmbeddedStylesheetTest extends JAXPFileBaseTest { + /** + * Simple XML documents with xml-stylesheet PI's. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase1() throws Exception { + setPermissions(new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.utils"), + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xpath.internal.objects")); + String xmlName = XML_DIR + "embeddedIdentity.xml"; + String goldFile = GOLDEN_DIR + "embeddedIdentity.out"; + String outputFile = USER_DIR + "embeddedIdentity.out"; + + TransformerFactory factory = TransformerFactory.newInstance(); + Source stylesheet = factory.getAssociatedStylesheet( + new StreamSource(filenameToURL(xmlName)), null, null, null); + Templates embedTemplates = factory.newTemplates(stylesheet); + Transformer embedTransformer = embedTemplates.newTransformer(); + embedTransformer.transform( + new StreamSource(filenameToURL(xmlName)), + new StreamResult(outputFile)); + compareWithGold(goldFile, outputFile); + } + + /** + * Data provider for testCase2. + * @return two dimensional array that provide parameters as output file, + * golden file, title, media. + */ + @DataProvider + public static Object[][] titleMediaProvider() { + return new Object[][]{ + {"EmbeddedRelative0.out", "EmbeddedRelative0.out", null, "bar/media"}, + {"EmbeddedRelative1.out", "EmbeddedRelative1.out", null, "foo/media"}, + {"EmbeddedRelative0.out", "EmbeddedRelative0.out", "bar-title", null}, + {"EmbeddedRelative1.out", "EmbeddedRelative1.out", "foo-title", null}, + {"EmbeddedRelative2.out", "EmbeddedRelative2.out", null, "alt/media"} + }; + } + + /** + * Test media, title, character set types of xml-stylesheet PI's. + * + * @param outputFileName output file name. + * @param goldFileName golden validation file name. + * @param media The media attribute to be matched. May be null, in which + * case the prefered templates will be used (i.e. alternate = no). + * @param title The value of the title attribute to match. May be null. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "titleMediaProvider") + public void testCase2(String outputFileName, String goldFileName, + String title, String media) throws Exception { + String mediaTitleName = XML_DIR + "EmbeddedMediaTitle.xml"; + String outputFile = USER_DIR + outputFileName; + String goldFile = GOLDEN_DIR + goldFileName; + + TransformerFactory factory = TransformerFactory.newInstance(); + Source xslSrc = factory.getAssociatedStylesheet( + new StreamSource(filenameToURL(mediaTitleName)), + media, title, null); + factory.newTransformer(xslSrc).transform( + new StreamSource(filenameToURL(mediaTitleName)), + new StreamResult(outputFile)); + compareWithGold(goldFile, outputFile); + } + + @DataProvider + public Object[][] invalidTitleMedia() { + return new Object[][] { + {"title-not-found", null}, + {null, "media/notfound"}, + {"alt-title", "media/notfound"}, + {"title-not-found", "alt/media"} + }; + } + + /** + * Expect null if invalid title or media. + * + * @param media The media attribute to be matched. May be null, in which + * case the prefered templates will be used (i.e. alternate = no). + * @param title The value of the title attribute to match. May be null. + * @throws TransformerConfigurationException Thrown in case of {@linkplain + * java.util.ServiceConfigurationError service configuration error} or if + * the implementation is not available or cannot be instantiated. + */ + @Test(dataProvider = "invalidTitleMedia") + public void checkNull(String title, String media) + throws TransformerConfigurationException { + String mediaTitleName = XML_DIR + "EmbeddedMediaTitle.xml"; + TransformerFactory factory = TransformerFactory.newInstance(); + Source xslSrc = factory.getAssociatedStylesheet( + new StreamSource(filenameToURL(mediaTitleName)), + media, title, null); + assertNull(xslSrc); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/ErrorListenerAPITest.java 2015-01-09 15:41:38.237119370 -0800 @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import com.sun.org.apache.xml.internal.utils.DefaultErrorHandler; +import javax.xml.transform.TransformerException; +import jaxp.library.JAXPBaseTest; +import static org.testng.Assert.assertNotNull; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +/** + * API Coverage test for ErrorListener. + */ +public class ErrorListenerAPITest extends JAXPBaseTest { + /** + * All test method need access internal package + * com.sun.org.apache.xml.internal.utils and + * com.sun.org.apache.xpath.internal.objects. + */ + @BeforeMethod + public void inititalize() { + setPermissions(new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.utils"), + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xpath.internal.objects")); + } + /** + * Root exception wrap message. + */ + private final String EXP_MSG = "Exception-message-here"; + + /** + * Transformer exception wrap message. + */ + private final String TRANSFORMER_EXP_MSG = "TransformerException-message-here"; + + /** + * Default behavior of DefaultErrorHandler.warning is doing nothing. + * + * @throws TransformerException Any SAX exception, possibly wrapping another + * exception. + */ + @Test + public void testWarning() throws TransformerException { + DefaultErrorHandler deh = new DefaultErrorHandler(); + assertNotNull(deh); + + Exception ex = new Exception(EXP_MSG); + TransformerException tex = new TransformerException(TRANSFORMER_EXP_MSG, ex); + deh.warning(tex); + } + + /** + * Default behavior of DefaultErrorHandler.error is throwing out the + * TransformerException. + * + * @throws TransformerException Any SAX exception, possibly wrapping another + * exception. + */ + @Test(expectedExceptions = TransformerException.class) + public void testError() throws TransformerException { + DefaultErrorHandler deh = new DefaultErrorHandler(); + assertNotNull(deh); + + Exception ex = new Exception(EXP_MSG); + TransformerException tex = new TransformerException(TRANSFORMER_EXP_MSG, ex); + deh.error(tex); + } + + /** + * Default behavior of DefaultErrorHandler.fatalError is throwing out the + * TransformerException. + * + * @throws TransformerException Any SAX exception, possibly wrapping another + * exception. + */ + @Test(expectedExceptions = TransformerException.class) + public void testFatalError() throws TransformerException { + DefaultErrorHandler deh = new DefaultErrorHandler(); + assertNotNull(deh); + + Exception ex = new Exception(EXP_MSG); + TransformerException tex = new TransformerException(TRANSFORMER_EXP_MSG, ex); + deh.fatalError(tex); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/ErrorListenerTest.java 2015-01-09 15:41:38.508119792 -0800 @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Result; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.SAXSource; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.apache.qetest.CheckingHandler.Expectation.ITEM_CHECKFAIL; +import static org.apache.qetest.trax.CheckingErrorListener.THROW_NEVER; +import static org.apache.qetest.trax.CheckingErrorListener.TYPE_FATALERROR; +import static org.apache.qetest.trax.CheckingErrorListener.TYPE_WARNING; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import org.apache.qetest.xsl.CheckingSAXErrorHandler; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; + +/** + * Verify that ErrorListeners are called properly from Transformers. Also + * verifies basic Transformer behavior after a stylesheet with errors has been + * built. Note: parts of this test may rely on specific Xalan functionality, in + * that with the specific errors I've chosen, Xalan can actually continue to + * process the stylesheet, even though it had an error. XSLTC mode may either + * throw slighly different kinds of errors, or may not be able to continue after + * the error (we should investigate changing this test to just verify common + * things, and then check the rest into the xalanj2 directory). + */ +public class ErrorListenerTest extends JAXPFileBaseTest { + /** + * Expect fatal when transformation by default. + */ + private static final int TEMPLATES_EXPECTED_TYPE = TYPE_FATALERROR; + + /** + * Expect warning when transformation by default. + */ + private static final int TRANSFORM_EXPECTED_TYPE = TYPE_WARNING; + + /** + * Data provide provides test XML, stylesheet and output files name. + * @return an array has XML, stylesheet and output files name. + */ + @DataProvider + public Object[][] testFiles(){ + return new Object[][]{ + {XML_DIR + "ErrorListenerTest.xml", + XML_DIR + "ErrorListenerTest.xsl", + GOLDEN_DIR + "ErrorListenerTest.out"} + }; + } + + /** + * TransformerFactory Set/Get ErrorListener test. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "testFiles") + public void testCase1(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + + CheckingErrorListener chkErrorListener = new CheckingErrorListener(THROW_NEVER); + + TransformerFactory factory = TransformerFactory.newInstance(); + // Set the errorListener and validate it + factory.setErrorListener(chkErrorListener); + + // Attempt to build templates from known-bad stylesheet + // Validate known errors in stylesheet building + chkErrorListener.setExpected(TEMPLATES_EXPECTED_TYPE, + ITEM_CHECKFAIL); + Templates templates = factory.newTemplates(new StreamSource(filenameToURL(xslFile))); + // Clear out any setExpected or counters + chkErrorListener.reset(); + + // This stylesheet will still work, even though errors + // were detected during it's building. Note that + // future versions of Xalan or other processors may + // not be able to continue here... + Transformer transformer = templates.newTransformer(); + + // Set the errorListener and validate it + transformer.setErrorListener(chkErrorListener); + + // Validate the first xsl:message call in the stylesheet + chkErrorListener.setExpected(TRANSFORM_EXPECTED_TYPE, + ITEM_CHECKFAIL); + transformer.transform(new StreamSource(filenameToURL(xmlFile)), + new StreamResult(outputFile)); + // Clear out any setExpected or counters + chkErrorListener.reset(); + compareWithGold(goldFile, outputFile); + } + + /** + * Build a bad style-sheet/do a transform with DOMs. Verify that the + * ErrorListener is called properly. Primarily using SAXSources. + * + * @param xmlFile test XML filename. + * @param xslFile test style-sheet filename. + * @param goldFile golden verification filename. + * + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "testFiles") + public void testCase2(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + + CheckingErrorListener loggingErrorListener = new CheckingErrorListener(THROW_NEVER); + // assumes SAXSource.feature! + SAXTransformerFactory saxFactory = (SAXTransformerFactory)TransformerFactory.newInstance(); + + // Set the errorListener and validate it + saxFactory.setErrorListener(loggingErrorListener); + + // Use the JAXP way to get an XMLReader + XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + InputSource is = new InputSource(filenameToURL(xslFile)); + + // Attempt to build templates from known-bad stylesheet + // Validate known errors in stylesheet building + loggingErrorListener.setExpected(TEMPLATES_EXPECTED_TYPE, + ITEM_CHECKFAIL); + TransformerHandler handler = saxFactory.newTransformerHandler(new SAXSource(is)); + // Clear out any setExpected or counters + loggingErrorListener.reset(); + + // This stylesheet will still work, even though errors + // were detected during it's building. Note that + // future versions of Xalan or other processors may + // not be able to continue here... + + // Create a result and setup SAX parsing 'tree' + Result result = new StreamResult(outputFile); + handler.setResult(result); + reader.setContentHandler(handler); + + CheckingSAXErrorHandler loggingSAXErrorHandler + = new CheckingSAXErrorHandler(CheckingSAXErrorHandler.THROW_NEVER); + reader.setErrorHandler(loggingSAXErrorHandler); + + // Validate the first xsl:message call in the stylesheet + loggingErrorListener.setExpected(TRANSFORM_EXPECTED_TYPE, + ITEM_CHECKFAIL); + reader.parse(filenameToURL(xmlFile)); + // Clear out any setExpected or counters + loggingErrorListener.reset(); + loggingSAXErrorHandler.reset(); + compareWithGold(goldFile, outputFile); + } + + /** + * Build a bad style-sheet/do a transform with DOMs. Verify that the + * ErrorListener is called properly. Primarily using DOMSources. + * + * @param xmlFile test XML filename. + * @param xslFile test style-sheet filename. + * @param goldFile golden verification filename. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "testFiles") + public void testCase3(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + CheckingErrorListener chkErrorListener = new CheckingErrorListener(THROW_NEVER); + // Startup a DOM factory, create some nodes/DOMs + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node xslNode = docBuilder.parse(new InputSource(filenameToURL(xslFile))); + Node xmlNode = docBuilder.parse(new InputSource(filenameToURL(xmlFile))); + + // Create a transformer factory with an error listener + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setErrorListener(chkErrorListener); + + // Attempt to build templates from known-bad stylesheet + // Validate known errors in stylesheet building + Templates templates = factory.newTemplates(new DOMSource(xslNode)); + // Clear out any setExpected or counters + Transformer transformer = templates.newTransformer(); + transformer.setErrorListener(chkErrorListener); + transformer.transform(new DOMSource(xmlNode), new StreamResult(outputFile)); + compareWithGold(goldFile, outputFile); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/ExamplesTest.java 2015-01-09 15:41:38.786120226 -0800 @@ -0,0 +1,499 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory; +import com.sun.org.apache.xml.internal.serializer.Serializer; +import com.sun.org.apache.xml.internal.serializer.SerializerFactory; +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.Properties; +import java.util.PropertyPermission; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Result; +import javax.xml.transform.Templates; +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.sax.SAXResult; +import javax.xml.transform.sax.SAXSource; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.*; +import org.testng.annotations.Test; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.XMLFilter; +import org.xml.sax.XMLReader; + +/** + * Test version of xml-xalan/java/samples/trax/Examples.java. + * This file is essentially copied from the Examples for TRAX, or + * javax.xml.transform; however this file actually validates most output and + * behavior for correctness. + */ +public class ExamplesTest extends JAXPFileBaseTest { + /** + * Test XML file 1 name. + */ + private static final String SOURCE_ID = XML_DIR + "xml/foo.xml"; + + /** + * Test XML file 2 name. + */ + private static final String SOURCE_ID2 = XML_DIR + "xml/baz.xml"; + + /** + * Test stylesheet file name. + */ + private static final String XSL_ID = XML_DIR + "xsl/foo.xsl"; + + /** + * Show the Transformer as a simple XMLFilter. This is pretty similar to + * exampleXMLReader, except that here the parent XMLReader is created by the + * caller, instead of automatically within the XMLFilter. This gives the + * caller more direct control over the parent reader. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleXMLFilter() throws Exception { + String outputFile = getNextFile(this.getClass()); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + + TransformerFactory tfactory = TransformerFactory.newInstance(); + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + SAXParser jaxpParser = factory.newSAXParser(); + XMLReader reader = jaxpParser.getXMLReader(); + + // Set the result handling to be a serialization to the file output stream. + Serializer serializer = SerializerFactory.getSerializer( + OutputPropertiesFactory.getDefaultMethodProperties("xml")); + serializer.setOutputStream(fos); + reader.setContentHandler(serializer.asContentHandler()); + reader.setFeature("http://xml.org/sax/features/namespace-prefixes", + true); + reader.setFeature("http://apache.org/xml/features/validation/dynamic", + true); + XMLFilter filter = ((SAXTransformerFactory) tfactory) + .newXMLFilter(new StreamSource(filenameToURL(XSL_ID))); + filter.setParent(reader); + + // Now, when you call transformer.parse, it will set itself as + // the content handler for the parser object (it's "parent"), and + // will then call the parse method on the parser. + filter.parse(new InputSource(filenameToURL(SOURCE_ID))); + } + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_14.out", outputFile)); + } + + /** + * Show simple transformation from reader to output stream. In general this + * use case is discouraged, since the XML encoding can not be processed. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleFromReader() throws Exception { + String outputFile = getNextFile(this.getClass()); + // Create a transform factory instance. + TransformerFactory tfactory = TransformerFactory.newInstance(); + + // Note that in this case the XML encoding can not be processed! + Reader xslReader = new BufferedReader(new InputStreamReader(new FileInputStream(XSL_ID), "UTF-8")); + StreamSource xslSource = new StreamSource(xslReader); + // Note that if we don't do this, relative URLs can not be resolved correctly! + xslSource.setSystemId(filenameToURL(XSL_ID)); + + // Create a transformer for the stylesheet. + Transformer transformer = tfactory.newTransformer(xslSource); + + Reader xmlReader = new BufferedReader(new InputStreamReader(new FileInputStream(SOURCE_ID), "UTF-8")); + StreamSource xmlSource = new StreamSource(xmlReader); + // Note that if we don't do this, relative URLs can not be resolved correctly! + xmlSource.setSystemId(filenameToURL(SOURCE_ID)); + + // Transform the source XML to output file. + transformer.transform(xmlSource, new StreamResult(outputFile)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_5.out", outputFile)); + } + + /** + * Show the Transformer using SAX events in and SAX events out. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleContentHandlerToContentHandler() throws Exception { + TransformerFactory tfactory = TransformerFactory.newInstance(); + String outputFile = getNextFile(this.getClass()); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + // Does this factory support SAX features? + if (!tfactory.getFeature(SAXSource.FEATURE)) { + return; + } + // If so, we can safely cast. + SAXTransformerFactory stfactory = (SAXTransformerFactory) tfactory; + + // A TransformerHandler is a ContentHandler that will listen for + // SAX events, and transform them to the result. + TransformerHandler handler + = stfactory.newTransformerHandler(new StreamSource(filenameToURL(XSL_ID))); + + // Set the result handling to be a serialization to the file output stream. + Serializer serializer = SerializerFactory.getSerializer( + OutputPropertiesFactory.getDefaultMethodProperties("xml")); + serializer.setOutputStream(fos); + Result result = new SAXResult(serializer.asContentHandler()); + + handler.setResult(result); + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + XMLReader reader = factory.newSAXParser().getXMLReader(); + reader.setContentHandler(handler); + + // It's a good idea for the parser to send lexical events. + // The TransformerHandler is also a LexicalHandler. + reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); + + // Parse the source XML, and send the parse events to the TransformerHandler. + reader.parse(filenameToURL(SOURCE_ID)); + } + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_3.out", outputFile)); + } + + /** + * Show the Transformer using SAX events in and DOM nodes out. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleContentHandler2DOM() throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + + // Make sure the transformer factory we obtained supports both + // DOM and SAX. + if (!(tfactory.getFeature(SAXSource.FEATURE) + && tfactory.getFeature(DOMSource.FEATURE))) { + return; + } + // We can now safely cast to a SAXTransformerFactory. + SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory; + + // Create an Document node as the root for the output. + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + org.w3c.dom.Document outNode = docBuilder.newDocument(); + + // Create a ContentHandler that can liston to SAX events + // and transform the output to DOM nodes. + TransformerHandler handler + = sfactory.newTransformerHandler(new StreamSource(filenameToURL(XSL_ID))); + handler.setResult(new DOMResult(outNode)); + + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + XMLReader reader = factory.newSAXParser().getXMLReader(); + reader.setContentHandler(handler); + reader.setProperty("http://xml.org/sax/properties/lexical-handler", + handler); + + // Send the SAX events from the parser to the transformer, + // and thus to the DOM tree. + reader.parse(filenameToURL(SOURCE_ID)); + + // Serialize the node for diagnosis. + // This serializes to outNames.nextName() + Transformer serializer = tfactory.newTransformer(); + serializer.setOutputProperty(OutputKeys.INDENT, "yes"); + serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + serializer.transform(new DOMSource(outNode), + new StreamResult(outputFile)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_2.out", outputFile)); + } + + /** + * A fuller example showing how the TrAX interface can be used to serialize + * a DOM tree. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleAsSerializer() throws Exception { + String outputFile = getNextFile(this.getClass()); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + org.w3c.dom.Document outNode = docBuilder.newDocument(); + Node doc = docBuilder.parse(new InputSource(filenameToURL(SOURCE_ID))); + + TransformerFactory tfactory = TransformerFactory.newInstance(); + + // This creates a transformer that does a simple identity transform, + // and thus can be used for all intents and purposes as a serializer. + Transformer serializer = tfactory.newTransformer(); + + Properties oprops = new Properties(); + oprops.put("method", "html"); + oprops.put("{http://xml.apache.org/xslt}indent-amount", "2"); + serializer.setOutputProperties(oprops); + serializer.transform(new DOMSource(doc), + new StreamResult(outputFile)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_1.out", outputFile)); + } + + /** + * Show simple transformation from input stream to output stream. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleFromStream() throws Exception { + String outputFile = getNextFile(this.getClass()); + try (InputStream xslIS = new BufferedInputStream(new FileInputStream(XSL_ID)); + InputStream xmlIS = new BufferedInputStream(new FileInputStream(SOURCE_ID))) { + // Create a transform factory instance. + TransformerFactory tfactory = TransformerFactory.newInstance(); + StreamSource xslSource = new StreamSource(xslIS); + // Note that if we don't do this, relative URLs can not be resolved correctly! + xslSource.setSystemId(filenameToURL(XSL_ID)); + + // Create a transformer for the stylesheet. + Transformer transformer = tfactory.newTransformer(xslSource); + StreamSource xmlSource = new StreamSource(xmlIS); + // Note that if we don't do this, relative URLs can not be resolved correctly! + xmlSource.setSystemId(filenameToURL(SOURCE_ID)); + + // Transform the source XML to output file. + transformer.transform(xmlSource, new StreamResult(outputFile)); + } + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_6.out", outputFile)); + } + + /** + * Show how to override output properties. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleOutputProperties() throws Exception { + String outputFile = getNextFile(this.getClass()); + + TransformerFactory tfactory = TransformerFactory.newInstance(); + Templates templates = tfactory.newTemplates(new StreamSource(filenameToURL(XSL_ID))); + Properties oprops = templates.getOutputProperties(); + + oprops.put(OutputKeys.INDENT, "yes"); + + Transformer transformer = templates.newTransformer(); + + transformer.setOutputProperties(oprops); + transformer.transform(new StreamSource(filenameToURL(SOURCE_ID)), + new StreamResult(outputFile)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_7.out", outputFile)); + } + + /** + * Show how to transform a DOM tree into another DOM tree. This uses the + * javax.xml.parsers to parse an XML file into a DOM, and create an output + * DOM. + * + * @throws Exception If any errors occur. + */ + public void exampleDOM2DOM() throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + org.w3c.dom.Document outNode = docBuilder.newDocument(); + Node xslDoc = docBuilder.parse(new InputSource(filenameToURL(XSL_ID))); + DOMSource dsource = new DOMSource(xslDoc); + // If we don't do this, the transformer won't know how to + // resolve relative URLs in the stylesheet. + dsource.setSystemId(filenameToURL(XSL_ID)); + + Templates templates = tfactory.newTemplates(dsource); + + Transformer transformer = templates.newTransformer(); + Node xmlDoc = docBuilder.parse(new InputSource(filenameToURL(SOURCE_ID))); + + transformer.transform(new DOMSource(xmlDoc), new DOMResult(outNode)); + + Transformer serializer = tfactory.newTransformer(); + serializer.transform(new DOMSource(outNode), new StreamResult(outputFile)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_4.out", outputFile)); + } + + /** + * Show the Transformer using SAX events in and DOM nodes out. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleSimple1() throws Exception { + String outputFile = getNextFile(this.getClass()); + // Create a transform factory instance. + TransformerFactory tfactory = TransformerFactory.newInstance(); + + // Create a transformer for the stylesheet. + Transformer transformer + = tfactory.newTransformer(new StreamSource(filenameToURL(XSL_ID))); + // No need to setSystemId, the transformer can get it from the URL + + transformer.transform(new StreamSource(filenameToURL(SOURCE_ID)), + new StreamResult(outputFile)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_8.out", outputFile)); + } + + /** + * Show the simplest possible transformation from File to a File. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleSimple2() throws Exception { + String outputFile = getNextFile(this.getClass()); + + TransformerFactory tfactory = TransformerFactory.newInstance(); + + // Create a transformer for the stylesheet. + try { + setPermissions(new PropertyPermission("user.dir", "read")); + Transformer transformer + = tfactory.newTransformer(new StreamSource(new File(XSL_ID))); + // No need to setSystemId, the transformer can get it from the File + + transformer.transform(new StreamSource(new File(SOURCE_ID)), + new StreamResult(new File(outputFile))); + } finally { + setPermissions(); + } + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_9.out", outputFile)); + } + + /** + * Show the that a transformer can be reused, and show resetting a parameter + * on the transformer. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleTransformerReuse() throws Exception { + String outputFile = getNextFile(this.getClass()); + // Create a transform factory instance. + TransformerFactory tfactory = TransformerFactory.newInstance(); + + // Create a transformer for the stylesheet. + Transformer transformer + = tfactory.newTransformer(new StreamSource(filenameToURL(XSL_ID))); + + transformer.setParameter("a-param", "hello to you!"); + + transformer.transform(new StreamSource(filenameToURL(SOURCE_ID)), + new StreamResult(outputFile)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_10.out", outputFile)); + + transformer.setParameter("a-param", "hello to me!"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + String outputFile2 = getNextFile(this.getClass()); + transformer.transform(new StreamSource(filenameToURL(SOURCE_ID)), + new StreamResult(outputFile2)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_11.out", outputFile)); + } + + /** + * Show the simplest possible transformation from system id to output + * stream. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleUseTemplatesObj() throws Exception { + String outputFile1 = getNextFile(this.getClass()); + String outputFile2 = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + + // Create a templates object, which is the processed, + // thread-safe representation of the stylesheet. + Templates templates = tfactory.newTemplates(new StreamSource(filenameToURL(XSL_ID))); + + // Illustrate the fact that you can make multiple transformers + // from the same template. + Transformer transformer1 = templates.newTransformer(); + Transformer transformer2 = templates.newTransformer(); + + transformer1.transform(new StreamSource(filenameToURL(SOURCE_ID)), + new StreamResult(outputFile1)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_12.out", outputFile1)); + + transformer2.transform(new StreamSource(filenameToURL(SOURCE_ID2)), + new StreamResult(outputFile2)); + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_13.out", outputFile2)); + } + + /** + * Show the Transformer as a SAX2 XMLReader. An XMLFilter obtained from + * newXMLFilter should act as a transforming XMLReader if setParent is not + * called. Internally, an XMLReader is created as the parent for the + * XMLFilter. + * + * @throws Exception If any errors occur. + */ + @Test + public void exampleXMLReader() throws Exception { + String outputFile = getNextFile(this.getClass()); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + TransformerFactory tfactory = TransformerFactory.newInstance(); + XMLReader reader = ((SAXTransformerFactory) tfactory) + .newXMLFilter(new StreamSource(filenameToURL(XSL_ID))); + + // Set the result handling to be a serialization to the file output stream. + Serializer serializer = SerializerFactory.getSerializer(OutputPropertiesFactory.getDefaultMethodProperties("xml")); + + serializer.setOutputStream(fos); + + reader.setContentHandler(serializer.asContentHandler()); + reader.parse(new InputSource(filenameToURL(SOURCE_ID))); + } + assertTrue(compareWithGold(GOLDEN_DIR + "ExamplesTest_15.out", outputFile)); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/Minitest.java 2015-01-09 15:41:39.102120719 -0800 @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import java.io.FileOutputStream; +import java.util.Properties; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import org.apache.qetest.xslwrapper.TransformWrapper; +import org.apache.qetest.xslwrapper.TransformWrapperFactory; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +/** + * Unit test for Xalan-J 2.x. + * + * Developers should always run either the minitest or smoketest + * target before checking any code into the xml-xalan CVS + * repository. Running the minitest before checking in ensures + * that the Xalan CVS tree will always be in a compileable and + * at least basically functional state, thus ensuring a workable + * product for your fellow Xalan developers. Ensuring your code + * passes the smoketest target will also help the nightly GUMP + * runs to pass the smoketest as well and avoid 'nag' emails. + */ +public class Minitest extends JAXPFileBaseTest { + /** + * Constants matching parameter names/values. + */ + private static final String PARAM1S = "param1s"; + + private static final String PARAM1N = "param1n"; + + /** + * Basic systemId transforms and parameters plus API coverage. + * + * @throws Exception If any errors occur. + */ + @Test + public void test() throws Exception { + String xslFile = XML_DIR + "Minitest.xsl"; + String xmlFile = XML_DIR + "Minitest.xml"; + // Use separate output files for different versions, since + // some indenting rules are implemented differently 1.x/2.x + String goldFile = GOLDEN_DIR + "Minitest-xalanj2.out"; + + String file1 = getNextFile(this.getClass()); + String file2 = getNextFile(this.getClass()); + + try (FileOutputStream fos1 = new FileOutputStream(file1); + FileOutputStream fos2 = new FileOutputStream(file2);) { + TransformerFactory factory = TransformerFactory.newInstance(); + Templates templates = factory.newTemplates(new StreamSource(filenameToURL(xslFile))); + Transformer transformer = templates.newTransformer(); + transformer.transform(new StreamSource(filenameToURL(xmlFile)), + new StreamResult(fos1)); + compareWithGold(goldFile, file1); + + // Validate transformer reuse + transformer.transform(new StreamSource(filenameToURL(xmlFile)), + new StreamResult(fos2)); + compareWithGold(goldFile, file2); + } + + String paramXslFile = XML_DIR + "MinitestParam.xsl"; + String paramXmlFile = XML_DIR + "MinitestParam.xml"; + String paramGoldFile = GOLDEN_DIR + "MinitestParam.out"; + String file3 = getNextFile(this.getClass()); + try (FileOutputStream fos = new FileOutputStream(file3)) { + // Validate selected API's - primarily Parameters + TransformerFactory factory = TransformerFactory.newInstance(); + Templates paramTemplates = factory.newTemplates(new StreamSource(filenameToURL(paramXslFile))); + Transformer paramTransformer = paramTemplates.newTransformer(); + paramTransformer.setParameter(PARAM1S, "paramVal"); + assertTrue(paramTransformer.getParameter(PARAM1S) instanceof String); + + // Verify simple re-set/get of a single parameter - new Integer + paramTransformer.setParameter(PARAM1S, 1234); // SPR SCUU4R3JGY - can't re-set + assertTrue(paramTransformer.getParameter(PARAM1S) instanceof Integer); + + // Validate a transform with two params set + paramTransformer.setParameter(PARAM1N, "new-param1n-value"); + + paramTransformer.transform(new StreamSource(filenameToURL(paramXmlFile)), + new StreamResult(fos)); + compareWithGold(paramGoldFile, file3); + // Validate params are still set after transform + assertTrue(paramTransformer.getParameter(PARAM1S) instanceof Integer); + assertTrue(paramTransformer.getParameter(PARAM1S) instanceof Integer); + } + } + + /** + * Using different Transformer to transform xml files. + * Note wrapper here is mapping with wrapper according to + * TransformWrapperFactory.wrapperMapper + * + * @return an array that has the style-sheet file name, XML file name, + * golden validation file name and type of wrapper. + */ + @DataProvider + public Object[][] wrapperProvider() { + return new Object[][]{ + {"Minitest.xsl", "Minitest.xml", "Minitest-xalanj2.out", "trax.dom"}, + {"Minitest.xsl", "Minitest.xml", "Minitest-xalanj2.out", "trax.sax"}, + {"Minitest.xsl", "Minitest.xml", "Minitest-xalanj2.out", "trax.stream"}, + {"Minitest.xsl", "Minitest.xml", "Minitest-xalanj2.out", "trax.file"}, + {"Minitest.xsl", "Minitest.xml", "Minitest-xalanj2.out", "trax.systemId"}, + {"Minitest.xsl", "Minitest.xml", "Minitest-xalanj2.out", "trax.localPath"}, + {"Minitest.xsl", "Minitest.xml", "Minitest-xalanj2.out", "trax.systemId3"}, + {"MinitestPerf.xsl", "MinitestPerf.xml", "MinitestPerf.out", "trax.dom"}, + {"MinitestPerf.xsl", "MinitestPerf.xml", "MinitestPerf.out", "trax.sax"}, + {"MinitestPerf.xsl", "MinitestPerf.xml", "MinitestPerf.out", "trax.stream"}, + {"MinitestPerf.xsl", "MinitestPerf.xml", "MinitestPerf.out", "trax.file"}, + {"MinitestPerf.xsl", "MinitestPerf.xml", "MinitestPerf.out", "trax.systemId"}, + {"MinitestPerf.xsl", "MinitestPerf.xml", "MinitestPerf.out", "trax.localPath"}, + {"MinitestPerf.xsl", "MinitestPerf.xml", "MinitestPerf.out", "trax.systemId3"} + }; + } + + /** + * Basic test for transformWrapper. Worker method to use a TransformWrapper + * to transform a file and checking the output. + * + * @param xslName stylesheet file. + * @param xmlName XML file for parsing. + * @param goldName golden file for checking. + * @param flavor Test favor. + * @throws Exception any exception in wrapper. + */ + @Test(dataProvider = "wrapperProvider") + public void testTransformWrapper(String xslName, String xmlName, + String goldName, String flavor) throws Exception { + String xslFile = XML_DIR + xslName; + String xmlFile = XML_DIR + xmlName; + String goldFile = GOLDEN_DIR + goldName; + String outputFile = getNextFile(this.getClass()); + + TransformWrapper transformWrapper = TransformWrapperFactory.newWrapper(flavor); + transformWrapper.newProcessor(new Properties()); + if (null == xslFile) { + // presume it's an embedded test + transformWrapper.transformEmbedded(xmlFile, outputFile); + } else { + // presume it's a normal stylesheet test + transformWrapper.transform(xmlFile, xslFile, outputFile); + } + compareWithGold(goldFile, outputFile); + + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/ParameterTest.java 2015-01-09 15:41:39.365121129 -0800 @@ -0,0 +1,319 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +/** + * Functional test of various usages of parameters in transforms. + */ +public class ParameterTest extends JAXPFileBaseTest { + /** + * Test XSL file. + */ + private static final String XSLT_TEST_FILE = filenameToURL(XML_DIR + "ParameterTest.xsl"); + + /** + * Test XML file. + */ + private static final String XML_TEST_FILE = filenameToURL(XML_DIR + "ParameterTest.xml"); + + /** + * Test XSL file. + */ + private static final String SIMPLE_XSLT_TEST_FILE = filenameToURL(XML_DIR + "ParameterTest2.xsl"); + + /** + * Test XML file. + */ + private static final String SIMPLE_XML_TEST_FILE = filenameToURL(XML_DIR + "ParameterTest2.xml"); + + /** + * Test Parameters. + */ + private static final String[][] PARAMETERS + = { + { + "t1", + "'a'", + "false-notset,false-blank,false-a,false-1,'a'", + "(10)Select expr of a 'param' string" + }, + { + "t1", + "a", + "false-notset,false-blank,true-a,false-1,a", + "(10a)Select expr of a param string" + }, + { + "t1", + "'1'", + "false-notset,false-blank,false-a,false-1,'1'", + "(11)Select expr of a 'param' number" + }, + { + "t1", + "1", + "false-notset,false-blank,false-a,true-1,1", + "(11a)Select expr of a param number" + }, + { + "t1", + "''", + "false-notset,false-blank,false-a,false-1,''", + "(12)Select expr of a param 'blank' string" + }, + { + "t1", + "", + "false-notset,true-blank,false-a,false-1,", + "(12a)Select expr of a param blank string" + }, + { + "p1", + "'foo'", + "'foo','foo';", + "(13)Stylesheet with literal 'param' value" + }, + { + "p1", + "foo", + "foo,foo;", + "(13a)Stylesheet with literal param value" + }, + { + "p1", + "'bar'", + "'bar','bar';", + "(14)Stylesheet with replaced/another literal 'param' value" + }, + { + "p1", + "bar", + "bar,bar;", + "(14a)Stylesheet with replaced/another literal param value" + }, + { + "p2", + "'<item>bar</item>'", + "'&lt;item&gt;bar&lt;/item&gt;','&lt;item&gt;bar&lt;/item&gt;'; GHI,GHI; ", + "(15)Stylesheet with 'param' value with nodes" + }, + { + "p2", + "<item>bar</item>", + "&lt;item&gt;bar&lt;/item&gt;,&lt;item&gt;bar&lt;/item&gt;;", + "(15a)Stylesheet with param value with nodes" + }, + { + "p3", + "'foo3'", + "DEF,DEF;", + "(16)Stylesheet with literal 'param' value in a template, is not passed" + }, + { + "p3", + "foo3", + "DEF,DEF;", + "(16a)Stylesheet with literal param value in a template, is not passed" + }, + { + "s1", + "'foos'", + "'foos','foos';", + "(17)Stylesheet with literal 'param' select" + }, + { + "s1", + "foos", + "foos,foos;", + "(17a)Stylesheet with literal param select" + }, + { + "s1", + "'bars'", + "'bars','bars'; s2val,s2val; s3val,s3val; ", + "(18)Stylesheet with replaced/another literal 'param' select" + }, + { + "s1", + "bars", + "bars,bars; s2val,s2val; s3val,s3val; ", + "(18a)Stylesheet with replaced/another literal param select" + }, + { + "s2", + "'<item/>'", + "'&lt;item/&gt;','&lt;item/&gt;'; s3val,s3val; ", + "(19)Stylesheet with nodes(?) 'param' select" + }, + { + "s2", + "<item/>", + "&lt;item/&gt;,&lt;item/&gt;; s3val,s3val; ", + "(19a)Stylesheet with nodes(?) param select" + } + }; + + @DataProvider + public Object[][] parameters() { + return Arrays.stream(PARAMETERS).map(ps -> new Object[]{ + ps[0], ps[1], new StreamSource(XML_TEST_FILE), + new StreamSource(XSLT_TEST_FILE), ps[2] + }).toArray(Object[][]::new); + } + + /** + * Reuse the same transformer multiple times with parameters set. + * @throws Exception If any errors occur. + */ + @Test + public void reuseParametersTest() throws Exception { + Transformer transformer = TransformerFactory.newInstance() + .newTemplates(new StreamSource(SIMPLE_XSLT_TEST_FILE)) + .newTransformer(); + String outputFile1 = getNextFile(this.getClass()); + transformer.transform(new StreamSource(XML_TEST_FILE), + new StreamResult(outputFile1)); + // Verify the values are correct for no params set + checkFileContains(outputFile1, "ParameterTest.xml:"); + String outputFile2 = getNextFile(this.getClass()); + transformer.transform(new StreamSource(SIMPLE_XML_TEST_FILE), + new StreamResult(outputFile2)); + // Do NOT call clear Parameters here; reuse the transformer + checkFileContains(outputFile2, "ParameterTest.xml:"); + String outputFile3 = getNextFile(this.getClass()); + transformer.transform(new StreamSource(XML_TEST_FILE), + new StreamResult(outputFile3)); + // Do NOT call clearParameters here; reuse the transformer + transformer.transform(new StreamSource(XML_TEST_FILE), + new StreamResult(outputFile3)); + } + + /** + * Test setting a single string-valued parameter. + * Uses the supplied Transformer and calls setParameter() + * then transform(Source, Source), then uses the worker + * method checkFileContains() to validate and output results. + * + * @param paramName simple name of parameter + * @param paramVal String value of parameter + * @param transformer object to use + * @param xmlSource object to use in transform + * @param checkString to look for in output file (logged) + */ + private void testSetParam(String paramName, String paramVal, + Transformer transformer, Source xmlSource, String checkString) + throws TransformerException, IOException { + String outputFile = getNextFile(this.getClass()); + + transformer.setParameter(paramName, paramVal); + transformer.transform(xmlSource, new StreamResult(outputFile)); + assertTrue(checkFileContains(outputFile, checkString)); + } + + /** + * Test setting a single string-valued parameter. + * Creates a Transformer and calls setParameter() + * then transform(Source, Source), then uses the worker + * method checkFileContains() to validate and output results. + * + * @param paramName simple name of parameter + * @param paramVal String value of parameter + * @param xmlSource object to use in transform + * @param xslStylesheet object to use in transform + * @param checkString to look for in output file (logged) + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void testSetParam(String paramName, String paramVal, + Source xmlSource, Source xslStylesheet, String checkString) + throws Exception { + testSetParam(paramName, paramVal, + TransformerFactory.newInstance().newTransformer(xslStylesheet), + xmlSource, checkString); + } + + /** + * Setting various string-valued parameters and reusing transformers. + * Creates one transformer first, then loops through array + * of simple test data re-using transformer. + * @throws IOException if any I/O operation error. + * @throws TransformerException If an unrecoverable error occurs during the + * course of the transformation. + */ + @Test + public void reuseTestParams() throws IOException, TransformerException { + Transformer transformer = TransformerFactory.newInstance() + .newTemplates(new StreamSource(XSLT_TEST_FILE)) + .newTransformer(); + String outputFile = getNextFile(this.getClass()); + transformer.transform(new StreamSource(XML_TEST_FILE), + new StreamResult(outputFile)); + transformer.clearParameters(); + // Verify each of the three kinds of params are correct + assertTrue(checkFileContains(outputFile, "ABC,ABC; DEF,DEF; GHI,GHI; ")); + assertTrue(checkFileContains(outputFile, "s1val,s1val; s2val,s2val; s3val,s3val; ")); + assertTrue(checkFileContains(outputFile, "true-notset,false-blank,false-a,false-1,notset")); + Arrays.stream(PARAMETERS).forEach(ps -> { + try { + testSetParam(ps[0], ps[1], new StreamSource(XML_TEST_FILE), + new StreamSource(XSLT_TEST_FILE), ps[2]); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + }); + } + + + + /** + * Checks if a file contains a certain string (all within one line). + * We should really consider validating the entire output file, but + * this is the important functionality, and it makes maintaining the + * test and gold data easier (since it's all in this file). + * + * @param file local path/name of file to check. + * @param checkStr String to look for in the file. + * @return true if file contain checkStr + * false if file doesn't contain checkStr. + * @throws IOException if any wrong with I/O operation. + */ + protected boolean checkFileContains(String file, String checkStr) throws IOException { + return Files.readAllLines(Paths.get(file)).stream() + .anyMatch(s -> s.contains(checkStr)); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/SystemIdImpInclTest.java 2015-01-09 15:41:39.631121544 -0800 @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Test behavior of imports/includes with various setSystemId sources. + * Note: This test is directory-dependent, so if there are any fails, check the + * code to see what the test file is expecting the path/directory/etc to be. + */ +public class SystemIdImpInclTest extends JAXPFileBaseTest { + /** + * Gold filename for level0, i.e. one directory above the test file. + */ + private static final String GOLDEN_File_LEVEL0 = "SystemIdImpInclLevel0.out"; + + /** + * Gold filename for level1, i.e. the directory of the test file. + */ + private static final String GOLDEN_File_LEVEL1 = "SystemIdImpInclLevel1.out"; + + /** + * Gold filename for level2, i.e. a directory below the test file. + */ + private static final String GOLDEN_File_LEVEL2 = "SystemIdImpInclLevel2.out"; + + /** + * Test style-sheet file name. + */ + private static final String XSL_FILE = XML_DIR + "SystemIdImpIncl.xsl"; + + /** + * Test style-sheet file name. + */ + private static final String LEVEL0_INCLUDE_XSL = XML_DIR + "../SystemIdImpIncl.xsl"; + + /** + * Test style-sheet file name. + */ + private static final String LEVEL1_INCLUDE_XSL = XSL_FILE; + + /** + * Test style-sheet file name. + */ + private static final String LEVEL2_INCLUDE_XSL = XML_DIR + "systemid/SystemIdImpIncl.xsl"; + + /** + * Test XML file name. + */ + private static final String XML_FILE = XML_DIR + "SystemIdImpIncl.xml"; + + /** + * Simple StreamSources with different setSystemIds. + * @throws Exception If any errors occur. + */ + @Test + public void testCase1() throws Exception { + String goldFile = GOLDEN_DIR + GOLDEN_File_LEVEL1; + String outputFile = getNextFile(this.getClass()); + + try(InputStream xmlStream = new FileInputStream(XML_FILE); + FileOutputStream fos = new FileOutputStream(outputFile);) { + TransformerFactory factory = TransformerFactory.newInstance(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Node xslNode = docBuilder.parse(new InputSource(filenameToURL(XSL_FILE))); + Source xslSource = new DOMSource(xslNode); + xslSource.setSystemId(filenameToURL(LEVEL1_INCLUDE_XSL)); + + Source xmlSource = new StreamSource(xmlStream); + xmlSource.setSystemId(filenameToURL(XML_FILE)); + factory.newTemplates(xslSource).newTransformer(). + transform(xmlSource, new StreamResult(fos)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Verify simple SAXSources with systemIds. + * @throws Exception If any errors occur. + */ + @Test + public void testCase2() throws Exception { + String goldFile = GOLDEN_DIR + GOLDEN_File_LEVEL0; + String outputFile = getNextFile(this.getClass()); + + try(InputStream xslStream = new FileInputStream(XSL_FILE); + InputStream xmlStream = new FileInputStream(XML_FILE); + FileOutputStream fos = new FileOutputStream(outputFile);) { + TransformerFactory factory = TransformerFactory.newInstance(); + Source xslSource = new StreamSource(new InputStreamReader(xslStream)); + xslSource.setSystemId(filenameToURL(LEVEL0_INCLUDE_XSL)); + + Source xmlSource = new StreamSource(xmlStream); + xmlSource.setSystemId(filenameToURL(XML_FILE)); + factory.newTemplates(xslSource).newTransformer(). + transform(xmlSource, new StreamResult(fos)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Verify simple SAXSources with systemIds. + * @throws Exception If any errors occur. + */ + @Test + public void testCase3() throws Exception { + String goldFile = GOLDEN_DIR + GOLDEN_File_LEVEL2; + String outputFile = getNextFile(this.getClass()); + + try(InputStream xslStream = new FileInputStream(XSL_FILE); + InputStream xmlStream = new FileInputStream(XML_FILE); + FileOutputStream fos = new FileOutputStream(outputFile);) { + TransformerFactory factory = TransformerFactory.newInstance(); + Source xslSource = new StreamSource(new InputStreamReader(xslStream, "UTF-8")); + xslSource.setSystemId(filenameToURL(LEVEL2_INCLUDE_XSL)); + + Source xmlSource = new StreamSource(xmlStream); + xmlSource.setSystemId(filenameToURL(XML_FILE)); + factory.newTemplates(xslSource).newTransformer(). + transform(xmlSource, new StreamResult(fos)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/TemplateAPITest.java 2015-01-09 15:41:39.896121957 -0800 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import java.io.FilePermission; +import java.util.Properties; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static org.testng.Assert.*; +import org.testng.annotations.Test; + +/** + * Basic API coverage test for the Templates class of TRAX. + */ +public class TemplateAPITest extends JAXPBaseTest{ + /** + * TRAX Templates: cover newTransformer(),getOutputProperties() APIs and + * basic functionality. + * @throws javax.xml.transform.TransformerConfigurationException + */ + @Test + public void test() throws TransformerConfigurationException { + setPermissions(new FilePermission(XML_DIR + "-", "read")); + final String xslFile = XML_DIR + "TransformerAPIParam.xsl"; + final String outputFormatXSL = XML_DIR + "TransformerAPIOutputFormat.xsl"; + + TransformerFactory factory = TransformerFactory.newInstance(); + Templates templates1 = factory.newTemplates(new StreamSource(xslFile)); + + // Cover APIs newTransformer(), getOutputProperties() + Transformer transformer = templates1.newTransformer(); + assertNotNull(transformer); + Properties outputFormat = templates1.getOutputProperties(); + assertNotNull(outputFormat); + + // Check that the local stylesheet.getProperty has default set, cf. + // getOutputProperties javadoc + assertEquals(outputFormat.getProperty(OutputKeys.METHOD), "xml"); + assertNull(outputFormat.get(OutputKeys.METHOD)); + assertEquals(outputFormat.getProperty(OutputKeys.INDENT), "no"); + assertNull(outputFormat.get(OutputKeys.INDENT)); + + Templates templates2 + = factory.newTemplates(new StreamSource(outputFormatXSL)); + Properties outputFormat2 = templates2.getOutputProperties(); + assertNotNull(outputFormat2); + + // Known outputFormat property name/value from outputFormatXSL. + final String OUTPUT_FORMAT_NAME = OutputKeys.CDATA_SECTION_ELEMENTS; + final String OUTPUT_FORMAT_VALUE = "cdataHere "; + + // Test known properties + outputFormat2.getProperty(OUTPUT_FORMAT_NAME); + assertEquals(outputFormat2.getProperty(OUTPUT_FORMAT_NAME), OUTPUT_FORMAT_VALUE); + assertEquals(outputFormat2.getProperty("omit-xml-declaration"), "yes"); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/TransformerAPITest.java 2015-01-09 15:41:40.162122372 -0800 @@ -0,0 +1,362 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import java.io.FileOutputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Properties; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +/** + * Basic API coverage test for the Transformer class of TRAX. + * This test focuses on coverage testing for the API's, and + * very brief functional testing. + */ +public class TransformerAPITest extends JAXPFileBaseTest { + /** + * Parameter names from TransformerAPIParam.xsl + */ + private static final String PARAM1S = "param1s"; + + /** + * Parameter names from TransformerAPIParam.xsl + */ + private static final String PARAM3S = "param3s"; + + /** + * Parameter names from TransformerAPIParam.xsl + */ + private static final String PARAM1N = "param1n"; + + /** + * TransformerFactory for creating Transfomer. + */ + private final TransformerFactory factory; + + /** + * Initiate Transformer factory. + */ + public TransformerAPITest() { + factory = TransformerFactory.newInstance(); + } + + /** + * Known outputFormat values from TransformerAPIOutputFormat.xsl . + */ + private static final String METHOD_VALUE = "xml"; + private static final String VERSION_VALUE ="123.45"; + private static final String ENCODING_VALUE ="UTF-16"; + private static final String STANDALONE_VALUE = "yes"; + private static final String DOCTYPE_PUBLIC_VALUE = "this-is-doctype-public"; + private static final String DOCTYPE_SYSTEM_VALUE = "this-is-doctype-system"; + private static final String CDATA_SECTION_ELEMENTS_VALUE = "cdataHere "; + private static final String INDENT_VALUE = "yes"; + private static final String MEDIA_TYPE_VALUE = "text/test/xml"; + private static final String OMIT_XML_DECLARATION_VALUE = "yes"; + + /** + * Basic API coverage tests for Transformer API. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase1() throws Exception { + String xmlFile = filenameToURL(XML_DIR + "TransformerAPIParam.xml"); + String xslFile = filenameToURL(XML_DIR + "TransformerAPIParam.xsl"); + String goldFile= GOLDEN_DIR + "TransformerAPIParam.out"; + + Transformer identityTransformer = factory.newTransformer(); + Templates templates = factory.newTemplates(new StreamSource(xslFile)); + assertNull(identityTransformer.getParameter("This-param-does-not-exist")); + + identityTransformer.setParameter("foo", "bar"); + assertNotNull(identityTransformer.getParameter("foo")); + + Transformer transformer = templates.newTransformer(); + // Default Transformer should not have any parameters. + assertNull(transformer.getParameter("This-param-does-not-exist")); + // Including params in the stylesheet, Javadoc says "This method does + // not return a default parameter value, which cannot be determined + // until the node context is evaluated during the transformation process". + assertNull(transformer.getParameter(PARAM1S)); + + // Verify simple set/get of a single parameter - Integer + transformer.setParameter(PARAM3S, 1234); + assertEquals(transformer.getParameter(PARAM3S), 1234); + + transformer.setParameter(PARAM3S, 99); // Had bug can't re-set + assertEquals(transformer.getParameter(PARAM3S), 99); + + // Verify simple re-set/get of a single parameter - now a new String + transformer.setParameter(PARAM3S, "new value3s"); + assertEquals(transformer.getParameter(PARAM3S), "new value3s"); + + transformer.setParameter(PARAM1S, "'test-param-1s'"); // note single quotes + transformer.setParameter(PARAM1N, 1234); + + + // Verify basic params actually affect transformation + // Use the transformer we set the params onto above! + String outputFile = getNextFile(this.getClass()); + try (FileOutputStream fos = new FileOutputStream(outputFile);) { + transformer.transform(new StreamSource(xmlFile), + new StreamResult(fos)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + assertEquals(transformer.getParameter(PARAM1S), "'test-param-1s'"); + assertEquals(transformer.getParameter(PARAM1N), 1234); + } + + /** + * API coverage test of Transformer.set/getOutputProperty(). + * + * @param xslFile XSLT file we will use. + * @param xmlFile XML test file. + * @param goldFile golden validation file. + * @param expectedProperties expected result. + * @throws Exception If any errors occur. + */ + @Test(dataProvider="propertiesDataProvider") + public void testCase2(String xslFile, String xmlFile, String goldFile, + String[] expectedProperties) throws Exception { + Transformer transformer = factory.newTemplates(new StreamSource(xslFile)).newTransformer(); + Properties props = transformer.getOutputProperties(); + // Default uses UTF8 as encoding. + Charset cs = StandardCharsets.UTF_8; + for(int i = 0; i < expectedProperties.length; i = i + 2) { + assertEquals(props.get(expectedProperties[i]), + expectedProperties[i + 1]); + if(expectedProperties[i].equals(OutputKeys.ENCODING)) { + cs = Charset.forName(expectedProperties[i + 1]); + } + } + // Always do set/get testing on default Transformer. + Transformer defaultTransformer = factory.newTransformer(); + defaultTransformer.setOutputProperty(OutputKeys.METHOD, "text"); + assertEquals(defaultTransformer.getOutputProperty(OutputKeys.METHOD), "text"); + + String outputFile = getNextFile(this.getClass()); + transformer.transform(new StreamSource(xmlFile), new StreamResult(outputFile)); + assertTrue(compareWithGold(goldFile, outputFile, cs)); + } + + /** + * Data provider for testCase2. + * + * @return an array that has parameters XSL file,XML file, golden validation + * file, expected properties. + */ + @DataProvider + public Object[][] propertiesDataProvider(){ + return new Object[][]{ + {XML_DIR + "identity.xsl", + XML_DIR + "identity.xml", + GOLDEN_DIR + "identity.out", + new String[]{OutputKeys.METHOD, null, + OutputKeys.INDENT, null}}, + {XML_DIR + "TransformerAPIVar.xsl", + XML_DIR + "TransformerAPIVar.xml", + GOLDEN_DIR + "TransformerAPIVar.out", + new String[]{OutputKeys.METHOD, "xml", OutputKeys.INDENT, "no"}}, + {XML_DIR + "TransformerAPIOutputFormat.xsl", + XML_DIR + "TransformerAPIOutputFormat.xml", + GOLDEN_DIR + "TransformerAPIOutputFormatUTF16.out", + new String[]{ + OutputKeys.METHOD, METHOD_VALUE, + OutputKeys.VERSION, VERSION_VALUE, + OutputKeys.ENCODING, ENCODING_VALUE, + OutputKeys.STANDALONE, STANDALONE_VALUE, + OutputKeys.DOCTYPE_PUBLIC, DOCTYPE_PUBLIC_VALUE, + OutputKeys.DOCTYPE_SYSTEM, DOCTYPE_SYSTEM_VALUE, + OutputKeys.CDATA_SECTION_ELEMENTS, CDATA_SECTION_ELEMENTS_VALUE, + OutputKeys.INDENT, INDENT_VALUE, + OutputKeys.MEDIA_TYPE, MEDIA_TYPE_VALUE, + OutputKeys.OMIT_XML_DECLARATION, OMIT_XML_DECLARATION_VALUE}}, + {XML_DIR + "TransformerAPIHTMLFormat.xsl", + XML_DIR + "TransformerAPIHTMLFormat.xml", + GOLDEN_DIR + "TransformerAPIHTMLFormat.out", + new String[]{ + OutputKeys.METHOD, "html", OutputKeys.INDENT, null}} + }; + } + + /** + * API coverage test of Transformer.set/getOutputProperties() + * + * @throws TransformerConfigurationException Thrown in case of + * ServiceConfigurationError service configuration error or if the + * implementation is not available or cannot be instantiated. + */ + @Test + public void testCase3() throws TransformerConfigurationException { + Transformer identityTransformer = factory.newTransformer(); + assertNotNull(factory.newTemplates(new StreamSource(XML_DIR + "TransformerAPIOutputFormat.xsl"))); + assertNotNull(identityTransformer.getOutputProperties()); + identityTransformer.setOutputProperties(new Properties()); + assertEquals(identityTransformer.getOutputProperties(), new Properties()); + } + + /** + * Data provider for re-use Transformer test. + * + * @return an array that has parameters XSL file,XML file, golden validation + * file. + */ + @DataProvider + public Object[][] reuseTranfomerOnSameXMLProvider() { + return new Object[][]{ + {XML_DIR + "identity.xsl", + XML_DIR + "identity.xml", + GOLDEN_DIR + "identity.out"}, + {XML_DIR + "TransformerAPIVar.xsl", + XML_DIR + "TransformerAPIVar.xml", + GOLDEN_DIR + "TransformerAPIVar.out"}, + {XML_DIR + "TransformerAPIVar.xsl", + XML_DIR + "TransformerAPIVar2.xml", + GOLDEN_DIR + "TransformerAPIVar2.out"} + }; + } + + /** + * TRAX Transformer: cover transform() API and multiple Transformations from + * single transformer on same XML file with same style-sheet file. + * + * @param xslFile XSLT file we will use. + * @param xmlFile XML test file. + * @param goldFile golden validation file. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "reuseTranfomerOnSameXMLProvider") + public void reuseTransformerSameXMLTest(String xslFile, String xmlFile, + String goldFile) throws Exception { + Transformer reuseTransformer = factory.newTransformer(new StreamSource(xslFile)); + String outputFile = getNextFile(this.getClass()); + + // Re-use the transformer multiple times on XML file. + reuseTransformer.transform(new StreamSource(xmlFile), + new StreamResult(outputFile)); + assertTrue(compareWithGold(goldFile, outputFile)); + reuseTransformer.transform(new StreamSource(xmlFile), + new StreamResult(outputFile)); + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Data provider for re-use Transformer test. + * Note: same style-sheet should be transformed two different XML files. + * + * @return an array that has parameters XSL file,two XML files and two + * golden validation files. + */ + @DataProvider + public Object[][] reuseTranfomerOnDiffXMLProvider() { + return new Object[][]{ + {XML_DIR + "TransformerAPIVar.xsl", + XML_DIR + "TransformerAPIVar.xml", + GOLDEN_DIR + "TransformerAPIVar.out", + XML_DIR + "TransformerAPIVar2.xml", + GOLDEN_DIR + "TransformerAPIVar2.out"} + }; + } + + /** + * TRAX Transformer: cover transform() API and multiple Transformations from + * single transformer on same XML file. + * + * @param xslFile XSLT file we will use. + * @param xmlFile1 First XML test file to be transformed. + * @param goldFile1 golden validation file for xmlFile1. + * @param xmlFile2 Second XML test file to be transformed. + * @param goldFile2 golden validation file for xmlFile2. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "reuseTranfomerOnDiffXMLProvider") + public void reuseTransformerDiffXMLTest(String xslFile, String xmlFile1, + String goldFile1, String xmlFile2, String goldFile2) + throws Exception { + Transformer reuseTransformer = factory.newTransformer(new StreamSource(xslFile)); + + // Transform first xml file and validate it. + String outputFile1 = getNextFile(this.getClass()); + reuseTransformer.transform(new StreamSource(xmlFile1), + new StreamResult(outputFile1)); + assertTrue(compareWithGold(goldFile1, outputFile1)); + + // Transform second xml file and validate it. + String outputFile2 = getNextFile(this.getClass()); + reuseTransformer.transform(new StreamSource(xmlFile2), + new StreamResult(outputFile2)); + assertTrue(compareWithGold(goldFile2, outputFile2)); + + // Transform first xml file and validate it again. + String outputFile3 = getNextFile(this.getClass()); + reuseTransformer.transform(new StreamSource(xmlFile1), + new StreamResult(outputFile3)); + assertTrue(compareWithGold(goldFile1, outputFile3)); + } + + /** + * Negative test on getOutputProperty. IllegalArgumentException If the + * property is not supported. + * + * @param notSupportedProperty an invalid property name. + * @throws TransformerConfigurationException Thrown in case of + * ServiceConfigurationError service configuration error or if the + * implementation is not available or cannot be instantiated. + */ + @Test(dataProvider = "bogusProperties", expectedExceptions = IllegalArgumentException.class) + public void bogusPropertyName(String notSupportedProperty) + throws TransformerConfigurationException{ + Transformer transformer = factory.newTransformer(); + transformer.getOutputProperty(notSupportedProperty); + } + + /** + * Data provider for bogusPropertyName negative tests. + * + * @return a parameters array that contains all invalid properties name. + */ + @DataProvider + public Object[][] bogusProperties() { + return new Object[][]{ + {"bogus-name"}, + {"bogus-{name}"} + }; + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/TransformerFactoryAPITest.java 2015-01-09 15:41:40.424122780 -0800 @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FilePermission; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.Test; + +/** + * API Coverage test for TransformerFactory class of TRAX. + */ +public class TransformerFactoryAPITest extends JAXPBaseTest { + /** + * Cached system property. + */ + private final String cachedSysProp = null; + + /** + * System property name, from TransformerFactory. + */ + private static final String DEFAULT_PROP_NAME = "javax.xml.transform.TransformerFactory"; + + /** + * Stored system property name for TransformerFactory. + */ + private String factory_prop_value; + + /** + * System property name for Xalan-J 2.x impl. + */ + private static final String XALAN_CLASSNAME = "org.apache.xalan.processor.TransformerFactoryImpl"; + + /** + * Test XSLT file name. + */ + private static final String XSL_URI = filenameToURL(XML_DIR + "identity.xsl"); + + /** + * Test XML file name. + */ + private static final String EMBEDDED_XML = XML_DIR + "embeddedIdentity.xml"; + + /** + * Test XML uri. + */ + private static final String EMBEDDED_XML_URI = filenameToURL(EMBEDDED_XML); + + /** + * Golden file name. + */ + private static final String EMBEDDED_GOLD_FILE = GOLDEN_DIR + "embeddedIdentity.out"; + + /** + * invalid feature/attribute name for negative test. + */ + private static final String BOGUS_NAME = "fnord:this/feature/does/not/exist"; + + /** + * Coverage tests for factory pattern API's. + */ + @Test + public void testCase1() { + // Reset the system property to what was cached previously + // test when system property is null + setSystemProperty(DEFAULT_PROP_NAME, null); + assertNotNull(TransformerFactory.newInstance()); + // This should come last so it will stay set for the rest of the test + // Note: this needs review, since in the future we may + // not guaruntee order of testCase execution! + setSystemProperty(DEFAULT_PROP_NAME, cachedSysProp); + assertNotNull(TransformerFactory.newInstance()); + } + + /** + * Save system property for restoring. + */ + @BeforeGroups (groups = {"systemProp"}) + public void saveProp() { + factory_prop_value = getSystemProperty(DEFAULT_PROP_NAME); + } + + /** + * Restore the system property. + */ + @AfterGroups (groups = {"systemProp"}) + public void restoreProp() { + setSystemProperty(DEFAULT_PROP_NAME, factory_prop_value); + } + + /** + * TransformerFactoryConfigurationError is thrown when system property is a + * bogus name. + */ + @Test(groups = {"systemProp"}, expectedExceptions = TransformerFactoryConfigurationError.class) + public void negativeTestCase1() { + setSystemProperty(DEFAULT_PROP_NAME, "this.class.does.not.exist"); + TransformerFactory.newInstance(); + } + + /** + * TransformerFactoryConfigurationError is thrown when system property is + * another kind of class name. + */ + @Test(groups = {"systemProp"}, expectedExceptions = TransformerFactoryConfigurationError.class) + public void negativeTestCase2() { + setSystemProperty(DEFAULT_PROP_NAME, "java.lang.String"); + TransformerFactory.newInstance(); + } + + + + /** + * Coverage tests for newTransformer() API's. + * + * @throws TransformerConfigurationException Thrown in case of + * ServiceConfigurationError service configuration error or if the + * implementation is not available or cannot be instantiated. + */ + @Test + public void testCase2() throws TransformerConfigurationException { + setPermissions(new FilePermission(XML_DIR + "/-", "read")); + TransformerFactory factory = TransformerFactory.newInstance(); + Transformer identityTransformer = factory.newTransformer(); + assertNotNull(identityTransformer); + + assertTrue(factory.getFeature(StreamSource.FEATURE)); + assertNotNull(factory.newTransformer(new StreamSource(XSL_URI))); + setPermissions(); + } + + /** + * Coverage tests for newTemplates() API's. + * + * @throws TransformerConfigurationException Thrown in case of + * ServiceConfigurationError service configuration error or if the + * implementation is not available or cannot be instantiated. + */ + @Test + public void testCase3() throws TransformerConfigurationException { + setPermissions(new FilePermission(XML_DIR + "/-", "read")); + TransformerFactory factory = TransformerFactory.newInstance(); + assertNotNull(factory.getFeature(StreamSource.FEATURE)); + assertNotNull(factory.newTemplates(new StreamSource(XSL_URI))); + setPermissions(); + } + + /** + * Coverage tests for getAssociatedStylesheet() API's. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase4() throws Exception{ + setPermissions(new FilePermission(XML_DIR + "/-", "read"), + new FilePermission(GOLDEN_DIR + "/-", "read"), + new FilePermission(USER_DIR + "-", "read, write")); + String outputFile = getNextFile(this.getClass()); + try (FileOutputStream resultStream = new FileOutputStream(getNextFile(this.getClass()))){ + TransformerFactory factory = TransformerFactory.newInstance(); + // Get the xml-stylesheet and process it + Source stylesheet = factory.getAssociatedStylesheet( + new StreamSource(EMBEDDED_XML_URI), null, null, null); + assertTrue(stylesheet instanceof Source); + assertNotNull(stylesheet); + + Transformer transformer = factory.newTransformer(stylesheet); + transformer.transform(new StreamSource(EMBEDDED_XML_URI), + new StreamResult(resultStream)); + } + assert(compareWithGold(EMBEDDED_GOLD_FILE, outputFile)); + setPermissions(); + } + + /** + * Coverage tests for get/setURIResolver(), get/setErrorListener() API's. + */ + @Test + public void testCase5() { + TransformerFactory factory = TransformerFactory.newInstance(); + assertNull(factory.getURIResolver()); + CheckingURIResolver loggingURIRes = new CheckingURIResolver(); + factory.setURIResolver(loggingURIRes); + assertEquals(factory.getURIResolver(), loggingURIRes); + factory.setURIResolver(null); + assertNull(factory.getURIResolver()); + assertNotNull(factory.getErrorListener()); + CheckingErrorListener loggingErrListener = new CheckingErrorListener(); + factory.setErrorListener(loggingErrListener); + assertEquals(factory.getErrorListener(), loggingErrListener); + } + + /** + * IAE is thrown when setErrorListener(null). + */ + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNegativeCase5() { + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setErrorListener(null); + } + + /** + * Miscellaneous tests. + * @throws Exception If any errors occur. + */ + @Test + public void associateSourceTest() throws Exception { + setPermissions(new FilePermission(XML_DIR + "/-", "read")); + TransformerFactory factory = TransformerFactory.newInstance(); + DOMSource domsource = new DOMSource(DocumentBuilderFactory. + newInstance().newDocumentBuilder().parse(EMBEDDED_XML)); + assertNull(factory.getAssociatedStylesheet(domsource,"screen","Modern",null)); + + try(FileInputStream fis = new FileInputStream(EMBEDDED_XML)) { + StreamSource ss = new StreamSource(fis); + assertNull(factory.getAssociatedStylesheet(ss,"screen","Modern",null)); + } + + try(FileInputStream fis = new FileInputStream(EMBEDDED_XML)) { + StreamSource ss = new StreamSource(fis); + ss.setSystemId(EMBEDDED_XML_URI); + assertNull(factory.getAssociatedStylesheet(ss,"screen","Modern",null)); + } + setPermissions(); + } + + /** + * Test if factory supports valid features and doesn't support invalid + * features. + */ + @Test + public void getFeaturesTest() { + TransformerFactory factory = TransformerFactory.newInstance(); + // Expected no NPE here. + assertFalse(factory.getFeature(BOGUS_NAME)); + + assertTrue(factory.getFeature(StreamSource.FEATURE)); + assertTrue(factory.getFeature(StreamResult.FEATURE)); + } + + /** + * IllegalArgumentException is thrown when implementation does not recognize + * the attribute. + */ + @Test(expectedExceptions = IllegalArgumentException.class) + public void bogusSetFeatures() { + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setAttribute(BOGUS_NAME, "on"); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/URIResolverTest.java 2015-01-09 15:41:40.693123200 -0800 @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; + +/** + * Verify that URIResolvers are called properly. + */ +public class URIResolverTest extends JAXPFileBaseTest { + /** + * Build a style-sheet/do a transform with lots of URIs to resolve. + * Verify that the URIResolver is called properly. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase1() throws Exception { + setPermissions(new RuntimePermission("accessClassInPackage.com.sun.org.apache.xml.internal.utils"), + new RuntimePermission("accessClassInPackage.com.sun.org.apache.xpath.internal.objects")); + String xslFile = XML_DIR + "URIResolverTest.xsl"; + String xmlFile = XML_DIR + "URIResolverTest.xml"; + String goldFile = GOLDEN_DIR + "URIResolverTest.out"; + + // Validate various URI's to be resolved during stylesheet + // build with the loggingURIResolver + String[] expXslUris = { + "{" + filenameToURL(xslFile) + "}" + "impincl/SystemIdImport.xsl", + "{" + filenameToURL(xslFile) + "}" + "impincl/SystemIdInclude.xsl" + }; + CheckingURIResolver chkURIResolver = new CheckingURIResolver(expXslUris); + TransformerFactory factory = TransformerFactory.newInstance(); + // Set the URIResolver and validate it + factory.setURIResolver(chkURIResolver); + Templates templates = factory.newTemplates(new StreamSource(xslFile)); + Transformer transformer = templates.newTransformer(); + assertEquals(factory.getURIResolver(), chkURIResolver); + + // Validate various URI's to be resolved during transform + // time with the loggingURIResolver + String[] expectedXmlUris = { + "{" + filenameToURL(xslFile) + "}" + "../impincl/SystemIdImport.xsl", + "{" + filenameToURL(xslFile) + "}" + "impincl/SystemIdImport.xsl", + "{" + filenameToURL(xslFile) + "}" + "systemid/impincl/SystemIdImport.xsl", + }; + CheckingURIResolver transfomerResolver = new CheckingURIResolver(expectedXmlUris); + transformer.setURIResolver(transfomerResolver); + String outputFile = getNextFile(this.getClass()); + transformer.transform(new StreamSource(filenameToURL(xmlFile)), + new StreamResult(outputFile)); + assertTrue(compareWithGold(goldFile, outputFile)); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/DOMImpIncl.xml 2015-01-09 15:41:40.964123622 -0800 @@ -0,0 +1,13 @@ + + + + Above Should be include-list then import-list + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/DOMImpIncl.xsl 2015-01-09 15:41:41.234124044 -0800 @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/DOMTest.xml 2015-01-09 15:41:41.498124455 -0800 @@ -0,0 +1,10 @@ + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/DOMTest.xsl 2015-01-09 15:41:41.748124845 -0800 @@ -0,0 +1,11 @@ + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/EmbeddedFragment.xml 2015-01-09 15:41:42.008125251 -0800 @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + +Hello + + +Goodbye + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/EmbeddedMediaTitle.xml 2015-01-09 15:41:42.268125656 -0800 @@ -0,0 +1,14 @@ + + + + + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/EmbeddedType-application-xml-xslt.xml 2015-01-09 15:41:42.520126049 -0800 @@ -0,0 +1,12 @@ + + + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/EmbeddedType-text-xml.xml 2015-01-09 15:41:42.773126444 -0800 @@ -0,0 +1,12 @@ + + + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/EmbeddedType-text-xsl.xml 2015-01-09 15:41:43.029126843 -0800 @@ -0,0 +1,12 @@ + + + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/EmbeddedType.xsl 2015-01-09 15:41:43.295127258 -0800 @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/ErrorListenerTest.xml 2015-01-09 15:41:43.563127676 -0800 @@ -0,0 +1,10 @@ + + + warning(TransformerException) + error(TransformerException) + fatalError(TransformerException) + + ErrorListener API's + Defined Above + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/ErrorListenerTest.xsl 2015-01-09 15:41:43.825128085 -0800 @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + ExpectedMessage from: + + + + + + + + + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/Minitest.xml 2015-01-09 15:41:44.097128509 -0800 @@ -0,0 +1,262 @@ + + + + + + + + + Lew Smith + Ruth Smith + + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + + + + + + Andy Smith +
Stonefield Dr
+ + 483-23-5432 + + + + + 012-23-1234 +
+ + Male + 45 + Yes + + + Suzie + 45 + + + + Jules + 9 + + Daniel + 8 + + + + PA + BS + +
+ + +Tom Smith +
Pondside Lane
+ +508.257.2754 + + + + +274-76-2971 +
+ +Male +30 +Yes + + +Maggy +39 + + + +Joshua +7 + +Lauren +5 + + +BA +
+ + +Henry Smith +
Lakeview
+ +417.645.4954 + + + + +231-45-3590 +
+ +Male +40 +Yes + + +Beth +40 + + + +Nate +8 + +Sam +7 + + + +MBA +BA + +
+ + +Bruce Smith +
Strawberry Lane
+ +617.432.5607 +213.457.2190 + + + +675-00-4312 +
+ +Male +38 +Yes + + +Betsy +34 + + + +Ben +5 + +Lucy +2 + +Jake +1 + + +BA +
+ + +Joe Smith +
Green St.
+ +781.665.0539 + + + + +425-46-6982 +
+ +Male +34 +Yes + + +Lilla +38 + + + + +MA +BA + +
+
+
+ + +Melvin Weston +Liz Harris + +7 +8 +9 + + + + + +Caroline Weston +
Finchly Road
+ +715.264.8205 + + + + +09-46-8791 +
+ +Female +37 +No + + + +Assoc +
+ + +Betsy Weston +
Strawberry Lane
+ +617.432.5607 +213.457.2190 + + +123-46-9876 +
+ +Female +34 +Yes + + +Bruce +38 + + + +Ben +5 + +Lucy +2 + +Jake +1 + + + +MA +BS + +
+
+
+
\ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/Minitest.xsl 2015-01-09 15:41:44.360128919 -0800 @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 's phone number is . + +He is . + + +She is . + + + + + + + + is married to + . + + +Their children are + + + + + : + + :, + + and + + + +They have no kids + + + + + is not married. + + + + + + +The parents are: and + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/MinitestParam.xml 2015-01-09 15:41:44.631129342 -0800 @@ -0,0 +1,7 @@ + + + + one + 2 + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/MinitestParam.xsl 2015-01-09 15:41:44.925129801 -0800 @@ -0,0 +1,29 @@ + + + + + + + + + + + + 'default1n' + 'default2n' + default3n + + + + + :param1s: + :param2s: + :param3s: + + :param1n: + :param2n: + :param3n: + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/MinitestPerf.xml 2015-01-09 15:41:45.191130215 -0800 @@ -0,0 +1,262 @@ + + + + + + + + + Lew Smith + Ruth Smith + + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + + + + + + Andy Smith +
Stonefield Dr
+ + 483-23-5432 + + + + + 012-23-1234 +
+ + Male + 45 + Yes + + + Suzie + 45 + + + + Jules + 9 + + Daniel + 8 + + + + PA + BS + +
+ + +Tom Smith +
Pondside Lane
+ +508.257.2754 + + + + +274-76-2971 +
+ +Male +30 +Yes + + +Maggy +39 + + + +Joshua +7 + +Lauren +5 + + +BA +
+ + +Henry Smith +
Lakeview
+ +417.645.4954 + + + + +231-45-3590 +
+ +Male +40 +Yes + + +Beth +40 + + + +Nate +8 + +Sam +7 + + + +MBA +BA + +
+ + +Bruce Smith +
Strawberry Lane
+ +617.432.5607 +213.457.2190 + + + +675-00-4312 +
+ +Male +38 +Yes + + +Betsy +34 + + + +Ben +5 + +Lucy +2 + +Jake +1 + + +BA +
+ + +Joe Smith +
Green St.
+ +781.665.0539 + + + + +425-46-6982 +
+ +Male +34 +Yes + + +Lilla +38 + + + + +MA +BA + +
+
+
+ + +Melvin Weston +Liz Harris + +7 +8 +9 + + + + + +Caroline Weston +
Finchly Road
+ +715.264.8205 + + + + +09-46-8791 +
+ +Female +37 +No + + + +Assoc +
+ + +Betsy Weston +
Strawberry Lane
+ +617.432.5607 +213.457.2190 + + +123-46-9876 +
+ +Female +34 +Yes + + +Bruce +38 + + + +Ben +5 + +Lucy +2 + +Jake +1 + + + +MA +BS + +
+
+
+
\ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/MinitestPerf.xsl 2015-01-09 15:41:45.454130626 -0800 @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 's phone number is . + +He is . + + +She is . + + + + + + + + is married to + . + + +Their children are + + + + + : + + :, + + and + + + +They have no kids + + + + + is not married. + + + + + + +The parents are: and + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/OutputPropertiesHTML.xml 2015-01-09 15:41:45.715131033 -0800 @@ -0,0 +1,13 @@ + + + + + + + P-tag:beginCDATA? or not? + + li-tag:one + li-tag:two + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/OutputPropertiesHTML.xsl 2015-01-09 15:41:45.978131443 -0800 @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + xsl:text within HEAD tag + + + + <P>Fake 'p' element</P> + +

@   ~ © È

+ +
+ + + + + + + + + + + + +
    + +
+
+
--- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/ParameterTest.xml 2015-01-09 15:41:46.243131856 -0800 @@ -0,0 +1,7 @@ + + + + 1 + 2 + 3 + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/ParameterTest.xsl 2015-01-09 15:41:46.516132282 -0800 @@ -0,0 +1,59 @@ + + + + + + + + + + + + ABC + + +DEF + +notset + + + + + + + + GHI + + + + ,; + ,; + ,; + + : + + + ,; + ,; + ,; + + : + + + + -notset, + -blank, + -a, + -1, + + + + + + + + + Item-2-found + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/ParameterTest2.xml 2015-01-09 15:41:46.783132698 -0800 @@ -0,0 +1,7 @@ + + + + 11 + 22 + 33 + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/ParameterTest2.xsl 2015-01-09 15:41:47.058133128 -0800 @@ -0,0 +1,15 @@ + + + + + + + + + + + : + + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SAXImpIncl.xml 2015-01-09 15:41:47.320133536 -0800 @@ -0,0 +1,13 @@ + + + + Above Should be include-list then import-list + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SAXImpIncl.xsl 2015-01-09 15:41:47.573133931 -0800 @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SAXTest.xml 2015-01-09 15:41:47.831134333 -0800 @@ -0,0 +1,10 @@ + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SAXTest.xsl 2015-01-09 15:41:48.097134748 -0800 @@ -0,0 +1,11 @@ + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SAXdtd.dtd 2015-01-09 15:41:48.395135213 -0800 @@ -0,0 +1,9 @@ + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SAXdtd.xml 2015-01-09 15:41:48.677135653 -0800 @@ -0,0 +1,21 @@ + + + + + + +]> + + + Xalan-J© 1.x + Xalan-J&test-ent; 2.x + Xalan-C 1.x + + Xalan blah]]> documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SAXdtd.xsl 2015-01-09 15:41:48.960136094 -0800 @@ -0,0 +1,23 @@ + + + + + + + + + + Testing © entities &test-ent; here + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/StreamOutputFormat.xml 2015-01-09 15:41:49.311136642 -0800 @@ -0,0 +1,8 @@ + + + CDATA? or not? + + one + 2 + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/StreamOutputFormat.xsl 2015-01-09 15:41:49.604137099 -0800 @@ -0,0 +1,26 @@ + + + + + + + + CDATA? or not? + foo + + + bar + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SystemIdImpIncl.xml 2015-01-09 15:41:49.870137514 -0800 @@ -0,0 +1,14 @@ + + + + Above Should be include-list then import-list + This is SystemIdImpIncl.xml, used for setSystemId testing Note that different settings of systemIds will have different expected results! + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SystemIdImpIncl.xsl 2015-01-09 15:41:50.148137948 -0800 @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SystemIdTest.xml 2015-01-09 15:41:50.420138372 -0800 @@ -0,0 +1,11 @@ + + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/SystemIdTest.xsl 2015-01-09 15:41:50.688138790 -0800 @@ -0,0 +1,12 @@ + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerAPIHTMLFormat.xml 2015-01-09 15:41:50.956139208 -0800 @@ -0,0 +1,13 @@ + + + + + + + P-tag:beginCDATA? or not? + + li-tag:one + li-tag:two + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerAPIHTMLFormat.xsl 2015-01-09 15:41:51.218139617 -0800 @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + xsl:text within HEAD tag + + + + <P>Fake 'p' element</P> + +

@   ~ © È

+ +
+ + + + + + + + + + + + + +
    + +
+
+ + +
+
+ + +
+
+ + +
--- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerAPIOutputFormat.xml 2015-01-09 15:41:51.478140023 -0800 @@ -0,0 +1,8 @@ + + + CDATA? or not? + + one + 2 + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerAPIOutputFormat.xsl 2015-01-09 15:41:51.745140439 -0800 @@ -0,0 +1,26 @@ + + + + + + + + CDATA? or not? + foo + + + bar + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerAPIParam.xml 2015-01-09 15:41:52.011140854 -0800 @@ -0,0 +1,7 @@ + + + + one + 2 + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerAPIParam.xsl 2015-01-09 15:41:52.288141287 -0800 @@ -0,0 +1,23 @@ + + + + + + + + 'default1n' + 'default2n' + default3n + + + :param1s: + :param2s: + :param3s: + + :param1n: + :param2n: + :param3n: + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerAPIVar.xml 2015-01-09 15:41:52.547141690 -0800 @@ -0,0 +1,8 @@ + + + + + TransformerAPIVar-original + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerAPIVar.xsl 2015-01-09 15:41:52.811142102 -0800 @@ -0,0 +1,14 @@ + + + + + + + + + + Text and: + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerAPIVar2.xml 2015-01-09 15:41:53.076142516 -0800 @@ -0,0 +1,8 @@ + + + + + TransformerAPIVar2-changed + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerFactoryAPIModern.css 2015-01-09 15:41:53.347142939 -0800 @@ -0,0 +1,6 @@ + ARTICLE { font-family: sans-serif; background: white; color: black } + AUTHOR { margin: 1em; color: red } + HEADLINE { text-align: right; margin-bottom: 2em } + PARA { line-height: 1.5; margin-left: 15% } + INSTRUMENT { color: blue } + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/TransformerFactoryAPIModern.xml 2015-01-09 15:41:53.616143358 -0800 @@ -0,0 +1,13 @@ + + +
+ Fredrick the Great meets Bach + Johann Nikolaus Forkel + + One evening, just as he was getting his + flute ready and his + musicians were assembled, an officer brought him a list of + the strangers who had arrived. + +
--- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/URIResolverTest.xml 2015-01-09 15:41:53.878143767 -0800 @@ -0,0 +1,14 @@ + + + + Above Should be include-list then import-list + This is URIResolverTest.xml! + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/URIResolverTest.xsl 2015-01-09 15:41:54.161144209 -0800 @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + Various document() calls: + + , + + , + + . + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/cities.xml 2015-01-09 15:41:54.422144616 -0800 @@ -0,0 +1,13 @@ + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/cities.xsl 2015-01-09 15:41:54.734145103 -0800 @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/embeddedIdentity.xml 2015-01-09 15:41:55.001145519 -0800 @@ -0,0 +1,11 @@ + + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/identity.xml 2015-01-09 15:41:55.260145923 -0800 @@ -0,0 +1,10 @@ + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/identity.xsl 2015-01-09 15:41:55.518146326 -0800 @@ -0,0 +1,11 @@ + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/EmbeddedImpIncl.xml 2015-01-09 15:41:55.778146732 -0800 @@ -0,0 +1,15 @@ + + + + + Above Should be include-list then import-list + This is EmbeddedImpIncl.xml, used for setSystemId testing Note that different settings of systemIds will have different expected results! + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/EmbeddedImpIncl.xsl 2015-01-09 15:41:56.039147139 -0800 @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/EmbeddedRelative.xml 2015-01-09 15:41:56.302147549 -0800 @@ -0,0 +1,11 @@ + + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/EmbeddedRelative.xsl 2015-01-09 15:41:56.559147950 -0800 @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/MinitestDocument.xml 2015-01-09 15:41:56.825148365 -0800 @@ -0,0 +1,12 @@ + + + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/MinitestImport.xsl 2015-01-09 15:41:57.111148812 -0800 @@ -0,0 +1,35 @@ + + + + + + + + +They have grandchildren: + + + , + and + + + + +They should have grandchildren: + + + , + and + + + + +They got grandchildren: + + + , + and + + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/MinitestInclude.xsl 2015-01-09 15:41:57.383149236 -0800 @@ -0,0 +1,67 @@ + + + + + + + + + + Create an simplified output tree for each family + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/SimpleImport.xsl 2015-01-09 15:41:57.651149654 -0800 @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/SimpleInclude.xsl 2015-01-09 15:41:57.924150080 -0800 @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/StreamImpIncl.xml 2015-01-09 15:41:58.193150500 -0800 @@ -0,0 +1,13 @@ + + + + Above Should be include-list then import-list + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/StreamImpIncl.xsl 2015-01-09 15:41:58.461150918 -0800 @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/SystemIdImport.xsl 2015-01-09 15:41:58.734151344 -0800 @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/SystemIdInclude.xsl 2015-01-09 15:41:59.007151770 -0800 @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/citiesinclude.xsl 2015-01-09 15:41:59.271152182 -0800 @@ -0,0 +1,5 @@ + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/impincl/SimpleImport.xsl 2015-01-09 15:41:59.528152583 -0800 @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/impincl/impincl/SimpleInclude.xsl 2015-01-09 15:41:59.795153000 -0800 @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/systemid/impincl/EmbeddedRelative.xsl 2015-01-09 15:42:00.077153440 -0800 @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/systemid/impincl/SystemIdImport.xsl 2015-01-09 15:42:00.335153843 -0800 @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/systemid/impincl/SystemIdInclude.xsl 2015-01-09 15:42:00.594154247 -0800 @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xml/baz.xml 2015-01-09 15:42:00.915154748 -0800 @@ -0,0 +1,6 @@ + + +MyBaz + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xml/foo.xml 2015-01-09 15:42:01.191155178 -0800 @@ -0,0 +1,10 @@ + + + +MyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xml/subdir1/foo2.xml 2015-01-09 15:42:01.458155595 -0800 @@ -0,0 +1,2 @@ + +text in foo2.xml \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xml/subdir1/subdir2/foo3.xml 2015-01-09 15:42:01.731156021 -0800 @@ -0,0 +1,2 @@ + +text in foo3.xml \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xsl/baz.xsl 2015-01-09 15:42:02.048156516 -0800 @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xsl/foo.xsl 2015-01-09 15:42:02.317156936 -0800 @@ -0,0 +1,27 @@ + + + + + default param value + + + + + , + + + + + + + + + + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xsl/foo2.xsl 2015-01-09 15:42:02.598157374 -0800 @@ -0,0 +1,14 @@ + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xsl/foo3.xsl 2015-01-09 15:42:02.860157783 -0800 @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xsl/inc1/inc1.xsl 2015-01-09 15:42:03.128158202 -0800 @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/content/xsl/inc1/inc2/inc2.xsl 2015-01-09 15:42:03.408158639 -0800 @@ -0,0 +1,4 @@ + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/dom/DOMResultAPITest.java 2015-01-09 15:42:03.687159074 -0800 @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.dom; + +import java.io.FilePermission; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; +import jaxp.library.JAXPBaseTest; +import static jaxp.library.JAXPTestUtilities.compareSerializeDOMWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +/** + * + * API Coverage test for the DOMResult class of TRAX. + */ +public class DOMResultAPITest extends JAXPBaseTest { + /** + * Basic API coverage, constructor and set/get methods. + * + * @throws ParserConfigurationException in case of ServiceConfigurationError + * service configuration error or if the implementation is not + * available or cannot be instantiated. + */ + @Test + public void testCase1() throws ParserConfigurationException { + // Default no-arg ctor sets nothing (but needs special test for + // creating new doc when being transformed) + DOMResult defaultDOM = new DOMResult(); + assertNull(defaultDOM.getNode()); + assertNull(defaultDOM.getSystemId()); + + // ctor(Node) with a simple node + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node n = docBuilder.newDocument(); + DOMResult nodeDOM = new DOMResult(n); + assertEquals(nodeDOM.getNode(), n); + assertNull(nodeDOM.getSystemId()); + + DOMResult nodeDOMid = new DOMResult(n, "this-is-system-id"); + assertEquals(nodeDOMid.getNode(), n); + assertEquals(nodeDOMid.getSystemId(), "this-is-system-id"); + + DOMResult wackyDOM = new DOMResult(); + Node n2 = docBuilder.newDocument(); + wackyDOM.setNode(n2); + assertEquals(wackyDOM.getNode(), n2); + + wackyDOM.setSystemId("another-system-id"); + assertEquals(wackyDOM.getSystemId(), "another-system-id"); + } + + /** + * Basic functionality of DOMResults. + * Test 'blank' Result; reuse Results; swap Nodes; etc. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase2() throws Exception { + setPermissions(new FilePermission(System.getProperty("user.dir") + "/-", + "read, write"), + new FilePermission(System.getProperty("test.src") + "/-", + "read")); + String xslURI = filenameToURL(XML_DIR + "DOMTest.xsl"); + String xmlURI = filenameToURL(XML_DIR + "DOMTest.xml"); + String goldFile = GOLDEN_DIR + "DOMTest.out"; + + TransformerFactory factory = TransformerFactory.newInstance(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node xslNode = docBuilder.parse(new InputSource(xslURI)); + Node xmlNode = docBuilder.parse(new InputSource(xmlURI)); + + // Try to get templates, transformer from node + DOMSource xslSource = new DOMSource(xslNode); + Templates templates = factory.newTemplates(xslSource); + DOMSource xmlSource = new DOMSource(xmlNode); + + // Transforming into a DOMResult with a node is already + // well covered in DOMSourceAPITest and elsewhere + // Verify a 'blank' Result object gets filled up properly + DOMResult blankResult = new DOMResult(); + Transformer transformer = templates.newTransformer(); + transformer.transform(xmlSource, blankResult); + Node blankNode = blankResult.getNode(); + assertNotNull(blankNode); + assertTrue(compareSerializeDOMWithGold(goldFile, blankNode)); + + // Reuse the same result for multiple transforms + DOMResult reuseResult1 = new DOMResult(docBuilder.newDocument()); + transformer = templates.newTransformer(); + transformer.transform(xmlSource, reuseResult1); + Node reuseNode = reuseResult1.getNode(); + assertTrue(compareSerializeDOMWithGold(goldFile, reuseNode)); + + // So far it throws Exception as follows if you use same DOMResult: + // org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made + // to insert a node where it is not permitted. + DOMResult reuseResult2 = new DOMResult(docBuilder.newDocument()); + transformer = templates.newTransformer(); + transformer.transform(xmlSource, reuseResult2); + reuseNode = reuseResult2.getNode(); + assertTrue(compareSerializeDOMWithGold(goldFile, reuseNode)); + } +} \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/dom/DOMSourceAPITest.java 2015-01-09 15:42:03.960159500 -0800 @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.dom; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.compareSerializeDOMWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +/** + * API Coverage test for the DOMSource class of TRAX. + */ +public class DOMSourceAPITest extends JAXPFileBaseTest { + /** + * Basic API coverage, constructor and set/get methods. + * + * @throws ParserConfigurationException if the implementation is not + * available or cannot be instantiated. + */ + @Test + public void testCase1() throws ParserConfigurationException { + // Default no-arg ctor sets nothing (but needs special test for + // creating new doc when being transformed) + DOMSource defaultDOM = new DOMSource(); + assertNull(defaultDOM.getNode()); + assertNull(defaultDOM.getSystemId()); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node n = docBuilder.newDocument(); + DOMSource nodeDOM = new DOMSource(n); + assertEquals(nodeDOM.getNode(), n); + assertNull(nodeDOM.getSystemId()); + + DOMSource nodeDOMid = new DOMSource(n, "this-is-system-id"); + assertEquals(nodeDOMid.getNode(), n); + assertEquals(nodeDOMid.getSystemId(), "this-is-system-id"); + + DOMSource wackyDOM = new DOMSource(); + Node n2 = docBuilder.newDocument(); + wackyDOM.setNode(n2); + assertEquals(wackyDOM.getNode(), n2); + + wackyDOM.setSystemId("another-system-id"); + assertEquals(wackyDOM.getSystemId(), "another-system-id"); + } + + /** + * newTemplates on empty DOMSource throws TransformerConfigurationException. + * + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = TransformerConfigurationException.class) + public void negativeTestCase21() throws Exception { + // Startup a factory, create some nodes/DOMs + TransformerFactory factory = TransformerFactory.newInstance(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + // A blank DOM as an input stylesheet - what should happen? + DOMSource blankXSLDOM = new DOMSource(); + factory.newTemplates(blankXSLDOM); + } + + /** + * newTransformer on empty DOMSource throws TransformerConfigurationException. + * + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = TransformerConfigurationException.class) + public void negativeTestCase22() throws Exception { + // Startup a factory, create some nodes/DOMs + TransformerFactory factory = TransformerFactory.newInstance(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + // A blank DOM as an input stylesheet - what should happen? + DOMSource blankXSLDOM = new DOMSource(); + factory.newTransformer(blankXSLDOM); + } + + /** + * Validation with DOMSource on TransformerException. + * + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = TransformerException.class) + public void negativeTestCase24() throws Exception { + String xslFile = XML_DIR + "DOMImpIncl.xsl"; + String xslImpInclURI = filenameToURL(xslFile); + String xmlFile = XML_DIR + "DOMImpIncl.xml"; + String xmlImpInclURI = filenameToURL(xmlFile); + + // Startup a factory, create some nodes/DOMs + TransformerFactory factory = TransformerFactory.newInstance(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node xslImpInclNode = docBuilder.parse(new InputSource(xslImpInclURI)); + Node xmlImpInclNode = docBuilder.parse(new InputSource(xmlImpInclURI)); + + DOMSource xslDOM = new DOMSource(xslImpInclNode); + Transformer transformerXSL = factory.newTransformer(xslDOM); + DOMSource xmlDOM = new DOMSource(xmlImpInclNode); + DOMResult emptyResult = new DOMResult(); + transformerXSL.transform(xmlDOM, emptyResult); + } + + /** + * Blank DOMSource should parse without error. + * + * @throws Exception If any errors occur. + */ + @Test + public void positiveTestCase21() throws Exception { + String xslURI = filenameToURL(XML_DIR + "DOMTest.xsl"); + String xmlURI = filenameToURL(XML_DIR + "DOMTest.xml"); + String goldFile = GOLDEN_DIR + "DOMTest.out"; + + // Startup a factory, create some nodes/DOMs + TransformerFactory factory = TransformerFactory.newInstance(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node xslNode = docBuilder.parse(new InputSource(xslURI)); + Node xmlNode = docBuilder.parse(new InputSource(xmlURI)); + // Try to get templates, transformerXSL from node + DOMSource xslDOM = new DOMSource(xslNode); + Templates templates = factory.newTemplates(xslDOM); + assertNotNull(templates); + Transformer transformerXSL = factory.newTransformer(xslDOM); + assertNotNull(transformerXSL); + + // A blank DOM as an output of the transform - should auto-create a + // source Document + DOMSource xmlDOM = new DOMSource(xmlNode); + Node outNode = docBuilder.newDocument(); + DOMResult outResult = new DOMResult(outNode); + transformerXSL.transform(xmlDOM, outResult); + outNode = outResult.getNode(); + assertNotNull(outNode); + assertTrue(compareSerializeDOMWithGold(goldFile, outNode)); + } + + /** + * Validate DOMSource setting with systemid. + * + * @throws Exception If any errors occur. + */ + @Test + public void positiveTestCase22() throws Exception { + String xslImpInclFile = XML_DIR + "DOMImpIncl.xsl"; + String xslImpInclURI = filenameToURL(xslImpInclFile); + String xmlImpInclFile = XML_DIR + "DOMImpIncl.xml"; + String xmlImpInclURI = filenameToURL(xmlImpInclFile); + String goldImpInclFile = GOLDEN_DIR + "DOMImpIncl.out"; + + // Startup a factory, create some nodes/DOMs + TransformerFactory factory = TransformerFactory.newInstance(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node xslImpInclNode = docBuilder.parse(new InputSource(xslImpInclURI)); + Node xmlImpInclNode = docBuilder.parse(new InputSource(xmlImpInclURI)); + + DOMSource xslDOM = new DOMSource(xslImpInclNode); + // Note that inputName, xmlName are already URL'd + xslDOM.setSystemId(xslImpInclURI); + Transformer transformerXSL = factory.newTransformer(xslDOM); + DOMSource xmlDOM = new DOMSource(xmlImpInclNode); + // Do we really need to set SystemId on both XML and XSL? + xmlDOM.setSystemId(xmlImpInclFile); + DOMResult emptyResult = new DOMResult(); + transformerXSL.transform(xmlDOM, emptyResult); + Node outNode = emptyResult.getNode(); + assertNotNull(outNode); + assertTrue(compareSerializeDOMWithGold(goldImpInclFile, outNode)); + } + + /** + * Validate simple transform on DOMSource. + * + * @throws Exception If any errors occur. + */ + @Test + public void positiveTestCase23() throws Exception { + String xslURI = filenameToURL(XML_DIR + "DOMTest.xsl"); + String xmlURI = filenameToURL(XML_DIR + "DOMTest.xml"); + String goldFile = GOLDEN_DIR + "DOMTest.out"; + + // Startup a factory, create some nodes/DOMs + TransformerFactory factory = TransformerFactory.newInstance(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node xslNode = docBuilder.parse(new InputSource(xslURI)); + Node xmlNode = docBuilder.parse(new InputSource(xmlURI)); + // Try to get templates, transformerXSL from node + DOMSource xslDOM = new DOMSource(xslNode); + Templates templates = factory.newTemplates(xslDOM); + assertNotNull(templates); + Transformer transformerXSL = factory.newTransformer(xslDOM); + assertNotNull(transformerXSL); + + // A simple DOM-DOM-DOM transform + DOMSource xmlDOM = new DOMSource(xmlNode); + Node outNode = docBuilder.newDocument(); + DOMResult outDOM = new DOMResult(outNode); + transformerXSL.transform(xmlDOM, outDOM); + Node gotNode = outDOM.getNode(); + assertNotNull(gotNode); + assertTrue(compareSerializeDOMWithGold(goldFile, gotNode)); + } + + /** + * Test re-usage source for the stylesheet. It expects same result. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase3() throws Exception { + String xslFile = XML_DIR + "DOMTest.xsl"; + String xmlFile = XML_DIR + "DOMTest.xml"; + String goldFile = GOLDEN_DIR + "DOMTest.out"; + + String xslImpInclFile = XML_DIR + "DOMImpIncl.xsl"; + String xmlImpInclFile = XML_DIR + "DOMImpIncl.xml"; + String goldImpInclFile = GOLDEN_DIR + "DOMImpIncl.out"; + + // Startup a factory, create some nodes/DOMs + TransformerFactory factory = TransformerFactory.newInstance(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node xslNode = docBuilder.parse(new InputSource(xslFile)); + Node xmlNode = docBuilder.parse(new InputSource(xmlFile)); + Node xslImpInclNode = docBuilder.parse(new InputSource(xslImpInclFile)); + Node xmlImpInclNode = docBuilder.parse(new InputSource(xmlImpInclFile)); + + // Re-use DOMSource for stylesheet + DOMSource xmlSource1 = new DOMSource(xmlNode); + DOMResult result1 = new DOMResult(docBuilder.newDocument()); + DOMSource xslSource = new DOMSource(xslNode); + Transformer transformer1 = factory.newTransformer(xslSource); + transformer1.transform(xmlSource1, result1); + Node node1 = result1.getNode(); + assertTrue(compareSerializeDOMWithGold(goldFile, node1)); + // Use same Source for the stylesheet + DOMSource xmlSource2 = new DOMSource(xmlNode); + DOMResult result2 = new DOMResult(docBuilder.newDocument()); + Transformer transformer2 = factory.newTransformer(xslSource); + transformer2.transform(xmlSource2, result2); + Node node2 = result2.getNode(); + assertTrue(compareSerializeDOMWithGold(goldFile, node2)); + + // Re-use DOMSource for XML doc; with the same stylesheet + DOMResult result3 = new DOMResult(docBuilder.newDocument()); + Transformer transformer3 = factory.newTransformer(xslSource); + transformer3.transform(xmlSource2, result3); + Node node3 = result3.getNode(); + assertTrue(compareSerializeDOMWithGold(goldFile, node3)); + + // Re-use DOMSource after setNode to different one + DOMSource xmlSource = new DOMSource(xmlNode); + // Use same Sources, but change Nodes for xml,xsl + xmlSource.setNode(xmlImpInclNode); + xmlSource.setSystemId(xmlImpInclFile); + xslSource.setNode(xslImpInclNode); + xslSource.setSystemId(xslImpInclFile); + transformer2 = factory.newTransformer(xslSource); + result2 = new DOMResult(docBuilder.newDocument()); + transformer2.transform(xmlSource, result2); + node2 = result2.getNode(); + assertTrue(compareSerializeDOMWithGold(goldImpInclFile, node2)); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/DOMImpIncl.out 2015-01-09 15:42:04.239159936 -0800 @@ -0,0 +1,12 @@ + + + Above Should be include-list then import-list + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/DOMTest.out 2015-01-09 15:42:04.534160396 -0800 @@ -0,0 +1,9 @@ + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/EmbeddedFragment.out 2015-01-09 15:42:04.814160833 -0800 @@ -0,0 +1,7 @@ + + +Hello + +Goodbye + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/EmbeddedRelative0.out 2015-01-09 15:42:05.094161270 -0800 @@ -0,0 +1,10 @@ + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/EmbeddedRelative1.out 2015-01-09 15:42:05.412161766 -0800 @@ -0,0 +1,10 @@ + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/EmbeddedRelative2.out 2015-01-09 15:42:05.717162242 -0800 @@ -0,0 +1,10 @@ + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/EmbeddedType.out 2015-01-09 15:42:05.989162667 -0800 @@ -0,0 +1,2 @@ + +Xalan-J 1.xXalan-J 2.xXalan-C 1.x \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ErrorListenerTest.out 2015-01-09 15:42:06.266163099 -0800 @@ -0,0 +1,10 @@ + + + warning(TransformerException) + error(TransformerException) + fatalError(TransformerException) + + ErrorListener API's + Defined Above + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_1.out 2015-01-09 15:42:06.568163571 -0800 @@ -0,0 +1,4 @@ + + +MyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_10.out 2015-01-09 15:42:06.853164016 -0800 @@ -0,0 +1,3 @@ + +hello to you!, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_11.out 2015-01-09 15:42:07.121164434 -0800 @@ -0,0 +1,6 @@ + + +hello to me!, text from my-var in inc2.xsl +MyBar + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_12.out 2015-01-09 15:42:07.394164860 -0800 @@ -0,0 +1,3 @@ + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_13.out 2015-01-09 15:42:07.665165283 -0800 @@ -0,0 +1,3 @@ + +default param value, text from my-var in inc2.xslMyBaz + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_14.out 2015-01-09 15:42:07.929165695 -0800 @@ -0,0 +1,3 @@ + +MyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_15.out 2015-01-09 15:42:08.226166159 -0800 @@ -0,0 +1,3 @@ + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_2.out 2015-01-09 15:42:08.497166582 -0800 @@ -0,0 +1,6 @@ + + +default param value, text from my-var in inc2.xsl +MyBar + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_3.out 2015-01-09 15:42:08.794167045 -0800 @@ -0,0 +1,3 @@ + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_4.out 2015-01-09 15:42:09.060167461 -0800 @@ -0,0 +1,3 @@ + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_5.out 2015-01-09 15:42:09.331167884 -0800 @@ -0,0 +1,3 @@ + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_6.out 2015-01-09 15:42:09.601168305 -0800 @@ -0,0 +1,3 @@ + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_7.out 2015-01-09 15:42:09.872168728 -0800 @@ -0,0 +1,6 @@ + + +default param value, text from my-var in inc2.xsl +MyBar + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_8.out 2015-01-09 15:42:10.158169175 -0800 @@ -0,0 +1,3 @@ + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/ExamplesTest_9.out 2015-01-09 15:42:10.510169724 -0800 @@ -0,0 +1,3 @@ + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/Minitest-xalanj2.out 2015-01-09 15:42:10.786170155 -0800 @@ -0,0 +1,82 @@ + + + + + + +Lew Smith +Ruth Smith + + + + +Julie +Daniel +Andy + + +Joshua +Lauren +Thomas + + +Nathaniel +Samual +Henry + + +Benjamin +Lucy +Jake +Bruce +Joseph + + + +The Smith +The parents are: Lewis and Ruth Smith +They have 9 grandchildren: Julie, Nathaniel, Joshua, Daniel, Samual, Lauren, Benjamin, Lucy, and Jake + Andy Smith's phone number is 483-23-5432. +He is 45. Andy is married to Suzie. +Their children are Jules:9, and Daniel:8 + Bruce Smith's phone number is 213.457.2190. +He is 38. Bruce is married to Betsy. +Their children are Ben:5, Lucy:2, and Jake:1 + Henry Smith's phone number is 417.645.4954. +He is 40. Henry is married to Beth. +Their children are Nate:8, and Sam:7 + Joe Smith's phone number is 781.665.0539. +He is 34. Joseph is married to Lilla. +They have no kids + + Tom Smith's phone number is 508.257.2754. +He is 30. Thomas is married to Maggy. +Their children are Joshua:7, and Lauren:5 + + + + +Melvin Weston +Liz Harris + + +Caroline + + +Benjamin +Lucy +Jake +Betsy + + + +The Westons +The parents are: Melvin and Liz Harris +They have 3 grandchildren: Benjamin, Lucy, and Jake + Betsy Weston's phone number is 213.457.2190. +She is 34. Betsy is married to Bruce. +Their children are Ben:5, Lucy:2, and Jake:1 + Caroline Weston's phone number is 715.264.8205. +She is 37. Caroline is not married. + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/MinitestParam.out 2015-01-09 15:42:11.050170567 -0800 @@ -0,0 +1,3 @@ + + :param1s: 1234 :param2s: default2s :param3s: + :param1n: new-param1n-value :param2n: 'default2n' :param3n: default3n --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/MinitestPerf.out 2015-01-09 15:42:11.316170982 -0800 @@ -0,0 +1,82 @@ + + + + + + +Lew Smith +Ruth Smith + + + + +Julie +Daniel +Andy + + +Joshua +Lauren +Thomas + + +Nathaniel +Samual +Henry + + +Benjamin +Lucy +Jake +Bruce +Joseph + + + +The Smith +The parents are: Lewis and Ruth Smith +They have 9 grandchildren: Julie, Nathaniel, Joshua, Daniel, Samual, Lauren, Benjamin, Lucy, and Jake + Andy Smith's phone number is 483-23-5432. +He is 45. Andy is married to Suzie. +Their children are Jules:9, and Daniel:8 + Bruce Smith's phone number is 213.457.2190. +He is 38. Bruce is married to Betsy. +Their children are Ben:5, Lucy:2, and Jake:1 + Henry Smith's phone number is 417.645.4954. +He is 40. Henry is married to Beth. +Their children are Nate:8, and Sam:7 + Joe Smith's phone number is 781.665.0539. +He is 34. Joseph is married to Lilla. +They have no kids + + Tom Smith's phone number is 508.257.2754. +He is 30. Thomas is married to Maggy. +Their children are Joshua:7, and Lauren:5 + + + + +Melvin Weston +Liz Harris + + +Caroline + + +Benjamin +Lucy +Jake +Betsy + + + +The Westons +The parents are: Melvin and Liz Harris +They have 3 grandchildren: Benjamin, Lucy, and Jake + Betsy Weston's phone number is 213.457.2190. +She is 34. Betsy is married to Bruce. +Their children are Ben:5, Lucy:2, and Jake:1 + Caroline Weston's phone number is 715.264.8205. +She is 37. Caroline is not married. + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/OutputPropertiesHTML.out 2015-01-09 15:42:11.580171394 -0800 @@ -0,0 +1,18 @@ + + + + +title-tag:textxsl:text within HEAD tag + +

P-tag:beginCDATA? or not?

+
    + + +li-tag:one + +li-tag:two + + +

Fake 'p' element

@   ~ © È

+ + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/SAXImpIncl.out 2015-01-09 15:42:11.870171847 -0800 @@ -0,0 +1,13 @@ + + + + Above Should be include-list then import-list + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/SAXTest.out 2015-01-09 15:42:12.145172276 -0800 @@ -0,0 +1,10 @@ + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/SAXdtd.out 2015-01-09 15:42:12.413172695 -0800 @@ -0,0 +1,10 @@ + +Testing © entities an-xsl-entity here + Xalan-J© 1.x + Xalan-Jan-xml-entity 2.x + Xalan-C 1.x + + Xalan this is a CDATA section blah<?<!/>blah documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/StreamImpIncl.out 2015-01-09 15:42:12.691173129 -0800 @@ -0,0 +1,13 @@ + + + Above Should be include-list then import-list + This is SystemIdImpIncl.xml, used for setSystemId testing Note that different settings of systemIds will have different expected results! + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/StreamOutputFormat.out 2015-01-09 15:42:12.961173550 -0800 @@ -0,0 +1,10 @@ + + + +foo +bar + one + 2 + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/SystemIdImpInclHttp.out 2015-01-09 15:42:13.243173991 -0800 @@ -0,0 +1,14 @@ + + + + Above Should be include-list then import-list + This is SystemIdImpIncl.xml, used for setSystemId testing Note that different settings of systemIds will have different expected results! + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/SystemIdImpInclLevel0.out 2015-01-09 15:42:13.545174462 -0800 @@ -0,0 +1,13 @@ + + + Above Should be include-list then import-list + This is SystemIdImpIncl.xml, used for setSystemId testing Note that different settings of systemIds will have different expected results! + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/SystemIdImpInclLevel1.out 2015-01-09 15:42:13.816174885 -0800 @@ -0,0 +1,13 @@ + + + Above Should be include-list then import-list + This is SystemIdImpIncl.xml, used for setSystemId testing Note that different settings of systemIds will have different expected results! + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/SystemIdImpInclLevel2.out 2015-01-09 15:42:14.092175316 -0800 @@ -0,0 +1,13 @@ + + + Above Should be include-list then import-list + This is SystemIdImpIncl.xml, used for setSystemId testing Note that different settings of systemIds will have different expected results! + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/SystemIdTest.out 2015-01-09 15:42:14.366175744 -0800 @@ -0,0 +1,10 @@ + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/TransformerAPIHTMLFormat.out 2015-01-09 15:42:14.645176180 -0800 @@ -0,0 +1,19 @@ + + + +title-tag:textxsl:text within HEAD tag + +

P-tag:beginCDATA? or not?
+


+

+
    + + +li-tag:one + +li-tag:two + + +

Fake 'p' element

@   ~ © È

+ + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/TransformerAPIOutputFormatUTF16.out 2015-01-09 15:42:14.919176607 -0800 @@ -0,0 +1,9 @@ + + +foo +bar + one + 2 + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/TransformerAPIParam.out 2015-01-09 15:42:15.226177087 -0800 @@ -0,0 +1,4 @@ + + :param1s:'test-param-1s' :param2s:default2s :param3s:new value3s + :param1n:1234 :param2n:'default2n' :param3n:default3n + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/TransformerAPIVar.out 2015-01-09 15:42:15.509177529 -0800 @@ -0,0 +1 @@ +TransformerAPIVar-originalText and:TransformerAPIVar-original \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/TransformerAPIVar2.out 2015-01-09 15:42:15.779177950 -0800 @@ -0,0 +1 @@ +TransformerAPIVar2-changedText and:TransformerAPIVar2-changed \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/URIResolverTest.out 2015-01-09 15:42:16.052178376 -0800 @@ -0,0 +1,25 @@ +Various document() calls: + + + +, + + + +, + + + +. + + Above Should be include-list then import-list + This is URIResolverTest.xml! + Should be matched-by-import + Should be matched-by-include + Should be matched-by-import-also + + Should be matched-by-main + Should be matched-by-main + + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/baz.out 2015-01-09 15:42:16.330178811 -0800 @@ -0,0 +1,4 @@ + + +default param value, text from my-var in inc2.xslMyBaz + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/cities-indent-no.out 2015-01-09 15:42:16.604179238 -0800 @@ -0,0 +1,2 @@ + +ParisNiceLyonRomaMilanoFirenzeNapoliMadridBarcelona \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/cities-method-text.out 2015-01-09 15:42:16.868179651 -0800 @@ -0,0 +1 @@ +ParisNiceLyonRomaMilanoFirenzeNapoliMadridBarcelona \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/cities.out 2015-01-09 15:42:17.147180086 -0800 @@ -0,0 +1,17 @@ + + +Paris +Nice +Lyon + + +Roma +Milano +Firenze +Napoli + + +Madrid +Barcelona + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/citiesSerialized.out 2015-01-09 15:42:17.413180502 -0800 @@ -0,0 +1,2 @@ + +ParisNiceLyonRomaMilanoFirenzeNapoliMadridBarcelona \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/embeddedIdentity.out 2015-01-09 15:42:17.683180923 -0800 @@ -0,0 +1,9 @@ + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/foo.out 2015-01-09 15:42:17.956181349 -0800 @@ -0,0 +1,4 @@ + + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/fooSAX.out 2015-01-09 15:42:18.268181837 -0800 @@ -0,0 +1,4 @@ + + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/fooSAX2.out 2015-01-09 15:42:18.538182258 -0800 @@ -0,0 +1,4 @@ + + +default param value, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/identity.out 2015-01-09 15:42:18.833182719 -0800 @@ -0,0 +1,9 @@ + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/output.out 2015-01-09 15:42:19.103183140 -0800 @@ -0,0 +1,8 @@ + + + + +default param value, text from my-var in inc2.xsl +MyBar + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/param1.out 2015-01-09 15:42:19.436183660 -0800 @@ -0,0 +1,4 @@ + + +hello to you!, text from my-var in inc2.xslMyBar + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/golden/param2.out 2015-01-09 15:42:19.759184165 -0800 @@ -0,0 +1,8 @@ + + + + +hello to me!, text from my-var in inc2.xsl +MyBar + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/impincl/EmbeddedRelative.xml 2015-01-09 15:42:20.021184574 -0800 @@ -0,0 +1,11 @@ + + + + Xalan-J 1.x + Xalan-J 2.x + Xalan-C 1.x + + Xalan documentation + Xalan tests + + \ No newline at end of file --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/impincl/EmbeddedRelative.xsl 2015-01-09 15:42:20.281184980 -0800 @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/impincl/SystemIdImport.xsl 2015-01-09 15:42:20.543185389 -0800 @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/impincl/SystemIdInclude.xsl 2015-01-09 15:42:20.798185787 -0800 @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/sax/SAXResultAPITest.java 2015-01-09 15:42:21.108186271 -0800 @@ -0,0 +1,291 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.sax; + +import java.io.FileOutputStream; +import java.io.FilePermission; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Result; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.SAXResult; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import org.apache.qetest.xsl.CheckingContentHandler; +import org.apache.qetest.xsl.CheckingLexicalHandler; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertSame; +import static org.testng.Assert.fail; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.Test; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.ext.LexicalHandler; + +/** + * API Coverage test for the SAXResult class of TRAX. + */ +public class SAXResultAPITest extends JAXPBaseTest { + + /** + * Nonsense systemId for various tests. + */ + private static final String NONSENSE_SYSTEMID = "file:///nonsense-system-id"; + + /** + * Basic API coverage, constructor and set/get methods. + * + * @throws TransformerConfigurationException Thrown in case of + * ServiceConfigurationError service configuration error or if the + * implementation is not available or cannot be instantiated. + */ + @Test + public void testCase1() throws TransformerConfigurationException { + + // Default no-arg ctor sets nothing + SAXResult defaultSAX = new SAXResult(); + assertNull(defaultSAX.getHandler()); + assertNull(defaultSAX.getLexicalHandler()); + assertNull(defaultSAX.getSystemId()); + + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + // ctor(Handler) with identity transformer, which is both + // a ContentHandler and LexicalHandler + ContentHandler handler = (ContentHandler) saxFactory.newTransformerHandler(); + SAXResult handlerSAX = new SAXResult(handler); + assertSame(handlerSAX.getHandler(), handler); + assertNull(handlerSAX.getLexicalHandler()); + assertNull(handlerSAX.getSystemId()); + + // ctor(Handler) with LoggingContentHandler, which not + // a LexicalHandler, so it can't be cast + ContentHandler nonLexHandler = new CheckingContentHandler(); + SAXResult otherHandlerSAX = new SAXResult(nonLexHandler); + assertSame(otherHandlerSAX.getHandler(), nonLexHandler); + assertNull(otherHandlerSAX.getLexicalHandler()); + assertNull(otherHandlerSAX.getSystemId()); + + // Note the Javadoc in SAXResult which talks about + // automatically casting the ContentHandler into + // a LexicalHandler: this cannot be tested alone + // here, since it's the Transformer that does that + // internally if necessary, and it may not get set + // back into the SAXResult object itself + // set/getHandler API coverage + SAXResult wackySAX = new SAXResult(); + wackySAX.setHandler(handler); // isa LexicalHandler also + assertSame(wackySAX.getHandler(), handler); + assertNull(wackySAX.getLexicalHandler()); + + // set/getLexicalHandler API coverage + LexicalHandler lexHandler = new CheckingLexicalHandler(); + wackySAX.setLexicalHandler(lexHandler); // SCUU4SPPMV - does not work + assertSame(wackySAX.getLexicalHandler(), lexHandler); + assertSame(wackySAX.getHandler(), handler); + + // set/getHandler API coverage, setting to null, which + // should work here but can't be used legally + wackySAX.setHandler(null); + assertNull(wackySAX.getHandler()); + assertSame(wackySAX.getLexicalHandler(), lexHandler); + + wackySAX.setLexicalHandler(null); + assertNull(wackySAX.getLexicalHandler()); + + // set/getSystemId API coverage + wackySAX.setSystemId(NONSENSE_SYSTEMID); + assertEquals(wackySAX.getSystemId(), NONSENSE_SYSTEMID); + wackySAX.setSystemId(null); + assertNull(wackySAX.getSystemId()); + + } + + /** + * Save system property for restoring. + */ + @BeforeGroups (groups = {"accessLocalFiles"}) + public void setFilePermissions() { + setPermissions(new FilePermission(XML_DIR + "/-", "read"), + new FilePermission(GOLDEN_DIR + "/-", "read"), + new FilePermission(USER_DIR + "-", "read, write")); + } + + /** + * Restore the system property. + */ + @AfterGroups (groups = {"readLocalFiles"}) + public void restoreFilePermissions() { + setPermissions(); + } + + /** + * Basic functionality of SAXResults. + * @throws Exception If any errors occur. + */ + @Test(groups = {"accessLocalFiles"}) + public void testCase2() throws Exception { + String xslFile = XML_DIR + "SAXTest.xsl"; + String xmlFile = XML_DIR + "SAXTest.xml"; + String goldFile = GOLDEN_DIR + "SAXTest.out"; + String outputFile = USER_DIR + "SAXTest_02.out"; + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + Templates streamTemplates = saxFactory.newTemplates(new StreamSource(filenameToURL(xslFile))); + // Use a TransformerHandler for serialization: this + // supports ContentHandler and can replace the + // Xalan/Xerces specific Serializers we used to use + TransformerHandler tHandler = saxFactory.newTransformerHandler(); + tHandler.setResult(new StreamResult(fos)); + SAXResult saxResult = new SAXResult(tHandler); + + // Just do a normal transform to this result + Transformer transformer = streamTemplates.newTransformer(); + transformer.transform(new StreamSource(filenameToURL(xmlFile)), saxResult); + } + compareWithGold(goldFile, outputFile); + } + + /** + * Detailed functionality of SAXResults: setLexicalHandler. + * + * @throws Exception If any errors occur. + */ + @Test(groups = {"accessLocalFiles"}) + public void testCase3() throws Exception { + String xslFile = XML_DIR + "SAXdtd.xsl"; + String xmlFile = XML_DIR + "SAXdtd.xml"; + String goldFile = GOLDEN_DIR + "SAXdtd.out"; + String outputFile = USER_DIR + "SAXdtd.out"; + + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + Templates streamTemplates = saxFactory.newTemplates(new StreamSource(filenameToURL(xslFile))); + TransformerHandler tHandler = saxFactory.newTransformerHandler(); + tHandler.setResult(new StreamResult(fos)); + + SAXResult saxResult = new SAXResult(); + // Add a contentHandler that logs out info about the transform, and + // that passes-through calls back to the original tHandler. + CheckingContentHandler lch = new CheckingContentHandler(); + lch.setDefaultHandler(tHandler); + saxResult.setHandler(lch); + + // Add a lexicalHandler that logs out info about the transform, and + // that passes-through calls back to the original tHandler + CheckingLexicalHandler llh = new CheckingLexicalHandler(tHandler); + saxResult.setLexicalHandler(llh); + + // Just do a normal transform to this result + Transformer transformer = streamTemplates.newTransformer(); + transformer.transform(new StreamSource(filenameToURL(xmlFile)), saxResult); + fail("Excepted a TransformerException"); + } catch (TransformerException expected) {} + compareWithGold(goldFile, outputFile); + + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + TransformerHandler tHandler = saxFactory.newTransformerHandler(); + Result realResult = new StreamResult(fos); + tHandler.setResult(realResult); + + SAXResult saxResult = new SAXResult(); + CheckingContentHandler lch = new CheckingContentHandler(); + lch.setDefaultHandler(tHandler); + saxResult.setHandler(lch); + + CheckingLexicalHandler llh = new CheckingLexicalHandler(tHandler); + saxResult.setLexicalHandler(llh); + + // Do an identityTransform to this result + Transformer identityTransformer = TransformerFactory.newInstance().newTransformer(); + identityTransformer.transform(new StreamSource(filenameToURL(xmlFile)), saxResult); + fail("Excepted a TransformerException"); + } catch (TransformerException expected) {} + compareWithGold(goldFile, outputFile); + + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + // Validate a DOMSource to a logging SAXResult, as above + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + Node xmlNode = docBuilder.parse(new InputSource(filenameToURL(xmlFile))); + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + + // Have an actual handler that does the physical output + TransformerHandler tHandler = saxFactory.newTransformerHandler(); + Templates streamTemplates = saxFactory.newTemplates(new StreamSource(filenameToURL(xslFile))); + tHandler.setResult(new StreamResult(fos)); + + SAXResult saxResult = new SAXResult(); + // Add a contentHandler that logs out info about the + // transform, and that passes-through calls back + // to the original tHandler + CheckingContentHandler lch = new CheckingContentHandler(); + lch.setDefaultHandler(tHandler); + saxResult.setHandler(lch); + + // Add a lexicalHandler that logs out info about the + // transform, and that passes-through calls back + // to the original tHandler + CheckingLexicalHandler llh = new CheckingLexicalHandler(tHandler); + saxResult.setLexicalHandler(llh); + + // Just do a normal transform to this result + streamTemplates.newTransformer().transform(new DOMSource(xmlNode), saxResult); + fail("Excepted a TransformerException"); + } catch (TransformerException expected) {} + compareWithGold(goldFile, outputFile); + } + + /** + * Negative test: SAXResult without a handler throws TransformerException. + * + * @throws TransformerException If an unrecoverable error occurs during the + * course of the transformation. + */ + @Test(expectedExceptions = TransformerException.class) + public void negativeTransform() throws TransformerException { + setPermissions(new FilePermission(XML_DIR + "/-", "read")); + String xslFile = XML_DIR + "SAXTest.xsl"; + String xmlFile = XML_DIR + "SAXTest.xml"; + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + Templates streamTemplates = saxFactory.newTemplates(new StreamSource(filenameToURL(xslFile))); + // Just do a normal transform to this result + Transformer transformer = streamTemplates.newTransformer(); + transformer.transform(new StreamSource(filenameToURL(xmlFile)), new SAXResult()); + setPermissions(); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/sax/SAXSourceAPITest.java 2015-01-09 15:42:21.381186698 -0800 @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.sax; + +import java.io.FileInputStream; +import java.io.FilePermission; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXSource; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.stream.StreamResult; +import jaxp.library.JAXPBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; + +/** + * API Coverage test for the SAXSource class of TRAX. + */ +public class SAXSourceAPITest extends JAXPBaseTest { + + /** + * Nonsense systemId for various tests. + */ + private static final String NONSENSE_SYSTEMID = "file:///nonsense-system-id"; + + /** + * Basic API coverage, constructor and set/get methods. + * + * @throws Exception If any errors occur. + */ + public void testCase1() throws Exception { + // Default no-arg ctor sets nothing (but needs special test for + // creating new doc when being transformed) + SAXSource defaultSAX = new SAXSource(); + assertNull(defaultSAX.getInputSource()); + assertNull(defaultSAX.getXMLReader()); + assertNull(defaultSAX.getSystemId()); + // ctor(InputSource) with an InputSource() + InputSource srcNoID = new InputSource(); + SAXSource saxSrcNoID = new SAXSource(srcNoID); + assertEquals(saxSrcNoID.getInputSource(), srcNoID, + "SAXSource(new InputSource()) has InputSource: " + + saxSrcNoID.getInputSource()); + assertNull(saxSrcNoID.getXMLReader()); + assertNull(saxSrcNoID.getSystemId()); + + // ctor(InputSource) with an InputSource("sysId") + InputSource srcWithID = new InputSource(NONSENSE_SYSTEMID); + SAXSource saxSrcWithID = new SAXSource(srcWithID); + assertEquals(saxSrcWithID.getInputSource(), srcWithID); + assertNull(saxSrcWithID.getXMLReader()); + assertEquals(saxSrcWithID.getSystemId(), NONSENSE_SYSTEMID); + + // ctor(XMLReader, InputSource) + XMLReader reader2 = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + SAXSource saxSrcReaderID2 = new SAXSource(reader2, srcWithID); + assertEquals(saxSrcReaderID2.getInputSource(), srcWithID); + assertEquals(saxSrcReaderID2.getXMLReader(), reader2); + assertEquals(saxSrcReaderID2.getSystemId(), NONSENSE_SYSTEMID); + + // ctor(XMLReader, InputSource) + // Be sure to use the JAXP methods only! + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + SAXParser saxParser = factory.newSAXParser(); + XMLReader reader = saxParser.getXMLReader(); + SAXSource saxSrcReaderID = new SAXSource(reader, srcWithID); + assertEquals(saxSrcReaderID.getInputSource(), srcWithID); + assertEquals(saxSrcReaderID.getXMLReader(), reader); + assertEquals(saxSrcReaderID.getSystemId(), NONSENSE_SYSTEMID); + + // ctor(null InputSource) - note it won't actually + // be able to be used as a Source in real life + SAXSource saxNullSrc = new SAXSource(null); + assertNull(saxNullSrc.getInputSource()); + assertNull(saxNullSrc.getXMLReader()); + assertNull(saxNullSrc.getSystemId()); + + // ctor(null Reader, null InputSource) + SAXSource saxNullSrc2 = new SAXSource(null, null); + assertNull(saxNullSrc2.getInputSource()); + assertNull(saxNullSrc2.getXMLReader()); + assertNull(saxNullSrc2.getSystemId()); + + // Validate various simple set/get methods + SAXSource wackySAX = new SAXSource(); + + // Validate setting systemId auto-creates InputSource + // with that systemId + wackySAX.setSystemId(NONSENSE_SYSTEMID); + assertEquals(wackySAX.getSystemId(), NONSENSE_SYSTEMID); + assertNotNull(wackySAX.getInputSource()); + InputSource newIS = wackySAX.getInputSource(); + assertEquals(newIS.getSystemId(), NONSENSE_SYSTEMID); + + // API Coverage set/getSystemId + wackySAX.setSystemId("another-system-id"); + assertEquals(wackySAX.getSystemId(), "another-system-id"); + InputSource gotIS = wackySAX.getInputSource(); + assertEquals(gotIS.getSystemId(), "another-system-id"); + // setting to null explicitly + wackySAX.setSystemId(null); + assertNull(wackySAX.getSystemId()); + assertNull(wackySAX.getInputSource().getSystemId()); + + // API Coverage set/getInputSource + InputSource anotherIS = new InputSource(NONSENSE_SYSTEMID); + wackySAX.setInputSource(anotherIS); + assertEquals(wackySAX.getInputSource(), anotherIS); + assertEquals(wackySAX.getSystemId(), NONSENSE_SYSTEMID); + + // API Coverage set/getXMLReader + assertNull(wackySAX.getXMLReader(), null); + // Be sure to use the JAXP methods only! + saxParser = factory.newSAXParser(); + XMLReader wackyReader = saxParser.getXMLReader(); + wackySAX.setXMLReader(wackyReader); + assertEquals(wackySAX.getXMLReader(), wackyReader); + wackySAX.setXMLReader(null); + assertNull(wackySAX.getXMLReader()); + + } + + /** + * Basic functionality of SAXSources. Use them in simple transforms, + * with/without systemId set. + * + * @throws Exception If any errors occur. + */ + public void testCase2() throws Exception { + setPermissions(new FilePermission(XML_DIR + "/-", "read"), + new FilePermission(USER_DIR + "-", "read, write")); + String xslURI = filenameToURL(XML_DIR + "SAXTest.xsl"); + String xmlFile = XML_DIR + "SAXTest.xml"; + String xmlURI = filenameToURL(XML_DIR + "SAXTest.xml"); + String goldFile = GOLDEN_DIR + "SAXTest.out"; + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + try (FileInputStream xmlFis = new FileInputStream(xmlFile);) { + Templates streamTemplates = saxFactory.newTemplates(new SAXSource(new InputSource(xslURI))); + assertNotNull(streamTemplates); + + Transformer transformer1 = saxFactory.newTransformer(new SAXSource(new InputSource(xslURI))); + assertNotNull(transformer1); + // Validate process of a stylesheet using a simple SAXSource with a URL + SAXSource xslSAXSrc = new SAXSource(new InputSource(xslURI)); + Templates templates = saxFactory.newTemplates(xslSAXSrc); + assertNotNull(templates); + + xslSAXSrc = new SAXSource(new InputSource(xslURI)); + Transformer transformer2 = saxFactory.newTransformer(xslSAXSrc); + assertNotNull(transformer2); + + Transformer transformer3 = templates.newTransformer(); + assertNotNull(transformer3); + + SAXSource xmlSAXSrc = new SAXSource(new InputSource(xmlURI)); + String nextFile = getNextFile(this.getClass()); + transformer1.transform(xmlSAXSrc, new StreamResult(nextFile)); + assertTrue(compareWithGold(goldFile, nextFile)); + + nextFile = getNextFile(this.getClass()); + transformer2.transform(xmlSAXSrc, new StreamResult(nextFile)); + assertTrue(compareWithGold(goldFile, nextFile)); + + // Validate process of a stylesheet using a simple SAXSource with an + // InputStream. Note setting systemId is not necessary with this + // stylesheet. + Templates templatesStream = saxFactory.newTemplates(xslSAXSrc); + assertNotNull(templatesStream); + Transformer transformerStream = templatesStream.newTransformer(); + assertNotNull(transformerStream); + + SAXSource xmlSAXSrcStream = new SAXSource(new InputSource(xmlFis)); + nextFile = getNextFile(this.getClass()); + transformerStream.transform(xmlSAXSrcStream, new StreamResult(nextFile)); + assertTrue(compareWithGold(goldFile, nextFile)); + setPermissions(); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/sax/SAXTransformerFactoryAPITest.java 2015-01-09 15:42:21.650187118 -0800 @@ -0,0 +1,493 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.sax; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Result; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.SAXSource; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.FILE_SEP; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import org.apache.qetest.trax.CheckingErrorListener; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; + +/** + * API Coverage test for SAXTransformerFactory. + */ +public class SAXTransformerFactoryAPITest extends JAXPFileBaseTest { + /** + * Test XSLT embedded file. + */ + private static final String CITIES_INCLUDE_FILE = XML_DIR + "impincl" + + FILE_SEP + "citiesinclude.xsl"; + + /** + * Test XSLT file. + */ + private static final String XSLT_FILE = XML_DIR + "cities.xsl"; + + /** + * Test XML file. + */ + private static final String XML_FILE = XML_DIR + "cities.xml"; + + /** + * Test golden verification file. + */ + private static final String GOLDEN_FILE = GOLDEN_DIR + "cities.out"; + + @DataProvider + public Object[][] parameters(){ + return new Object[][]{ + {XML_FILE, XSLT_FILE, GOLDEN_FILE} + }; + } + + /** + * This tests newTransformerhandler() method which takes StreamSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest01(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = getJAXPXMLReader(); + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler( + new StreamSource(filenameToURL(xslFile))); + // Send results out to the next output name + handler.setResult(new StreamResult(fos)); + reader.setContentHandler(handler); + // Log what output is about to be created + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + /** + * This tests newTransformerhandler() method which takes SAXSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest02(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile); + FileInputStream fis = new FileInputStream(xslFile);) { + XMLReader reader = getJAXPXMLReader(); + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + SAXSource ss = new SAXSource(); + ss.setInputSource(new InputSource(fis)); + TransformerHandler handler = saxTFactory.newTransformerHandler(ss); + + handler.setResult(new StreamResult(fos)); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * This tests newTransformerhandler() method which takes DOMSource as + * argument. No relative URIs used. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest03(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + CheckingErrorListener loggingErrListener = new CheckingErrorListener(); + tfactory.setErrorListener(loggingErrListener); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); // Ensure we get namespaces! May be required for some Xerces versions + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + DOMSource domSource = new DOMSource((Node)docBuilder.parse(new File(xslFile))); + SAXTransformerFactory saxTFactory = (SAXTransformerFactory)tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler(domSource); + handler.setResult(new StreamResult(fos)); + XMLReader reader = getJAXPXMLReader(); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + /** + * This tests newTransformerhandler() method which takes DOMSource as + * argument. Here a relative URI is used in citiesinclude.xsl file. + * setSystemId is not used for DOMSource. It should throw an exception. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters", expectedExceptions = TransformerConfigurationException.class) + public void SAXTFactoryTest04(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + // Ensure we get namespaces! May be required for some Xerces versions + dbf.setNamespaceAware(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + // note specific file name used + Node node = (Node) docBuilder.parse(new File(CITIES_INCLUDE_FILE)); + DOMSource domSource = new DOMSource(node); + // setSystemId is not used for DOMSource. expecting Exception. + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler(domSource); + handler.setResult(new StreamResult(fos)); + + XMLReader reader = getJAXPXMLReader(); + reader.setContentHandler(handler); + + // Log what output is about to be created + reader.parse(filenameToURL(xmlFile)); + } + } + + /** + * Tests newTransformerhandler() method which takes DOMSource as argument. + * Here a relative URI is used in citiesinclude.xsl file. setSystemId is + * used for DOMSource. It should run well. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest05(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + + Document document = docBuilder.parse(new File(CITIES_INCLUDE_FILE)); + DOMSource domSource = new DOMSource((Node) document); + domSource.setSystemId(filenameToURL(CITIES_INCLUDE_FILE)); + TransformerHandler handler = saxTFactory.newTransformerHandler(domSource); + handler.setResult(new StreamResult(fos)); + XMLReader reader = getJAXPXMLReader(); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + // Validate the output by comparing against gold + assertTrue(compareWithGold(goldFile, outputFile)); + } + /** + * This tests newTransformerhandler() method which takes StreamSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest06(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = getJAXPXMLReader(); + + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler( + new StreamSource(filenameToURL(xslFile))); + // Send results out to the next output name + Result result = new StreamResult(fos); + + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * This tests newTransformerhandler() method which takes StreamSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest07(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = getJAXPXMLReader(); + + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler( + new StreamSource(filenameToURL(xslFile))); + // Send results out to the next output name + Result result = new StreamResult(fos); + + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * This tests newTransformerhandler() method which takes StreamSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest08(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = getJAXPXMLReader(); + + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler( + new StreamSource(filenameToURL(xslFile))); + // Send results out to the next output name + Result result = new StreamResult(fos); + + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * This tests newTransformerhandler() method which takes StreamSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest09(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = getJAXPXMLReader(); + + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler( + new StreamSource(filenameToURL(xslFile))); + // Send results out to the next output name + Result result = new StreamResult(fos); + + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * This tests newTransformerhandler() method which takes StreamSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest10(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = getJAXPXMLReader(); + + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler( + new StreamSource(filenameToURL(xslFile))); + // Send results out to the next output name + Result result = new StreamResult(fos); + + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * This tests newTransformerhandler() method which takes StreamSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest11(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = getJAXPXMLReader(); + + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler( + new StreamSource(filenameToURL(xslFile))); + // Send results out to the next output name + Result result = new StreamResult(fos); + + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * This tests newTransformerhandler() method which takes StreamSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest12(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = getJAXPXMLReader(); + + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler( + new StreamSource(filenameToURL(xslFile))); + // Send results out to the next output name + Result result = new StreamResult(fos); + + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * This tests newTransformerhandler() method which takes StreamSource as + * argument. + * + * @param xmlFile XML test file name. + * @param xslFile XSLT test file name. + * @param goldFile golden file name. + * @throws Exception If any errors occur. + */ + @Test(dataProvider = "parameters") + public void SAXTFactoryTest13(String xmlFile, String xslFile, String goldFile) + throws Exception { + String outputFile = getNextFile(this.getClass()); + TransformerFactory tfactory = TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile)) { + XMLReader reader = getJAXPXMLReader(); + + SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tfactory; + TransformerHandler handler = saxTFactory.newTransformerHandler( + new StreamSource(filenameToURL(xslFile))); + // Send results out to the next output name + Result result = new StreamResult(fos); + + handler.setResult(result); + reader.setContentHandler(handler); + reader.parse(filenameToURL(xmlFile)); + } + assertTrue(compareWithGold(goldFile, outputFile)); + } + + /** + * Worker method to get an XMLReader. + * + * @return a new XMLReader for use, with setNamespaceAware(true) + * @throws Exception If any errors occur. + */ + private XMLReader getJAXPXMLReader() + throws Exception { + // Be sure to use the JAXP methods only! + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + return factory.newSAXParser().getXMLReader(); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/sax/TemplatesHandlerAPITest.java 2015-01-09 15:42:21.920187540 -0800 @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.sax; + +import java.io.FileOutputStream; +import java.io.FilePermission; +import java.util.Properties; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TemplatesHandler; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import org.testng.annotations.Test; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + +/** + * API Coverage test for the TemplatesHandler class of TRAX. + */ +public class TemplatesHandlerAPITest extends JAXPBaseTest { + /** + * Nonsense systemId for various tests. + */ + private static final String NONSENSE_SYSTEMID = "file:///nonsense/system/id/"; + + /** + * Basic API coverage of set/get methods. Note that most of the + * functionality of this class goes far beyond what we test in this + * testCase. + * + * @throws TransformerConfigurationException Thrown in case of + * ServiceConfigurationError service configuration error or if the + * implementation is not available or cannot be instantiated. + */ + @Test + public void testCase1() throws TransformerConfigurationException { + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + // Basic construction + TemplatesHandler tHandler = saxFactory.newTemplatesHandler(); + assertNotNull(tHandler); + + // getTemplates API coverage - simple + Templates templates = tHandler.getTemplates(); + assertNull(templates); + + // set/getSystemId API coverage + tHandler.setSystemId(NONSENSE_SYSTEMID); + assertEquals(tHandler.getSystemId(), NONSENSE_SYSTEMID); + tHandler.setSystemId(null); + assertNull(tHandler.getSystemId()); + + } + + /** + * Template API test on transform process. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase2() throws Exception { + setPermissions(new FilePermission(XML_DIR + "/-", "read"), + new FilePermission(GOLDEN_DIR + "/-", "read"), + new FilePermission(USER_DIR + "-", "read, write")); + String xslURI = filenameToURL(XML_DIR + "SAXTest.xsl"); + String xmlURI = filenameToURL(XML_DIR + "SAXTest.xml"); + String goldFile = GOLDEN_DIR + "SAXTest.out"; + String outputFile1 = USER_DIR + "TemplatesHandlerAPITest1.out"; + + String xslImpInclURI = filenameToURL(XML_DIR + "SAXImpIncl.xsl"); + String xmlImpInclURI = filenameToURL(XML_DIR + "SAXImpIncl.xml"); + String goldImpInclFile = GOLDEN_DIR + "SAXImpIncl.out"; + String outputFile2 = USER_DIR + "TemplatesHandlerAPITest2.out"; + + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + try (FileOutputStream fos = new FileOutputStream(outputFile1)) { + // Validate a templatesHandler can create a valid stylesheet + TemplatesHandler templatesHandler = saxFactory.newTemplatesHandler(); + + XMLReader reader = getJAXPXMLReader(); + reader.setContentHandler(templatesHandler); + // Parse the stylesheet, which means we should be able to getTemplates() + reader.parse(xslURI); + + //Get the Templates object from the ContentHandler + Templates templates = templatesHandler.getTemplates(); + assertNotNull(templates); + Properties xslOutProps = templates.getOutputProperties(); + assertNotNull(xslOutProps); + // validate transformer not null + Transformer transformer = templates.newTransformer(); + assertNotNull(transformer); + + // Validate that this transformer actually works + Result result = new StreamResult(fos); + Source xmlSource = new StreamSource(xmlURI); + transformer.transform(xmlSource, result); + compareWithGold(goldFile, outputFile1); + } + compareWithGold(goldFile, outputFile1); + + try (FileOutputStream fos = new FileOutputStream(outputFile2)) { + // Validate a templatesHandler can create a stylesheet + // with imports/includes, with the default systemId + TemplatesHandler templatesHandler = saxFactory.newTemplatesHandler(); + + XMLReader reader = getJAXPXMLReader(); + reader.setContentHandler(templatesHandler); + + // Parse the stylesheet, which means we should be able to getTemplates() + reader.parse(xmlImpInclURI); + + //Get the Templates object from the ContentHandler + Templates templates = templatesHandler.getTemplates(); + assertNotNull(templates); + Properties xslOutProps = templates.getOutputProperties(); + assertNotNull(xslOutProps); + Transformer transformer = templates.newTransformer(); + assertNotNull(transformer); + + Result result = new StreamResult(fos); + Source xmlSource = new StreamSource(xmlImpInclURI); + transformer.transform(xmlSource, result); + + } + compareWithGold(goldImpInclFile, outputFile2); + setPermissions(); + } + + /** + * Worker method to get an XMLReader. Not the most efficient of methods, but + * makes the code simpler. + * + * @return a new XMLReader for use, with setNamespaceAware(true) + * @throws ParserConfigurationException if a parser cannot be created which + * satisfies the requested configuration. + * @throws SAXException for SAX errors. + */ + private XMLReader getJAXPXMLReader() throws SAXException, + ParserConfigurationException { + // Be sure to use the JAXP methods only! + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + return factory.newSAXParser().getXMLReader(); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/sax/TransformerHandlerAPITest.java 2015-01-09 15:42:22.190187961 -0800 @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.sax; + +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import org.testng.annotations.Test; + +/** + * API Coverage test for the TransformerHandler class of TRAX. + */ +public class TransformerHandlerAPITest extends JAXPFileBaseTest { + /** + * Nonsense systemId for various tests. + */ + private static final String NONSENSE_SYSTEMID = "file:///nonsense/system/id/"; + + /** + * IllegalArgumentException is thrown if result set as null. + * + * @throws TransformerConfigurationException Thrown in case of + * ServiceConfigurationError service configuration error or if the + * implementation is not available or cannot be instantiated. + */ + @Test(expectedExceptions = IllegalArgumentException.class) + public void negativeCase1() throws TransformerConfigurationException { + String outputFile = USER_DIR + "TransformerHandlerAPITest01.out"; + // Validate API's for an identity transformer + // No public constructor available: you must always ask + // a SAXTransformerFactory to give you one + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + + // Basic construction of identity transformer + TransformerHandler tHandler = saxFactory.newTransformerHandler(); + + // set/getSystemId API coverage + tHandler.setSystemId(NONSENSE_SYSTEMID); + tHandler.setSystemId(null); + + // setResult API coverage + Result unusedResult = new StreamResult(outputFile); + tHandler.setResult(unusedResult); + tHandler.setResult(null); + } + + /** + * IllegalArgumentException is thrown if result set as null. + * + * @throws TransformerConfigurationException Thrown in case of + * ServiceConfigurationError service configuration error or if the + * implementation is not available or cannot be instantiated. + */ + @Test(expectedExceptions = IllegalArgumentException.class) + public void negativeCase2() throws TransformerConfigurationException { + String outputFile = getNextFile(this.getClass()); + + // Validate API's for an identity transformer + // No public constructor available: you must always ask + // a SAXTransformerFactory to give you one + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + + // Basic construction of identity transformer + TransformerHandler tHandler = saxFactory.newTransformerHandler(); + + // set/getSystemId API coverage + tHandler.setSystemId(NONSENSE_SYSTEMID); + tHandler.setSystemId(null); + + // setResult API coverage + Result unusedResult = new StreamResult(outputFile); + tHandler.setResult(unusedResult); + tHandler.setResult(null); + } + + /** + * IllegalArgumentExceptionis thrown if result set as null. + * + * @throws TransformerConfigurationException Thrown in case of + * ServiceConfigurationError service configuration error or if the + * implementation is not available or cannot be instantiated. + */ + @Test(expectedExceptions = IllegalArgumentException.class) + public void negativeCase3() throws TransformerConfigurationException { + String xslURI = filenameToURL(XML_DIR + "SAXTest.xsl"); + String outputFile = getNextFile(this.getClass()); + + // Validate API's for a 'real' transformer, which is different code + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + // Basic construction of identity transformer + TransformerHandler tHandler = saxFactory.newTransformerHandler(new StreamSource(xslURI)); + assertNotNull(tHandler); + // getTemplates API coverage - simple + Transformer transformer = tHandler.getTransformer(); + assertNotNull(transformer); + // set/getSystemId API coverage + tHandler.setSystemId(NONSENSE_SYSTEMID); + assertEquals(tHandler.getSystemId(), NONSENSE_SYSTEMID); + tHandler.setSystemId(null); + assertNull(tHandler.getSystemId()); + + // setResult API coverage + Result unusedResult = new StreamResult(outputFile); + tHandler.setResult(unusedResult); + tHandler.setResult(null); + } + + /** + * Basic functionality of TransformerHandler. + * + * @throws Exception If any errors occur. + */ + public void testCase2() throws Exception { + String xslURI = filenameToURL(XML_DIR + "SAXTest.xsl"); + String xmlURI = XML_DIR + "SAXTest.xml"; + String goldFile = GOLDEN_DIR + "SAXTest.out"; + String outputURI = filenameToURL(USER_DIR + "SAXTest.out"); + + SAXTransformerFactory saxFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); + // Validate an identity transformerHandler is valid and performs as an + // identity stylesheet + TransformerHandler transformerHandler = saxFactory.newTransformerHandler(); + Transformer transformer = transformerHandler.getTransformer(); + assertNotNull(transformer); + transformer.transform(new StreamSource(xmlURI), new StreamResult(xslURI)); + compareWithGold(xmlURI, outputURI); + + + // Validate newTransformerHandler(Source) works + transformer = transformerHandler.getTransformer(); + assertNotNull(transformer); + transformer.transform(new StreamSource(xmlURI), new StreamResult(outputURI)); + compareWithGold(goldFile, outputURI); + + // Validate newTransformerHandler(Templates) works + Source xslSource = new StreamSource(xslURI); + Templates otherTemplates = saxFactory.newTemplates(xslSource); + transformerHandler = saxFactory.newTransformerHandler(otherTemplates); + transformer = transformerHandler.getTransformer(); + assertNotNull(transformer); + transformer.transform(new StreamSource(xmlURI), new StreamResult(outputURI)); + compareWithGold(goldFile, outputURI); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/sax/TransformerHandlerTest.java 2015-01-09 15:42:22.469188397 -0800 @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.sax; + +import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.stream.Collectors; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPFileBaseTest; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import org.apache.qetest.xsl.CheckingSAXErrorHandler; +import static org.testng.Assert.assertEquals; +import org.testng.annotations.Test; +import org.xml.sax.SAXParseException; + +/** + * Basic functionality test for the TransformerHandler class of TRAX. + */ +public class TransformerHandlerTest extends JAXPFileBaseTest { + + /** + * Un-formed XML string(note mismatched tags). + */ + private static final String XML_ERROR_STR + = "" + + ""; + + /** + * Well-formed XML string. + */ + private static final String XML_GOOD_STR + = "" + + "Hello world"; + + /** + * XSLT string. + */ + private static final String XSL_STR + = "" + + "" + + "" + + "" + + "" + + ""; + + /** + * Golden validation string. + */ + private static final String GOLDEN_STR + = "Hello world"; + + /** + * Transformer.transform on a not well-formed XML throws TransformerException. + * + * @throws TransformerException If an unrecoverable error occurs during the + * course of the transformation. + */ + @Test(expectedExceptions = TransformerException.class) + public void negativeCase1() throws TransformerException { + // No public constructor available: you must always ask + // a SAXTransformerFactory to give you one + SAXTransformerFactory saxFactory + = (SAXTransformerFactory) TransformerFactory.newInstance(); + try (StringReader sr1 = new StringReader(XSL_STR); + StringReader sr2 = new StringReader(XML_ERROR_STR)) { + Transformer reusedTransformer = saxFactory.newTransformer( + new StreamSource(sr1)); + reusedTransformer.transform(new StreamSource(sr2), + new StreamResult(getNextFile(TransformerHandlerTest.class))); + } + } + + /** + * Reader.read on a not well-formed XML throws TransformerException. + * + * @throws Exception If any errors occur. + */ + @Test(expectedExceptions = SAXParseException.class) + public void testCase2() throws Exception { + SAXTransformerFactory saxFactory + = (SAXTransformerFactory) TransformerFactory.newInstance(); + try(StringReader sr1 = new StringReader(XSL_STR); + StringReader sr2 = new StringReader(XML_ERROR_STR);) { + TransformerHandler thandler = saxFactory.newTransformerHandler( + new StreamSource(sr1)); + SAXParserFactory spf1 = SAXParserFactory.newInstance(); + spf1.setNamespaceAware(true); + SAXParser parser1 = spf1.newSAXParser(); + org.xml.sax.XMLReader reader = parser1.getXMLReader(); + reader.setContentHandler(thandler); + reader.setErrorHandler(new CheckingSAXErrorHandler()); + thandler.setResult(new StreamResult(getNextFile(TransformerHandlerTest.class))); + reader.parse(new org.xml.sax.InputSource(sr2)); + } + } + + /** + * Re-transform several times with XMLReader and Transformer. No exception + * should be thrown. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase3() throws Exception { + SAXTransformerFactory saxFactory + = (SAXTransformerFactory) TransformerFactory.newInstance(); + String outputFile1 = getNextFile(this.getClass()); + String outputFile2 = getNextFile(this.getClass()); + try(StringReader sr1 = new StringReader(XSL_STR); + StringReader sr2 = new StringReader(XML_GOOD_STR); + StringReader sr3 = new StringReader(XSL_STR); + StringReader sr4 = new StringReader(XML_GOOD_STR)) { + TransformerHandler thandler = saxFactory.newTransformerHandler( + new StreamSource(sr1)); + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser parser = spf.newSAXParser(); + org.xml.sax.XMLReader reader = parser.getXMLReader(); + thandler.setResult(new StreamResult(outputFile1)); + reader.setContentHandler(thandler); + reader.setErrorHandler(new CheckingSAXErrorHandler()); + reader.parse(new org.xml.sax.InputSource(sr2)); + + Transformer reusedTransformer = TransformerFactory.newInstance() + .newTransformer(new StreamSource(sr3)); + reusedTransformer.transform(new StreamSource(sr4), + new StreamResult(outputFile2)); + } + String outputStr1 = Files.readAllLines(Paths.get(outputFile1)).stream() + .collect(Collectors.joining(System.getProperty("line.separator"))); + String outputStr2 = Files.readAllLines(Paths.get(outputFile1)).stream() + .collect(Collectors.joining(System.getProperty("line.separator"))); + assertEquals(outputStr1, GOLDEN_STR); + assertEquals(outputStr2, GOLDEN_STR); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/stream/StreamResultAPITest.java 2015-01-09 15:42:22.733188809 -0800 @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.stream; + +import java.io.ByteArrayOutputStream; +import java.io.CharArrayWriter; +import java.io.FileInputStream; +import java.io.FilePermission; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.io.StringWriter; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareStringWithGold; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import org.testng.annotations.Test; + +/** + * API Coverage test for the StreamResult class of TRAX. + */ +public class StreamResultAPITest extends JAXPBaseTest { + /** + * Basic API coverage, constructor and set/get methods. + * @throws IOException if any I/O operation failed. + */ + @Test + public void testCase1() throws IOException { + // Default no-arg ctor sets nothing + StreamResult defaultStream = new StreamResult(); + assertNull(defaultStream.getOutputStream()); + assertNull(defaultStream.getWriter()); + assertNull(defaultStream.getSystemId()); + + try(ByteArrayOutputStream baos = new ByteArrayOutputStream(); + StringWriter strWriter = new StringWriter();) { + StreamResult byteResult1 = new StreamResult(baos); + assertEquals(byteResult1.getOutputStream(), baos); + assertNull(byteResult1.getWriter()); + assertNull(byteResult1.getSystemId()); + + StreamResult readerResult1 = new StreamResult(strWriter); + assertNull(readerResult1.getOutputStream()); + assertEquals(readerResult1.getWriter(), strWriter); + assertNull(readerResult1.getSystemId()); + + StreamResult wackyStream = new StreamResult(); + wackyStream.setOutputStream(baos); + assertEquals(wackyStream.getOutputStream(), baos); + + wackyStream.setWriter(strWriter); + assertEquals(wackyStream.getWriter(), strWriter); + + wackyStream.setSystemId("new-system-id"); + assertEquals(wackyStream.getSystemId(), "new-system-id"); + } + } + + /** + * Basic functionality of StreamResults. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase2() throws Exception { + setPermissions(new FilePermission(XML_DIR + "/-", "read"), + new FilePermission(GOLDEN_DIR + "/-", "read"), + new FilePermission(USER_DIR + "-", "read, write")); + String xsltFile = XML_DIR + "StreamOutputFormat.xsl"; + String xmlFile = XML_DIR + "StreamOutputFormat.xml"; + String goldFile = GOLDEN_DIR + "StreamOutputFormat.out"; + + TransformerFactory factory = TransformerFactory.newInstance(); + try (InputStream xslis = new FileInputStream(xsltFile); + InputStream xmlis1 = new FileInputStream(xmlFile); + InputStream xmlis2 = new FileInputStream(xmlFile); + InputStream xmlis3 = new FileInputStream(xmlFile); + InputStream xmlis4 = new FileInputStream(xmlFile); + InputStream xmlis5 = new FileInputStream(xmlFile); + InputStream xmlis6 = new FileInputStream(xmlFile);) { + // Create re-useable sources + Source xslSource = new StreamSource(xslis); + Templates templates = factory.newTemplates(xslSource); + + // Test some OutputStreams + // Simple FileOutputStream is tested in numerous other tests + Transformer transformer = templates.newTransformer(); + + // Note: must get a new xmlSource for each transform for now. + // FileInputStreams don't just get 'reset' for you, + // But it would be nice to reuse the StreamSources + try(ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ByteArrayOutputStream baos2 = new ByteArrayOutputStream();) { + transformer.transform(new StreamSource(xmlis1), + new StreamResult(baos)); + transformer.transform(new StreamSource(xmlis2), + new StreamResult(new PrintStream(baos2))); + assertEquals(baos.toString(), baos2.toString()); + compareStringWithGold(goldFile, baos.toString("UTF-8")); + } + + // Test wrap on StringWriter and CharArrayWriter + try(StringWriter sw = new StringWriter(); + CharArrayWriter cw = new CharArrayWriter();) { + transformer.transform(new StreamSource(xmlis3), new StreamResult(sw)); + transformer.transform(new StreamSource(xmlis4), new StreamResult(cw)); + assertEquals(sw.toString(), cw.toString()); + compareStringWithGold(goldFile, sw.toString()); + } + + // Test with systemId set + try (StringWriter sw1 = new StringWriter(); + StringWriter sw2 = new StringWriter();) { + transformer.transform(new StreamSource(xmlis5), new StreamResult(sw1)); + Result swResult2 = new StreamResult(sw2); + swResult2.setSystemId("random-system-id"); + transformer.transform(new StreamSource(xmlis6), swResult2); + assertEquals(sw1.toString(), sw2.toString()); + assertEquals(swResult2.getSystemId(), "random-system-id"); + compareStringWithGold(goldFile, sw1.toString()); + } + } + setPermissions(); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/apache/qetest/trax/stream/StreamSourceAPITest.java 2015-01-09 15:42:23.003189231 -0800 @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax.stream; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FilePermission; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.StringReader; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import jaxp.library.JAXPBaseTest; +import static jaxp.library.JAXPTestUtilities.USER_DIR; +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.apache.qetest.trax.TraxConst.GOLDEN_DIR; +import static org.apache.qetest.trax.TraxConst.XML_DIR; +import static jaxp.library.JAXPTestUtilities.getNextFile; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import org.testng.annotations.Test; + +/** + * API Coverage test for the StreamSource class of TRAX. + */ +public class StreamSourceAPITest extends JAXPBaseTest { + /** + * Basic API coverage, constructor and set/get methods. + */ + @Test + public void testCase1() { + // Default StreamSource contains empty source. + StreamSource defaultStream = new StreamSource(); + assertNull(defaultStream.getInputStream()); + assertNull(defaultStream.getReader()); + assertNull(defaultStream.getPublicId()); + assertNull(defaultStream.getSystemId()); + + byte[] bytes = {0, 0, 0, 0}; // just a few zeroes, not really needed + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + StreamSource byteSource1 = new StreamSource(bais); + assertEquals(byteSource1.getInputStream(), bais); + assertNull(byteSource1.getReader()); + assertNull(byteSource1.getPublicId()); + assertNull(byteSource1.getSystemId()); + + StreamSource byteSource2 = new StreamSource(bais, "some-system-id"); + assertEquals(byteSource2.getInputStream(), bais); + assertNull(byteSource2.getReader()); + assertNull(byteSource2.getPublicId()); + assertEquals(byteSource2.getSystemId(), "some-system-id"); + + try(StringReader strReader = + new StringReader("this is not your parent's XML data")) { + StreamSource readerSource1 = new StreamSource(strReader); + assertNull(readerSource1.getInputStream()); + assertEquals(readerSource1.getReader(), strReader); + assertNull(readerSource1.getPublicId()); + assertNull(readerSource1.getSystemId()); + + StreamSource readerSource2 = new StreamSource(strReader, "some-system-id"); + assertNull(readerSource2.getInputStream()); + assertEquals(readerSource2.getReader(), strReader); + assertNull(readerSource2.getPublicId()); + assertEquals(readerSource2.getSystemId(), "some-system-id"); + + StreamSource sysIDStream = new StreamSource("real-system-id"); + assertNull(sysIDStream.getInputStream()); + assertNull(sysIDStream.getReader()); + assertNull(sysIDStream.getPublicId()); + assertEquals(sysIDStream.getSystemId(), "real-system-id"); + + StreamSource wackyStream = new StreamSource(); + wackyStream.setInputStream(bais); + assertEquals(wackyStream.getInputStream(), bais); + + wackyStream.setReader(strReader); + assertEquals(wackyStream.getReader(), strReader); + + wackyStream.setSystemId("new-system-id"); + assertEquals(wackyStream.getSystemId(), "new-system-id"); + + wackyStream.setPublicId("new-public-id"); + assertEquals(wackyStream.getPublicId(), "new-public-id"); + } + } + + /** + * Basic functionality of StreamResource. + * + * @throws Exception If any errors occur. + */ + @Test + public void testCase2() throws Exception { + setPermissions(new FilePermission(XML_DIR + "/-", "read"), + new FilePermission(GOLDEN_DIR + "/-", "read"), + new FilePermission(USER_DIR + "-", "read, write")); + String xsltFile = XML_DIR + "impincl/StreamImpIncl.xsl"; + String xmlFile = XML_DIR + "impincl/StreamImpIncl.xml"; + String goldFile = GOLDEN_DIR + "StreamImpIncl.out"; + String xslID = filenameToURL(xsltFile); + String xmlID = filenameToURL(xmlFile); + + TransformerFactory factory = TransformerFactory.newInstance(); + try (InputStream xslStream1 = new FileInputStream(xsltFile); + InputStream xmlStream1 = new FileInputStream(xmlFile); + InputStream xslStream2 = new FileInputStream(xsltFile); + InputStream xmlStream2 = new FileInputStream(xmlFile); + InputStream xslStream3 = new FileInputStream(xsltFile); + InputStream xmlStream3 = new FileInputStream(xmlFile);) { + String outputFile1 = getNextFile(this.getClass()); + try(OutputStream fos1 = new FileOutputStream(outputFile1)) { + Source xslSource1 = new StreamSource(xslStream1); + xslSource1.setSystemId(xslID); + Source xmlSource1 = new StreamSource(xmlStream1); + xmlSource1.setSystemId(xmlID); + factory.newTemplates(xslSource1).newTransformer() + .transform(xmlSource1, new StreamResult(fos1)); + } + compareWithGold(goldFile, outputFile1); + + String outputFile2 = getNextFile(this.getClass()); + try(OutputStream fos = new FileOutputStream(outputFile2)) { + factory.newTemplates(new StreamSource(xslStream2, xslID)) + .newTransformer().transform( + new StreamSource(xmlStream2, xmlID), new StreamResult(fos)); + } + compareWithGold(goldFile, outputFile2); + + String outputFile3 = getNextFile(this.getClass()); + try(OutputStream fos = new FileOutputStream(outputFile3)) { + StreamSource source = new StreamSource(xslStream3); + source.setSystemId(xslID); + factory.newTemplates(source).newTransformer() + .transform(new StreamSource(xmlStream3), new StreamResult(fos)); + } + compareWithGold(goldFile, outputFile3); + } + setPermissions(); + } +} --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest01.java 2015-01-09 15:42:23.381189821 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,193 +0,0 @@ -/* - * Copyright (c) 2014, 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 org.xml.sax.ptests; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import org.xml.sax.SAXNotRecognizedException; -import org.xml.sax.SAXNotSupportedException; -import org.xml.sax.XMLReader; - -/** - * Class containing the test cases for Namespace Table defined at - * http://www.megginson.com/SAX/Java/namespaces.html - */ -public class NSTableTest01 { - private static final String NAMESPACES = - "http://xml.org/sax/features/namespaces"; - private static final String NAMESPACE_PREFIXES = - "http://xml.org/sax/features/namespace-prefixes"; - - /** - * Here namespace processing and namespace-prefixes are enabled. - * The testcase tests XMLReader for this. - */ - @Test - public void xrNSTable01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - - XMLReader xmlReader = saxParser.getXMLReader(); - xmlReader.setFeature(NAMESPACE_PREFIXES, true); - - assertTrue(xmlReader.getFeature(NAMESPACES)); - assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing is enabled. This will make namespace-prefixes - * disabled. The testcase tests XMLReader for this. - */ - @Test - public void xrNSTable02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - SAXParser saxParser = spf.newSAXParser(); - - XMLReader xmlReader = saxParser.getXMLReader(); - assertTrue(xmlReader.getFeature(NAMESPACES)); - assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - - } - - /** - * Here namespace processing is disabled. This will make namespace-prefixes - * enabled. The testcase tests XMLReader for this. - */ - @Test - public void xrNSTable03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxParser = spf.newSAXParser(); - XMLReader xmlReader = saxParser.getXMLReader(); - assertFalse(xmlReader.getFeature(NAMESPACES)); - assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing is disabled, and namespace-prefixes is - * disabled. This will make namespace processing on.The testcase tests - * XMLReader for this. This behavior only apply to crimson, not - * xerces - */ - @Test - public void xrNSTable04() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxParser = spf.newSAXParser(); - XMLReader xmlReader = saxParser.getXMLReader(); - xmlReader.setFeature(NAMESPACE_PREFIXES, false); - - assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing and namespace-prefixes are enabled. - * The testcase tests SAXParserFactory for this. - */ - @Test - public void spNSTable01() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - spf.setFeature(NAMESPACE_PREFIXES,true); - assertTrue(spf.getFeature(NAMESPACES)); - assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException - | SAXNotSupportedException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing is enabled. This will make namespace-prefixes - * disabled. The testcase tests SAXParserFactory for this. - */ - @Test - public void spNSTable02() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setNamespaceAware(true); - assertTrue(spf.getFeature(NAMESPACES)); - assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException - | SAXNotSupportedException ex) { - failUnexpected(ex); - } - } - - /** - * Here namespace processing is disabled. This will make namespace-prefixes - * enabled. The testcase tests SAXParserFactory for this. - */ - @Test - public void spNSTable03() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - assertFalse(spf.getFeature(NAMESPACES)); - assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException - | SAXNotSupportedException ex) { - failUnexpected(ex); - } - } - /** - * Here namespace processing is disabled, and namespace-prefixes is - * disabled. This will make namespace processing on.The testcase tests - * SAXParserFactory for this. This behavior only apply to crimson, - * not xerces. - */ - @Test - public void spNSTable04() { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setFeature(NAMESPACE_PREFIXES, false); - - assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); - } catch (ParserConfigurationException | SAXNotRecognizedException - | SAXNotSupportedException ex) { - failUnexpected(ex); - } - } -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/functional/org/xml/sax/ptests/NSTableTest.java 2015-01-09 15:42:23.265189640 -0800 @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2003, 2015, 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 org.xml.sax.ptests; + +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import jaxp.library.JAXPBaseTest; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; +import org.testng.annotations.Test; +import org.xml.sax.XMLReader; + +/** + * Class containing the test cases for Namespace Table defined at + * http://www.megginson.com/SAX/Java/namespaces.html + */ +public class NSTableTest extends JAXPBaseTest { + private static final String NAMESPACES = + "http://xml.org/sax/features/namespaces"; + private static final String NAMESPACE_PREFIXES = + "http://xml.org/sax/features/namespace-prefixes"; + + /** + * Here namespace processing and namespace-prefixes are enabled. + * The testcase tests XMLReader for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void xrNSTable01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + SAXParser saxParser = spf.newSAXParser(); + + XMLReader xmlReader = saxParser.getXMLReader(); + xmlReader.setFeature(NAMESPACE_PREFIXES, true); + + assertTrue(xmlReader.getFeature(NAMESPACES)); + assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is enabled. This will make namespace-prefixes + * disabled. The testcase tests XMLReader for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void xrNSTable02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + + XMLReader xmlReader = spf.newSAXParser().getXMLReader(); + assertTrue(xmlReader.getFeature(NAMESPACES)); + assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is disabled. This will make namespace-prefixes + * enabled. The testcase tests XMLReader for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void xrNSTable03() throws Exception { + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + assertFalse(xmlReader.getFeature(NAMESPACES)); + assertTrue(xmlReader.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is disabled, and namespace-prefixes is + * disabled. This will make namespace processing on.The testcase tests + * XMLReader for this. This behavior only apply to crimson, not + * XERCES. + * + * @throws Exception If any errors occur. + */ + @Test + public void xrNSTable04() throws Exception { + XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); + xmlReader.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(xmlReader.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing and namespace-prefixes are enabled. + * The testcase tests SAXParserFactory for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void spNSTable01() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setFeature(NAMESPACE_PREFIXES,true); + assertTrue(spf.getFeature(NAMESPACES)); + assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is enabled. This will make namespace-prefixes + * disabled. The testcase tests SAXParserFactory for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void spNSTable02() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + assertTrue(spf.getFeature(NAMESPACES)); + assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); + } + + /** + * Here namespace processing is disabled. This will make namespace-prefixes + * enabled. The testcase tests SAXParserFactory for this. + * + * @throws Exception If any errors occur. + */ + @Test + public void spNSTable03() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + assertFalse(spf.getFeature(NAMESPACES)); + assertTrue(spf.getFeature(NAMESPACE_PREFIXES)); + } + /** + * Here namespace processing is disabled, and namespace-prefixes is + * disabled. This will make namespace processing on.The testcase tests + * SAXParserFactory for this. This behavior only apply to crimson, + * not xerces. + * + * @throws Exception If any errors occur. + */ + @Test + public void spNSTable04() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setFeature(NAMESPACE_PREFIXES, false); + assertFalse(spf.getFeature(NAMESPACE_PREFIXES)); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/MyCHandler.java 2015-01-09 15:42:23.648190238 -0800 @@ -0,0 +1,173 @@ +/* + * Copyright (c) 1999, 2015, 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 javax.xml.parsers.ptests; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import static jaxp.library.JAXPTestUtilities.ERROR_MSG_HEADER; +import org.xml.sax.Attributes; +import org.xml.sax.Locator; +import org.xml.sax.helpers.DefaultHandler; +import org.xml.sax.helpers.LocatorImpl; + +/** + * Customized DefaultHandler which writes output document when methods are + * called by Transformer. Test may use output document to compare with golden + * file for verification. + */ +class MyCHandler extends DefaultHandler implements AutoCloseable { + + private final BufferedWriter bWriter; + private final Locator locator = new LocatorImpl(); + + private MyCHandler(File file) throws IOException { + bWriter = new BufferedWriter(new FileWriter(file)); + } + + public static MyCHandler newInstance(File file) throws IOException { + MyCHandler handler = new MyCHandler(file); + return handler; + } + + @Override + public void characters(char[] ch, int start, int length) { + String s = new String(ch, start, length); + String str = String.format("characters...length is:%d\n<%s>", s.length(), s); + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void endDocument() { + String str = "endDocument..."; + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + bWriter.flush(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void endElement(String namespaceURI, String localName, String qName) { + String str = String.format("endElement...\nnamespaceURI: <%s> localName: <%s> qName: <%s>", namespaceURI, localName, qName); + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void endPrefixMapping(String prefix) { + String str = String.format("endPrefixMapping...\nprefix: <%s>", prefix); + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void ignorableWhitespace(char[] ch, int start, int length) { + String s = new String(ch, start, length); + String str = String.format("ignorableWhitespace...\n%s ignorable white space string length: %d", s, s.length()); + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void processingInstruction(String target, String data) { + String str = String.format("processingInstruction...target:<%s> data: <%s>", target, data); + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void skippedEntity(String name) { + String str = String.format("skippedEntity...\nname: <%s>", name); + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void startDocument() { + String str = "startDocument..."; + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { + String str = String.format("startElement...\nnamespaceURI: <%s> localName: <%s> qName: <%s> Number of Attributes: <%d> Line# <%d>", namespaceURI, + localName, qName, atts.getLength(), locator.getLineNumber()); + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void startPrefixMapping(String prefix, String uri) { + String str = String.format("startPrefixMapping...\nprefix: <%s> uri: <%s>", prefix, uri); + try { + bWriter.write(str, 0, str.length()); + bWriter.newLine(); + } catch (IOException e) { + throw new RuntimeException(ERROR_MSG_HEADER, e); + } + } + + @Override + public void close() throws IOException { + if (bWriter != null) + bWriter.close(); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/MyErrorHandler.java 2015-01-09 15:42:23.945190702 -0800 @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1999, 2015, 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 javax.xml.parsers.ptests; + +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * Customized DefaultHandler used for SAXParseException testing. + */ +class MyErrorHandler extends DefaultHandler { + /** + * Flag whether any event was received. + */ + private volatile boolean errorOccured; + + /** + * Set no event received on constructor. + */ + private MyErrorHandler() { + errorOccured = false; + } + + /** + * Factory method to create a MyErrorHandler instance. + * @return a MyErrorHandler instance. + */ + public static MyErrorHandler newInstance() { + return new MyErrorHandler(); + } + + /** + * Receive notification of a recoverable error. + * @param e a recoverable parser exception error. + */ + @Override + public void error(SAXParseException e) { + errorOccured = true; + } + + /** + * Receive notification of a parser warning. + * @param e a parser warning event. + */ + @Override + public void warning(SAXParseException e) { + errorOccured = true; + } + + /** + * Report a fatal XML parsing error. + * @param e The error information encoded as an exception. + */ + @Override + public void fatalError(SAXParseException e) { + errorOccured = true; + } + + /** + * Has any event been received. + * + * @return true if any event has been received. + * false if no event has been received. + */ + public boolean isErrorOccured() { + return errorOccured; + } +} --- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/TestUtils.java 2015-01-09 15:42:24.348191331 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.parsers.ptests; - -import static jaxp.library.JAXPTestUtilities.ERROR_MSG_HEADER; -import static jaxp.library.JAXPTestUtilities.FILE_SEP; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; - -import org.xml.sax.Attributes; -import org.xml.sax.Locator; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.DefaultHandler; -import org.xml.sax.helpers.LocatorImpl; - -/** - * Utility interface which includes final variables of xml, golden file - * directories. - */ -interface TestUtils { - final String XML_DIR = System.getProperty("test.src", ".") + FILE_SEP + "javax/xml/parsers/xmlfiles"; - final String GOLDEN_DIR = XML_DIR + FILE_SEP + "out"; -} - -/** - * Customized DefaultHandler which writes output document when methods are - * called by Transformer. Test may use output document to compare with golden - * file for verification. - */ -class MyCHandler extends DefaultHandler { - - private final BufferedWriter bWriter; - private final Locator locator = new LocatorImpl(); - - private MyCHandler(File file) throws IOException { - bWriter = new BufferedWriter(new FileWriter(file)); - } - - public static MyCHandler newInstance(File file) throws IOException { - MyCHandler handler = new MyCHandler(file); - return handler; - } - - public void characters(char[] ch, int start, int length) { - String s = new String(ch, start, length); - String str = String.format("characters...length is:%d\n<%s>", s.length(), s); - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } - - public void endDocument() { - String str = "endDocument..."; - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - bWriter.flush(); - bWriter.close(); - - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } - - public void endElement(String namespaceURI, String localName, String qName) { - String str = String.format("endElement...\nnamespaceURI: <%s> localName: <%s> qName: <%s>", namespaceURI, localName, qName); - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } - - public void endPrefixMapping(String prefix) { - String str = String.format("endPrefixMapping...\nprefix: <%s>", prefix); - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } - - public void ignorableWhitespace(char[] ch, int start, int length) { - String s = new String(ch, start, length); - String str = String.format("ignorableWhitespace...\n%s ignorable white space string length: %d", s, s.length()); - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } - - public void processingInstruction(String target, String data) { - String str = String.format("processingInstruction...target:<%s> data: <%s>", target, data); - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } - - public void skippedEntity(String name) { - String str = String.format("skippedEntity...\nname: <%s>", name); - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } - - public void startDocument() { - String str = "startDocument..."; - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } - - public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { - String str = String.format("startElement...\nnamespaceURI: <%s> localName: <%s> qName: <%s> Number of Attributes: <%d> Line# <%d>", namespaceURI, - localName, qName, atts.getLength(), locator.getLineNumber()); - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } - - public void startPrefixMapping(String prefix, String uri) { - String str = String.format("startPrefixMapping...\nprefix: <%s> uri: <%s>", prefix, uri); - try { - bWriter.write(str, 0, str.length()); - bWriter.newLine(); - } catch (IOException e) { - throw new RuntimeException(ERROR_MSG_HEADER, e); - } - } -} - -/** - * Customized DefaultHandler used for SAXParseException testing. - */ -class MyErrorHandler extends DefaultHandler { - boolean errorOccured = false; - - private MyErrorHandler() { - } - - public static MyErrorHandler newInstance() { - return new MyErrorHandler(); - } - - public void error(SAXParseException e) { - errorOccured = true; - } - - public void warning(SAXParseException e) { - errorOccured = true; - } - - public void fatalError(SAXParseException e) { - errorOccured = true; - } -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/javax/xml/parsers/ptests/ParserTestConst.java 2015-01-09 15:42:24.225191139 -0800 @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2014, 2015, 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 javax.xml.parsers.ptests; + +import static jaxp.library.JAXPTestUtilities.FILE_SEP; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; + + +/** + * Utility interface which includes final variables of XML, golden file + * directories. + */ +public class ParserTestConst { + /** + * XML source file directory. + */ + public static final String XML_DIR = getPathByClassName(ParserTestConst.class, + ".." + FILE_SEP + "xmlfiles"); + + + /** + * Golden validation files directory. + */ + public static final String GOLDEN_DIR = getPathByClassName(ParserTestConst.class, + ".." + FILE_SEP + "xmlfiles" + FILE_SEP + "out"); +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/jaxp/library/JAXPBaseTest.java 2015-01-09 15:42:24.619191755 -0800 @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2015, 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 jaxp.library; + +import java.security.Permission; +import java.security.Permissions; +import java.security.Policy; +import java.util.PropertyPermission; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; + +/** + * This is a base class that every test class must extend if it needs to be run + * with security mode. + */ +public class JAXPBaseTest { + /** + * Backing up policy. + */ + protected static Policy policy; + + /** + * Backing up security manager. + */ + private static SecurityManager sm; + + /* + * Install a SecurityManager along with a base Policy to allow testNG to + * run when there is a security manager. + */ + @BeforeClass + public void setUpClass() throws Exception { + setPolicy(new TestPolicy()); + System.setSecurityManager(new SecurityManager()); + } + + /* + * Install the original Policy and SecurityManager when there is a security + * manager. + */ + @AfterClass + public void tearDownClass() throws Exception { + System.setSecurityManager(sm); + setPolicy(policy); + } + + /* + * Utility Method used to set the current Policy. + */ + protected static void setPolicy(Policy p) { + Policy.setPolicy(p); + } + + /* + * Add the specified permission(s) to the test policy. + * Note there is no way to add permissions to current permissions. Reset + * test policy by setting minimal permmisons in addition to specified + * permissions when calling this method. + */ + protected static void setPermissions(Permission... ps) { + Policy.setPolicy(new TestPolicy(ps)); + } + + /* + * Add the specified permission(s) to the test policy. + * Note there is no way to add permissions to current permissions. Reset + * test policy by setting minimal permmisons in addition to specified + * permissions when calling this method. + */ + protected static void setPermissions(Permissions ps) { + Policy.setPolicy(new TestPolicy(ps)); + } + + /** + * Backing up policy and security manager for restore when there is a + * security manager. + */ + public JAXPBaseTest() { + policy = Policy.getPolicy(); + sm = System.getSecurityManager(); + } + + /** + * Safety acquire a system property. + * Note invocation of this method will restore permission to limited + * minimal permission of tests. If there is additional permission set + * already, you need restore permission by yourself. + * @param propName System property name to be acquired. + * @return property value + */ + protected String getSystemProperty(final String propName) { + setPermissions(new PropertyPermission(propName, "read")); + try { + return System.getProperty(propName); + } finally { + setPermissions(); + } + } + + /** + * Safety set a system property by given system value. + * + * @param propName System property name to be set. + * @param propValue System property value to be set. + */ + protected void setSystemProperty(final String propName, final String propValue) { + setPermissions(new PropertyPermission(propName, "write")); + try { + if (propValue == null) { + System.clearProperty(propName); + } else { + System.setProperty(propName, propValue); + } + } finally { + setPermissions(); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileBaseTest.java 2015-01-09 15:42:24.892192181 -0800 @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2015, 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 jaxp.library; + +import java.io.FilePermission; +import java.security.Permission; +import java.security.Permissions; +import java.security.Policy; +import static jaxp.library.JAXPBaseTest.setPolicy; +import org.testng.annotations.BeforeClass; + +/** + * This is a base class that every test class that need to access local XML + * files must extend if it needs to be run with security mode. + */ +public class JAXPFileBaseTest extends JAXPBaseTest { + /* + * Install a SecurityManager along with a base Policy to allow testNG to + * run when there is a security manager. + */ + @BeforeClass + @Override + public void setUpClass() throws Exception { + setPolicy(new FileTestPolicy()); + System.setSecurityManager(new SecurityManager()); + } + + /* + * Add the specified permission(s) to the test policy. + * Note there is no way to add permissions to current permissions. Reset + * test policy by setting minimal permmisons in addition to specified + * permissions when calling this method. + */ + protected static void setPermissions(Permission... ps) { + Policy.setPolicy(new FileTestPolicy(ps)); + } + + /* + * Add the specified permission(s) to the test policy. + * Note there is no way to add permissions to current permissions. Reset + * test policy by setting minimal permmisons in addition to specified + * permissions when calling this method. + */ + protected static void setPermissions(Permissions ps) { + Policy.setPolicy(new FileTestPolicy(ps)); + } +} + +/** + * This policy is only given to tests that need access local files. Additional + * permissions for accessing local files have been granted by default. + * @author HaiboYan + */ +class FileTestPolicy extends TestPolicy { + /** + * Constructor which sets the minimum permissions by default allowing testNG + * to work with a SecurityManager. + * @param ps permissions to be added. + */ + public FileTestPolicy(Permissions ps) { + super(ps); + } + + /** + * Constructor which sets the minimum permissions by default allowing testNG + * to work with a SecurityManager. + * @param ps permission array to be added. + */ + public FileTestPolicy(Permission... ps) { + super(ps); + } + + /** + * Defines the minimal permissions required by testNG when running these + * tests + */ + @Override + protected void setMinimalPermissions() { + super.setMinimalPermissions(); + permissions.add(new FilePermission(System.getProperty("user.dir") + "/-", + "read, write")); + permissions.add(new FilePermission(System.getProperty("test.src") + "/-", + "read")); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/jaxp/library/JAXPFileReadOnlyBaseTest.java 2015-01-09 15:42:25.172192618 -0800 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2015, 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 jaxp.library; + +import java.io.FilePermission; +import static jaxp.library.JAXPBaseTest.setPermissions; +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; + +/** + * This is a base class that every test class that need to reading local XML + * files must extend if it needs to be run with security mode. + */ +public class JAXPFileReadOnlyBaseTest extends JAXPBaseTest { + /** + * Source files/XML files directory. + */ + private final String SRC_DIR = getSystemProperty("test.src"); + + /** + * Allowing access local file system for this group. + */ + @BeforeGroups (groups = {"readLocalFiles"}) + public void setFilePermissions() { + setPermissions(new FilePermission(SRC_DIR + "/-", "read")); + } + + /** + * Restore the system property. + */ + @AfterGroups (groups = {"readLocalFiles"}) + public void restoreFilePermissions() { + setPermissions(); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/jaxp/library/TestPolicy.java 2015-01-09 15:42:25.448193049 -0800 @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2015, 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 jaxp.library; + +import java.security.AllPermission; +import java.security.CodeSource; +import java.security.Permission; +import java.security.PermissionCollection; +import java.security.Permissions; +import java.security.Policy; +import java.security.ProtectionDomain; +import java.security.SecurityPermission; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.PropertyPermission; +import java.util.StringJoiner; + +/* + * Simple Policy class that supports the required Permissions to validate the + * JAXP concrete classes. + * Note: permission can only be added. You may want to create a new TestPolicy + * instance if you need remove permissions. + */ +public class TestPolicy extends Policy { + protected final PermissionCollection permissions = new Permissions(); + + /** + * Constructor which sets the minimum permissions by default allowing testNG + * to work with a SecurityManager. + */ + public TestPolicy() { + setMinimalPermissions(); + } + + /** + * Construct an instance with the minimal permissions required by the test + * environment and additional permission(s) as specified. + * @param ps permissions to be added. + */ + public TestPolicy(Permissions ps) { + setMinimalPermissions(); + TestPolicy.this.addPermissions(ps); + } + + /** + * Construct an instance with the minimal permissions required by the test + * environment and additional permission(s) as specified. + * @param ps permission array to be added. + */ + public TestPolicy(Permission... ps) { + setMinimalPermissions(); + addPermissions(ps); + } + + /** + * Defines the minimal permissions required by testNG when running these + * tests + */ + protected void setMinimalPermissions() { + permissions.add(new SecurityPermission("getPolicy")); + permissions.add(new SecurityPermission("setPolicy")); + permissions.add(new RuntimePermission("getClassLoader")); + permissions.add(new RuntimePermission("setSecurityManager")); + permissions.add(new RuntimePermission("createSecurityManager")); + permissions.add(new PropertyPermission("testng.show.stack.frames", + "read")); + permissions.add(new PropertyPermission("user.dir", "read")); + permissions.add(new PropertyPermission("test.src", "read")); + permissions.add(new PropertyPermission("file.separator", "read")); + permissions.add(new PropertyPermission("line.separator", "read")); + permissions.add(new PropertyPermission("fileStringBuffer", "read")); + permissions.add(new PropertyPermission("dataproviderthreadcount", "read")); + } + + /* + * Add permissions for your tests. + * @param permissions to be added. + */ + private void addPermissions(Permissions ps) { + Collections.list(ps.elements()).forEach(p -> permissions.add(p)); + } + + + /* + * Add permissions for your tests. + * @param permissions to be added. + */ + private void addPermissions(Permission[] ps) { + Arrays.stream(ps).forEach(p -> permissions.add(p)); + } + + /** + * Set all permissions. Caution: this should not called carefully unless + * it's really needed. + */ + private void setAllPermissions() { + permissions.add(new AllPermission()); + } + + /* + * Overloaded methods from the Policy class. + */ + @Override + public String toString() { + StringJoiner sj = new StringJoiner("\n", "policy: ", ""); + Enumeration perms = permissions.elements(); + while (perms.hasMoreElements()) { + sj.add(perms.nextElement().toString()); + } + return sj.toString(); + + } + + @Override + public PermissionCollection getPermissions(ProtectionDomain domain) { + return permissions; + } + + @Override + public PermissionCollection getPermissions(CodeSource codesource) { + return permissions; + } + + @Override + public boolean implies(ProtectionDomain domain, Permission perm) { + return permissions.implies(perm); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/CheckingHandler.java 2015-01-09 15:42:25.731193491 -0800 @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest; + +/** + * Base class defining common functionality of logging handlers. + *

+ * Common functionality used for testing when implementing various Handlers and + * Listeners. Provides common ways to set Loggers and levels, reset, and set + * expected errors or the like. Likely used to implement testing wrapper classes + * for things like javax.xml.transform.ErrorListener and + * org.xml.sax.ErrorHandler

+ *

+ * The best description for this class can be seen in an example; see + * trax.LoggingErrorHandler.java for one.

+ */ +public interface CheckingHandler { + /** + * Reset any items or counters we've handled. Resets any data about what + * we've handled or logged so far, like getLast() and getCounters() data, as + * well as any expected items from setExpected(). Does not change our Logger + * or loggingLevel. + */ + public void reset(); + + /** + * Ask us to report checkPass/Fail for certain events we handle. Since we + * may have to handle many events between when a test will be able to call + * us, testers can set this to have us automatically call checkPass when we + * see an item that matches, or to call checkFail when we get an unexpected + * item. Generally, we only call check* methods when: + *
    + *
  • containsString is not set, reset, or is ITEM_DONT_CARE, we do nothing + * (i.e. never call check* for this item)
  • + *
  • containsString is ITEM_CHECKFAIL, we will always call checkFail with + * the contents of any item if it occurs
  • + *
  • containsString is anything else, we will grab a String representation + * of every item of that type that comes along, and if the containsString is + * found, case-sensitive, within the handled item's string, call checkPass, + * otherwise call checkFail
  • + *
+ * Note that most implementations will only validate the first event of a + * specific type, and then will reset validation for that event type. This + * is because many events may be raised in between the time that a calling + * Test class could tell us of the 'next' expected event. + * + * @param itemType which of the various types of items we might handle; + * should be defined as a constant by subclasses + * @param expectation a set expectation if we care this event or not. + */ + public void setExpected(int itemType, Expectation expectation); + + enum Expectation { + ITEM_DONT_CARE, + ITEM_CHECKFAIL, + ITEM_CHECKPASS, + ITEM_RESOLVE + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/dtm/QeDtmConst.java 2015-01-09 15:42:25.999193910 -0800 @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.dtm; + +import com.sun.org.apache.xml.internal.dtm.DTM; +import com.sun.org.apache.xml.internal.dtm.DTMManager; +import com.sun.org.apache.xml.internal.dtm.DTMWSFilter; +import com.sun.org.apache.xml.internal.dtm.ref.DTMManagerDefault; +import com.sun.org.apache.xpath.internal.objects.XMLStringFactoryImpl; +import java.io.StringReader; +import java.util.List; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; + +/** + * This is the utilities test class provide basic support for DTM test. + */ +public class QeDtmConst { + /** + * XML source file directory. + */ + public static final String XML_DIR = getPathByClassName(QeDtmConst.class, "content"); + + /** + * Golden validation files directory. + */ + public static final String GOLDEN_DIR = getPathByClassName(QeDtmConst.class, "golden"); + + /** + * A XML source string for building DTM. + */ + public static final String DEFAULT_SOURCE = "\n" + + "" + + "" + + "" + + "
" + + "" + + "" + + "" + + "
"; + + /** + * String represent for DOM node type. The sequence of this array following + * same sequence in. + */ + public static final String[] TYPENAME = {"NULL", + "ELEMENT", + "ATTRIBUTE", + "TEXT", + "CDATA_SECTION", + "ENTITY_REFERENCE", + "ENTITY", + "PROCESSING_INSTRUCTION", + "COMMENT", + "DOCUMENT", + "DOCUMENT_TYPE", + "DOCUMENT_FRAGMENT", + "NOTATION", + "NAMESPACE" + }; + + /** + * This routine generates a new DTM with stripping whitespace filter. + * non-incremental, but with indexing (a fairly common case, and + * avoids the special mode used for RTF DTMs). + * @param theSource URL for StreamSource + * @return a non-null DTM reference. + */ + public static DTM createDTM(String theSource) { + return DTMManagerDefault.newInstance(new XMLStringFactoryImpl()) + .getDTM(new StreamSource(new StringReader(theSource)), true, + (eh, dtm) -> DTMWSFilter.STRIP, false, true); + } + + /** + * This routine generates a new DTM for each test case with no whitespace + * filtering, non-incremental, but with indexing (a fairly common case, + * and avoids the special mode used for RTF DTMs). + * @param method 0 create StreamSource directly. + * 1 create StreamSource by StringReader. + * @param theSource the specification of the source object. + * @param lines output string list that will be appended by memory usage. + * @return + */ + public static DTM createDTM(int method, String theSource, List lines) { + // Create DTM and generate initial context + Source source = (method == 1) ? + new StreamSource(new StringReader(theSource)) : + new StreamSource(theSource); + + DTMManager manager = DTMManagerDefault.newInstance(new XMLStringFactoryImpl()); + return manager.getDTM(source, true, (eh, dtm) -> DTMWSFilter.STRIP, false, true); + } + + /** + * Create DTM and generate initial context. + * @return a non-null DTM reference with initial context. + */ + public static DTM generateDTM() { + return createDTM(DEFAULT_SOURCE); + } + + /** + * Retrieve string represent for a XML node. + * @param dtm A XML document model table represent. + * @param nodeHandle Node id. + * @return A string represent by given node id. + */ + public static String getNodeName(DTM dtm, int nodeHandle) { + return TYPENAME[dtm.getNodeType(nodeHandle)]; + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/trax/CheckingErrorListener.java 2015-01-09 15:42:26.269194332 -0800 @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import javax.xml.transform.ErrorListener; +import javax.xml.transform.TransformerException; +import org.apache.qetest.CheckingHandler; +import static org.apache.qetest.CheckingHandler.Expectation.ITEM_CHECKPASS; +import static org.apache.qetest.CheckingHandler.Expectation.ITEM_DONT_CARE; +import static org.testng.Assert.fail; + +/** + * Cheap-o ErrorListener for use by API tests. + *

+ * Implements javax.xml.transform.ErrorListener and dumps everything to a + * Logger; is separately settable as to when it will throw an exception; also + * separately settable as to when we should validate specific events that we + * handle.

+ */ +public class CheckingErrorListener implements CheckingHandler, ErrorListener { + + /** + * Constants determining when we should throw exceptions. + *
    Flags are combineable like a bitfield. + *
  • THROW_NEVER - never ever (always continue - note this may have + * unexpected effects when fatalErrors happen, see + * {@link javax.xml.transform.ErrorListener#fatalError(javax.xml.transform.TransformerException)}
  • + *
  • THROW_ON_WARNING - throw only on warnings
  • + *
  • THROW_ON_ERROR - throw only on errors
  • + *
  • THROW_ON_FATAL - throw only on fatalErrors - default
  • + *
  • THROW_ALWAYS - always throw exceptions
  • + *
+ */ + public static final int THROW_NEVER = 0; + + /** + * THROW_ON_WARNING - throw only on warnings. + */ + public static final int THROW_ON_WARNING = 1; + + /** + * THROW_ON_ERROR - throw only on errors. + */ + public static final int THROW_ON_ERROR = 2; + + /** + * THROW_ON_FATAL - throw only on fatalErrors - default. + */ + public static final int THROW_ON_FATAL = 4; + + /** + * THROW_ALWAYS - always throw exceptions. + */ + public static final int THROW_ALWAYS = THROW_ON_WARNING | THROW_ON_ERROR + | THROW_ON_FATAL; + + /** + * If we should throw an exception for each message type. + */ + protected final int throwWhen; + + /** + * Constructor set when we should re-throw exceptions. + * + * @param t THROW_WHEN_* constant as to when we should re-throw an exception + * when we are called. + */ + public CheckingErrorListener(int t) { + throwWhen = t; + } + + /** + * Default constructor will behave as default. Throw only when there is + * non-recoverable error. + */ + public CheckingErrorListener() { + this(THROW_ON_FATAL); + } + + /** + * Tells us when we should re-throw exceptions. + * + * @return THROW_WHEN_* constant as to when we should re-throw an exception + * when we are called + */ + public int getThrowWhen() { + return throwWhen; + } + + /** + * Constant for items returned in getCounters: messages. + */ + public static final int TYPE_WARNING = 0; + + /** + * Constant for items returned in getCounters: errors. + */ + public static final int TYPE_ERROR = 1; + + /** + * Constant for items returned in getCounters: fatalErrors. + */ + public static final int TYPE_FATALERROR = 2; + + /** + * Expected values for events we may handle, default=ITEM_DONT_CARE. + */ + private final Expectation[] expected = { + ITEM_DONT_CARE, /* warning */ + ITEM_DONT_CARE, /* error */ + ITEM_DONT_CARE /* fatalError */}; + + /** + * Ask us to report checkPass/Fail for certain events we handle. Since we + * may have to handle many events between when a test will be able to call + * us, testers can set this to have us automatically call checkPass when we + * see an item that matches, or to call checkFail when we get an unexpected + * item. Generally, we only call check* methods when: + *
    + *
  • containsString is not set, reset, or is ITEM_DONT_CARE, we do nothing + * (i.e. never call check* for this item)
  • + *
  • containsString is ITEM_CHECKFAIL, we will always call checkFail with + * the contents of any item if it occurs
  • + *
  • containsString is anything else, we will grab a String representation + * of every item of that type that comes along, and if the containsString is + * found, case-sensitive, within the handled item's string, call checkPass, + * otherwise call checkFail
  • + *
+ * Note that any time we handle a particular event that was expected, we + * un-set the expected value for that item. This means that you can only ask + * us to validate one occurrence of any particular event; all events after + * that one will be treated as ITEM_DONT_CARE. Callers can of course call + * setExpected again, of course, but this covers the case where we handle + * multiple events in a single block, perhaps out of the caller's direct + * control. Note that we first store the event via setLast(), then we + * validate the event as above, and then we potentially re-throw the + * exception as by setThrowWhen(). + * + * @param itemType which of the various types of items we might handle; + * should be defined as a constant by subclasses + * @param expectation expectation if we need check or not. + */ + @Override + public void setExpected(int itemType, Expectation expectation) { + expected[itemType] = expectation; + } + + /** + * Reset all items or counters we've handled. + */ + @Override + public void reset() { + for (int j = 0; j < expected.length; j++) { + expected[j] = ITEM_DONT_CARE; + } + } + + /** + * Grab basic info out of a TransformerException. Worker method to hide + * implementation; currently just calls exception.getMessageAndLocation(). + * + * @param exception to get information from + * @return simple string describing the exception (getMessageAndLocation()) + */ + public String getTransformerExceptionInfo(TransformerException exception) { + if (exception == null) { + return ""; // Don't return null, just to make other code here simpler + } + return exception.getMessageAndLocation(); + } + + /** + * Implementation of warning; calls logMsg with info contained in exception. + * + * @param exception provided by Transformer + * @exception TransformerException thrown only if asked to or if loggers are + * bad + */ + @Override + public void warning(TransformerException exception) throws TransformerException { + // Log or validate the exception + if(expected[TYPE_WARNING] == ITEM_CHECKPASS) + fail("Unexpected error: ex " + exception); + + // Also re-throw the exception if asked to + if ((throwWhen & THROW_ON_WARNING) == THROW_ON_WARNING) { + // Note: re-throw the SAME exception, not a new one! + throw exception; + } + } + + /** + * Implementation of error; calls logMsg with info contained in exception. + * Only ever throws an exception itself if asked to or if loggers are bad. + * + * @param exception provided by Transformer + * @exception TransformerException thrown only if asked to. + */ + @Override + public void error(TransformerException exception) throws TransformerException { + // validate the exception + if(expected[TYPE_ERROR] == ITEM_CHECKPASS) + fail("Unexpected error: ex " + exception); + + // Also re-throw the exception if asked to + if ((throwWhen & THROW_ON_ERROR) == THROW_ON_ERROR) { + // Note: re-throw the SAME exception, not a new one! + throw exception; + } + } + + /** + * Implementation of error; calls logMsg with info contained in exception. + * Only ever throws an exception itself if asked to or if loggers are bad. + * Note that this may cause unusual behavior since we may not actually + * re-throw the exception, even though it was 'fatal'. + * + * @param exception provided by Transformer + * @exception TransformerException thrown only if asked to. + */ + @Override + public void fatalError(TransformerException exception) throws TransformerException { + // validate the exception + if(expected[TYPE_FATALERROR] == ITEM_CHECKPASS) + fail("Unexpected fatal error: ex " + exception); + + // Also re-throw the exception if asked to + if ((throwWhen & THROW_ON_FATAL) == THROW_ON_FATAL) { + // Note: re-throw the SAME exception, not a new one! + throw exception; + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/trax/CheckingURIResolver.java 2015-01-09 15:42:26.538194752 -0800 @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.trax; + +import com.sun.org.apache.xml.internal.utils.SystemIDResolver; +import java.util.Arrays; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerException; +import javax.xml.transform.URIResolver; +import javax.xml.transform.stream.StreamSource; +import static org.testng.Assert.fail; + +/** + * Implementation of URIResolver that logs all calls. Currently just provides + * default service; returns null. + * + */ +public class CheckingURIResolver implements URIResolver { + + /** + * Expected value(s) for URIs we may resolve. + */ + private final String[] expected; + + /** + * Default constructor for simple verification test. + */ + public CheckingURIResolver() { + this.expected = new String[0]; + } + + /** + * Initiator by given URIs that we expected. + * + * @param expected expected URI string that will be verified when resolve. + */ + public CheckingURIResolver(final String[] expected) { + this.expected = expected; + } + + /** + * This will be called by the processor when it encounters an xsl:include, + * xsl:import, or document() function. + * + * @param href An href attribute, which may be relative or absolute. + * @param base The base URI in effect when the href attribute was + * encountered. + * @return A non-null Source object. + * @throws TransformerException if an error occurs when trying to resolve + * the URI. + */ + @Override + public Source resolve(String href, String base) throws TransformerException { + // Note that we don't currently have a default URIResolver, + // so the LoggingURIResolver class will just attempt + // to use the SystemIDResolver class instead + String sysId = SystemIDResolver.getAbsoluteURI(href, base); + Source resolvedSource = new StreamSource(sysId); + + // verifiy sysId and base. + if(!Arrays.stream(expected).anyMatch(expectedStr -> + expectedStr.equals("{" + base + "}" + href))) + fail("Unexpected resolve called href:" + href + ";base:" + base); + return resolvedSource; + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/trax/TraxConst.java 2015-01-09 15:42:26.835195216 -0800 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2015, 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 org.apache.qetest.trax; + +import static jaxp.library.JAXPTestUtilities.getPathByClassName; + +/** + * This is the utilities test class provide basic support for Trax test. + */ +public class TraxConst { + /** + * XML source file directory. + */ + public static final String XML_DIR = getPathByClassName(TraxConst.class, "content"); + + /** + * Golden validation files directory. + */ + public static final String GOLDEN_DIR = getPathByClassName(TraxConst.class, "golden"); +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xsl/CheckingContentHandler.java 2015-01-09 15:42:27.105195637 -0800 @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xsl; + +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; + +/** + * Cheap-o ContentHandler for use by API tests. + *

Implements ContentHandler and a way to debug SAX stuff.

+ */ +public class CheckingContentHandler implements ContentHandler { + /** + * Our default handler that we pass all events through to. + */ + private volatile ContentHandler defaultHandler; + + /** + * Set a default handler for us to wrapper. Set a ContentHandler for us to + * use. + * @param handler Object of the correct type to pass-through to. + */ + public void setDefaultHandler(ContentHandler handler) { + defaultHandler = handler; + + } + + /** + * Accessor method for our default handler. + * @return default (Object) our default handler; null if unset + */ + public ContentHandler getDefaultHandler() { + return defaultHandler; + } + + @Override + public void setDocumentLocator(Locator locator) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void startDocument() throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void endDocument() throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void startPrefixMapping(String prefix, String uri) throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void endPrefixMapping(String prefix) throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void processingInstruction(String target, String data) throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void skippedEntity(String name) throws SAXException { + throw new UnsupportedOperationException("Not supported yet."); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xsl/CheckingLexicalHandler.java 2015-01-09 15:42:27.386196076 -0800 @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xsl; + +import org.xml.sax.SAXException; +import org.xml.sax.ext.LexicalHandler; + +/** + * Cheap-o LexicalHandler for use by API tests. This is a wrapper LexicalHandler. + * It always delegate the lexical analysis to wrapped LexicalHandler. + */ +public class CheckingLexicalHandler implements LexicalHandler { + /** + * Default handler + */ + private final LexicalHandler defaultHandler; + + /** + * Default constructor. + */ + public CheckingLexicalHandler() { + defaultHandler = null; + } + + /** + * Constructor by setting LexicalHandler. + * @param lh a delegated LexicalHandler. + */ + public CheckingLexicalHandler(LexicalHandler lh) { + defaultHandler = lh; + } + + ////////////////// Implement LexicalHandler ////////////////// + @Override + public void startDTD(String name, String publicId, String systemId) throws SAXException { + if(null != defaultHandler) + defaultHandler.startDTD(name, publicId, systemId); + } + + @Override + public void endDTD() throws SAXException { + if(null != defaultHandler) + defaultHandler.endDTD(); + } + + @Override + public void startEntity(String name) throws SAXException { + if(null != defaultHandler) + defaultHandler.startEntity(name); + } + + @Override + public void endEntity(String name) throws SAXException { + if(null != defaultHandler) + defaultHandler.endEntity(name); + } + + @Override + public void startCDATA() throws SAXException { + if(null != defaultHandler) + defaultHandler.startCDATA(); + } + + @Override + public void endCDATA() throws SAXException { + if(null != defaultHandler) + defaultHandler.endCDATA(); + } + + @Override + public void comment(char ch[], int start, int length) throws SAXException { + if(null != defaultHandler) + defaultHandler.comment(ch, start, length); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xsl/CheckingSAXErrorHandler.java 2015-01-09 15:42:27.694196558 -0800 @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xsl; + +import org.apache.qetest.CheckingHandler; +import static org.apache.qetest.CheckingHandler.Expectation.ITEM_CHECKPASS; +import static org.apache.qetest.CheckingHandler.Expectation.ITEM_DONT_CARE; +import static org.testng.Assert.fail; +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +/** + * Cheap-o ErrorHandler for use by API tests. + */ +public class CheckingSAXErrorHandler implements CheckingHandler, ErrorHandler { + + /** + * Constants determining when we should throw exceptions. + *
    Flags are combineable like a bitfield. + *
  • THROW_NEVER - never ever (always continue - note this may have + * unexpected effects when fatalErrors happen, see + * {@link javax.xml.transform.ErrorListener#fatalError(javax.xml.transform.TransformerException)}
  • + *
  • THROW_ON_WARNING - throw only on warnings
  • + *
  • THROW_ON_ERROR - throw only on errors
  • + *
  • THROW_ON_FATAL - throw only on fatalErrors - default
  • + *
  • THROW_ALWAYS - always throw exceptions
  • + *
+ */ + public static final int THROW_NEVER = 0; + + /** + * THROW_ON_WARNING - throw only on warnings. + */ + public static final int THROW_ON_WARNING = 1; + + /** + * THROW_ON_ERROR - throw only on errors. + */ + public static final int THROW_ON_ERROR = 2; + + /** + * THROW_ON_FATAL - throw only on fatalErrors - default. + */ + public static final int THROW_ON_FATAL = 4; + + /** + * THROW_ALWAYS - always throw exceptions. + */ + public static final int THROW_ALWAYS = THROW_ON_WARNING | THROW_ON_ERROR + | THROW_ON_FATAL; + + /** + * If we should throw an exception for each message type. + */ + private final int throwWhen; + + /** + * Constructor set when we should re-throw exceptions. + * + * @param t THROW_WHEN_* constant as to when we should re-throw an exception + * when we are called + */ + public CheckingSAXErrorHandler(int t) { + throwWhen = t; + } + + /** + * Default constructor will behave as default. Throw only when there is + * non-recoverable error. + */ + public CheckingSAXErrorHandler() { + this.throwWhen = THROW_ON_FATAL; + } + + /** + * Tells us when we should re-throw exceptions. + * + * @return THROW_WHEN_* constant as to when we should re-throw an exception + * when we are called + */ + public int getThrowWhen() { + return throwWhen; + } + + /** + * Constant for items returned in getCounters: messages. + */ + public static final int TYPE_WARNING = 0; + + /** + * Constant for items returned in getCounters: errors. + */ + public static final int TYPE_ERROR = 1; + + /** + * Constant for items returned in getCounters: fatalErrors. + */ + public static final int TYPE_FATALERROR = 2; + + /** + * Expected values for events we may handle, default=ITEM_DONT_CARE. + */ + private final Expectation[] expected = { + ITEM_DONT_CARE, /* warning */ + ITEM_DONT_CARE, /* error */ + ITEM_DONT_CARE /* fatalError */}; + + /** + * Ask us to report checkPass/Fail for certain events we handle. Since we + * may have to handle many events between when a test will be able to call + * us, testers can set this to have us automatically call checkPass when we + * see an item that matches, or to call checkFail when we get an unexpected + * item. Generally, we only call check* methods when: + *
    + *
  • containsString is not set, reset, or is ITEM_DONT_CARE, we do nothing + * (i.e. never call check* for this item)
  • + *
  • containsString is ITEM_CHECKFAIL, we will always call checkFail with + * the contents of any item if it occurs
  • + *
  • containsString is anything else, we will grab a String representation + * of every item of that type that comes along, and if the containsString is + * found, case-sensitive, within the handled item's string, call checkPass, + * otherwise call checkFail
  • + *
+ * Note that any time we handle a particular event that was expected, we + * un-set the expected value for that item. This means that you can only ask + * us to validate one occurrence of any particular event; all events after + * that one will be treated as ITEM_DONT_CARE. Callers can of course call + * setExpected again, of course, but this covers the case where we handle + * multiple events in a single block, perhaps out of the caller's direct + * control. Note that we first store the event via setLast(), then we + * validate the event as above, and then we potentially re-throw the + * exception as by setThrowWhen(). + * + * @param itemType which of the various types of items we might handle; + * should be defined as a constant by subclasses + * @param expectation expectation if we need check or not. + */ + @Override + public void setExpected(int itemType, Expectation expectation) { + expected[itemType] = expectation; + } + + /** + * Reset all items or counters we've handled. + */ + @Override + public void reset() { + for (int j = 0; j < expected.length; j++) { + expected[j] = ITEM_DONT_CARE; + } + } + + /** + * Receive notification of a warning. fail the test if it expects pass. + * Re-throw the exception when re-throw flag is set. + * @param exception The error information encapsulated in a + * SAX parse exception. + * @exception org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + */ + @Override + public void warning(SAXParseException exception) throws SAXException { + // Log or validate the exception + if (expected[TYPE_WARNING] == ITEM_CHECKPASS) { + fail("Unexpected error: ex " + exception); + } + + // Also re-throw the exception if asked to + if ((throwWhen & THROW_ON_WARNING) == THROW_ON_WARNING) { + // Note: re-throw the SAME exception, not a new one! + throw exception; + } + } + + /** + * Receive notification of a recoverable error. fail the test if it expects + * pass. Re-throw the exception when re-throw flag is set. + * @param exception The error information encapsulated in a + * SAX parse exception. + * @exception org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + */ + @Override + public void error(SAXParseException exception) throws SAXException { + // validate the exception + if (expected[TYPE_FATALERROR] == ITEM_CHECKPASS) { + fail("Unexpected fatal error: ex " + exception); + } + + // Also re-throw the exception if asked to + if ((throwWhen & THROW_ON_ERROR) == THROW_ON_ERROR) { + // Note: re-throw the SAME exception, not a new one! + throw exception; + } + } + + /** + * Receive notification of a non-recoverable error. fail the test if it + * expects pass. Re-throw the exception when re-throw flag is set. + * @param exception The error information encapsulated in a + * SAX parse exception. + * @exception org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + */ + @Override + public void fatalError(SAXParseException exception) throws SAXException { + // validate the exception + if (expected[TYPE_ERROR] == ITEM_CHECKPASS) { + fail("Unexpected fatal error: ex " + exception); + } + + // Also re-throw the exception if asked to + if ((throwWhen & THROW_ON_FATAL) == THROW_ON_FATAL) { + // Note: re-throw the SAME exception, not a new one! + throw exception; + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TransformWrapper.java 2015-01-09 15:42:27.974196995 -0800 @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.util.Properties; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; + +/** + * Helper interface to wrapper various XSLT processors for testing. + * + * A TransformWrapper wraps a particular 'flavor' of XSLT processing. This + * includes both a particular XSLT implementation, such as Xalan or Saxon, as + * well as a particular method to perform processing, like using streams or DOMs + * to perform transforms. + * + * As an important side effect, this class should return timing information + * about the steps done to perform the transformation. Note that exactly what is + * timed and how it's timed should be clearly documented in implementing + * classes! + * + * This is not a general-purpose wrapper for doing XSLT transformations: for + * that, you might as well use the real javax.xml.transform package itself. + * However this does allow many conformance and performance tests to run + * comparatively between different flavors of processors. + * + * TransformWrapper is a bit of an awkward name, but I wanted to keep it + * separate from the pre-existing ProcessorWrapper that this replaces so we can + * ensure stability for Xalan testing while updating to this new class. + * + */ +public interface TransformWrapper { + /** + * URL for set/getAttribute: should be an integer to set for the output + * indent of the processor. + * + * This is a common enough attribute that most wrapper implementations + * should be able to support it in a straightforward manner. + */ + public static final String ATTRIBUTE_INDENT + = "http://xml.apache.org/xalan/wrapper/indent"; + + /** + * URL for set/getAttribute: should be an Object to attempt to set as a + * diagnostic log/stream for the processor. + * + */ + public static final String ATTRIBUTE_DIAGNOSTICS + = "http://xml.apache.org/xalan/wrapper/diagnostics"; + + /** + * Marker for Attributes to set on Processors. + * + * Options that startWith() this constant will actually be attempted to be + * set onto our underlying processor/transformer. + */ + public static final String SET_PROCESSOR_ATTRIBUTES + = "Processor.setAttribute."; + + /** + * Get a specific description of the wrappered processor. + * + * @return specific description of the underlying processor or transformer + * implementation: this should include both the general product name, as + * well as specific version info. If possible, should be implemented without + * actively creating an underlying processor. + */ + public Properties getProcessorInfo(); + + /** + * Actually create/initialize an underlying processor or factory. + * + * For TrAX/javax.xml.transform implementations, this creates a new + * TransformerFactory. For Xalan-J 1.x this creates an XSLTProcessor. Other + * implementations may or may not actually do any work in this method. + * + * @param options Properties of options, possibly specific to that + * implementation. For future use. + * + * @return (Object)getProcessor() as a side-effect, this will be null if + * there was any problem creating the processor OR if the underlying + * implementation doesn't use this + * @throws javax.xml.transform.TransformerConfigurationException when + * actual implementation can't initiate a TransformerFactory. + */ + public TransformerFactory newProcessor(Properties options) throws TransformerConfigurationException; + + /** + * Transform supplied xmlName file with the stylesheet in the xslName file + * into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed for any underlying processor implementation. + * + * @param xmlName local path\filename of XML file to transform + * @param xslName local path\filename of XSL stylesheet to use + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + public void transform(String xmlName, String xslName, String resultName) + throws Exception; + + /** + * Pre-build/pre-compile a stylesheet. + * + * Although the actual mechanics are implementation-dependent, most + * processors have some method of pre-setting up the data needed by the + * stylesheet itself for later use in transforms. In + * TrAX/javax.xml.transform, this equates to creating a Templates object. + * + * Sets isStylesheetReady() to true if it succeeds. Users can then call + * transformWithStylesheet(xmlName, resultName) to actually perform a + * transformation with this pre-built stylesheet. + * + * @param xslName local path\filename of XSL stylesheet to use + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + * + * @see #transformWithStylesheet(String xmlName, String resultName) + */ + public void buildStylesheet(String xslName) throws Exception; + + /** + * Reports if a pre-built/pre-compiled stylesheet is ready; presumably built + * by calling buildStylesheet(xslName). + * + * @return true if one is ready; false otherwise + * + * @see #buildStylesheet(String xslName) + */ + public boolean isStylesheetReady(); + + /** + * Transform supplied xmlName file with a pre-built/pre-compiled stylesheet + * into a resultName file. + * + * User must have called buildStylesheet(xslName) beforehand, obviously. + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrappered processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation; throws an + * IllegalStateException if isStylesheetReady() == false. + * + * @see #buildStylesheet(String xslName) + */ + public void transformWithStylesheet(String xmlName, String resultName) + throws Exception; + + /** + * Transform supplied xmlName file with a stylesheet found in an + * xml-stylesheet PI into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. Implementations will use whatever facilities + * exist in their wrapped processor to fetch and build the stylesheet to + * use for the transform. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + public void transformEmbedded(String xmlName, String resultName) + throws Exception; + + /** + * Set a stylesheet parameter for use in later transforms. + * + * This method merely stores the triple for use later in a transform + * operation. Note that the actual mechanisims for setting parameters in + * implementation differ, especially with regards to namespaces. + * + * Note that the namespace may not contain the "{" or "}" characters, since + * these would be illegal XML namespaces anyways; an + * IllegalArgumentException will be thrown; also the name must not be null. + * + * @param namespace for the parameter, must not contain {} + * @param name of the parameter, must not be null + * @param value of the parameter + * + * @throws IllegalArgumentException thrown if the namespace or name appears + * to be illegal. + */ + public void setParameter(String namespace, String name, String value) + throws IllegalArgumentException; + + /** + * Get a parameter that was set with setParameter. + * + * Only returns parameters set locally, not parameters exposed by the + * underlying processor implementation. Not terribly useful but I like + * providing gets for any sets I define. + * + * @param namespace for the parameter, must not contain {} + * @param name of the parameter, must not be null + * + * @return value of the parameter; null if not found + */ + public Object getParameter(String namespace, String name); + + /** + * Reset our parameters and wrapper state, and optionally force creation of + * a new underlying processor implementation. + * + * This always clears our built stylesheet and any parameters that have been + * set. If newProcessor is true, also forces a re-creation of our underlying + * processor as if by calling newProcessor(). + * + * @param newProcessor if we should reset our underlying processor + * implementation as well + */ + public void reset(boolean newProcessor); +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TransformWrapperFactory.java 2015-01-09 15:42:28.293197493 -0800 @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.util.Properties; + +/** + * Factory static class for creating TransformWrappers. + * + * Includes a 'wrapperMapper' functionality to simplify specifying the 'flavor' + * of a wrapper to create. This is optional, but will allow a user to specify + * newWrapper("trax.file") and get back an instance of an + * org.apache.qetest.xslwrapper.TraxFileWrapper. + */ +public class TransformWrapperFactory { + + /** + * Currently known list of implemented wrappers. + *
    + *

    Allows specification of a simple name for each wrapper, so clients + * don't necessarily have to know the FQCN or fully qualified class name of + * their wrapper.

    + *
+ */ + protected final static Properties wrapperMapper = new Properties(); + + /** + * Static initializer for wrapperMapper. Attempts to load + * TransformWrapperFactory.properties into our wrapperMapper. + */ + static { + // Add a default trax flavor, since it's widely used + // This should be overwritten below if the properties + // file can be loaded. + wrapperMapper.put("trax.systemId", "org.apache.qetest.xslwrapper.TraxSystemIdWrapper"); + wrapperMapper.put("trax.file", "org.apache.qetest.xslwrapper.TraxFileWrapper"); + wrapperMapper.put("trax.stream", "org.apache.qetest.xslwrapper.TraxStreamWrapper"); + wrapperMapper.put("trax.dom", "org.apache.qetest.xslwrapper.TraxDOMWrapper"); + wrapperMapper.put("trax.sax", "org.apache.qetest.xslwrapper.TraxSAXWrapper"); + wrapperMapper.put("trax.localPath", "org.apache.qetest.xslwrapper.TraxLocalPathWrapper"); + wrapperMapper.put("trax.systemId3", "org.apache.qetest.xslwrapper.TraxSystemId3Wrapper"); + } + + /** + * Accessor for our wrapperMapper. + * @return Properties block of wrapper implementations that we implicitly + * know about; may be null if we have none + */ + public static final Properties getDescriptions() { + return wrapperMapper; + } + + /** + * Return an instance of a TransformWrapper of requested flavor. + * + * This static factory method creates TransformWrappers for the user. Our + * 'wrapperMapper' functionality allows users to either specify short names + * listed in TransformWrapperFactory.properties (which are mapped to the + * appropriate FQCN's) or to directly supply the FQCN of a wrapper to + * create. + * + * @param flavor to create, either a wrapperMapped one or FQCN + * + * @return instance of a wrapper; will throw an IllegalArgumentException if + * we cannot find the asked-for wrapper class anywhere + */ + public static final TransformWrapper newWrapper(String flavor) { + // Attempt to lookup the flavor: if found, use the value we got, + // otherwise default to the same value + String className = wrapperMapper.getProperty(flavor, flavor); + + try { + // Allow people to use bare classnames in popular packages + Class clazz = Class.forName(className); + return (TransformWrapper) clazz.newInstance(); + } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { + throw new IllegalArgumentException("newWrapper(" + flavor + ") threw: " + e.toString()); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TransformWrapperHelper.java 2015-01-09 15:42:28.558197907 -0800 @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.util.HashMap; +import java.util.Properties; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; + +/** + * A few default implementations of TransformWrapper methods. + * + * A TransformWrapperHelper implements a few of the common methods from + * TransformWrapper that don't directly interact with the underlying processor. + * Individual wrapper implementations are free to extend this class to get some + * free code. + */ +public abstract class TransformWrapperHelper implements TransformWrapper { + /** + * TransformerFactory to use; constructed in newProcessor(). + */ + protected TransformerFactory factory; + + /** + * Cached copy of newProcessor() properties. + */ + protected Properties newProcessorOpts; + + /** + * Constant denoting that indent should not be set. + */ + private static final int NO_INDENT = -2; + + /** + * Set of stylesheet parameters for use in transforms. + */ + protected final HashMap m_params = new HashMap<>(); + + /** + * If our wrapper has a built stylesheet ready. + */ + protected volatile boolean m_stylesheetReady = false; + + /** + * Current number of spaces to indent, default: NO_INDENT. Users call + * setAttribute(ATTRIBUTE_INDENT, int) to set this. If it is set, it will be + * applied to an underlying processor during each transform operation, where + * supported. + */ + protected int m_indent = NO_INDENT; + + /** + * Reports if a pre-built/pre-compiled stylesheet is ready; presumably built + * by calling buildStylesheet(xslName). + * + * @return true if one is ready; false otherwise + * + * @see #buildStylesheet(String xslName) + */ + @Override + public boolean isStylesheetReady() { + return m_stylesheetReady; + } + + /** + * Set a stylesheet parameter for use in later transforms. + * + * This method merely stores the triple for use later in a transform + * operation. Note that the actual mechanisims for setting parameters in + * implementation differ, especially with regards to namespaces. + * + * Note that the namespace may not contain the "{" or "}" characters, since + * these would be illegal XML namespaces anyways; an + * IllegalArgumentException will be thrown. Note that the name may not begin + * with the "{" character, since it would likely be an illegal XML name + * anyways; an IllegalArgumentException will be thrown. + * + * @param namespace for the parameter + * @param name of the parameter + * @param value of the parameter + * + * @throws IllegalArgumentException thrown if the namespace appears to be + * illegal. + */ + @Override + public void setParameter(String namespace, String name, String value) + throws IllegalArgumentException { + if (null != namespace) { + if ((namespace.contains("{")) + || (namespace.contains("}"))) { + throw new IllegalArgumentException("setParameter: illegal namespace includes brackets: " + namespace); + } + } + if (null != name) { + if (name.startsWith("{")) { + throw new IllegalArgumentException( + "setParameter: illegal name begins with bracket: " + name); + } + } + + if (null != namespace) { + m_params.put("{" + namespace + "}" + name, value); + } else { + m_params.put(name, value); + } + } + + /** + * Get a parameter that was set with setParameter. + * + * Only returns parameters set locally, not parameters exposed by the + * underlying processor implementation. Not terribly useful but I always + * like providing gets for any sets I define. + * + * @param namespace for the parameter + * @param name of the parameter + */ + @Override + public Object getParameter(String namespace, String name) { + if (null == m_params) { + return null; + } + + if (null != namespace) { + return m_params.get("{" + namespace + "}" + name); + } else { + return m_params.get(name); + } + } + + /** + * Apply the parameters that were set with setParameter to our underlying + * processor implementation. + * + * Subclasses may call this to apply all set parameters during each + * transform if they override the applyParameter() method to set a single + * parameter. + * + * This is a convenience method for getting data out of m_params that was + * encoded by our setParameter(). + * + * @param transformer a Transformer object. + */ + protected void applyParameters(Transformer transformer) { + m_params.forEach((key, value) -> { + String namespace = null; + String name; + if (key.startsWith("{")) { + int idx = key.indexOf("}"); + namespace = key.substring(1, idx); + name = key.substring(idx + 1); + } else { + // namespace stays null + name = key; + } + // Call subclassed worker method for each parameter + applyParameter(transformer, namespace, name, value); + }); + } + + /** + * Apply a single parameter to our underlying processor implementation: must + * be overridden. + * + * Subclasses must override; this class will throw an IllegalStateException + * since we can't do anything. + * + * @param transformer a Transformer object. + * @param namespace for the parameter, may be null + * @param name for the parameter, should not be null + * @param value for the parameter, may be null + */ + protected abstract void applyParameter(Transformer transformer, String namespace, + String name, String value); + + /** + * Reset our parameters and wrapper state, and optionally force creation of + * a new underlying processor implementation. + * + * This class clears the indent and any parameters. Subclasses are free to + * call us to get this default behavior or not. Note that subclasses must + * clear m_stylesheetReady themselves if needed. + * + * @param newProcessor ignored in this class + */ + @Override + public void reset(boolean newProcessor) { + m_params.clear(); + m_indent = NO_INDENT; + } + + /** + * Ensure newProcessor has been called when needed. + * + * Prevent users from shooting themselves in the foot by calling a + * transform* API before newProcessor(). + * + * @throws java.lang.Exception + */ + public void preventFootShooting() throws Exception { + if (null == factory) { + newProcessor(newProcessorOpts); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TraxDOMWrapper.java 2015-01-09 15:42:28.821198318 -0800 @@ -0,0 +1,392 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.util.Properties; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Source; +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.stream.StreamResult; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +/** + * Implementation of TransformWrapper that uses the TrAX API and uses DOMs for + * it's sources. + * + * This implementation records separate times for xslRead (time to parse the xsl + * and build a DOM) and xslBuild (time to take the DOMSource object until it's + * built the templates); xmlRead (time to parse the xml and build a DOM). Note + * xmlBuild is not timed since it's not easily measureable in TrAX. The + * transform time is just the time to create the DOMResult object; the + * resultsWrite is the separate time it takes to serialize that to disk. + * + * Important! The underlying System property of + * javax.xml.transform.TransformerFactory will determine the actual TrAX + * implementation used. This value will be reported out in our + * getProcessorInfo() method. + * + */ +public class TraxDOMWrapper extends TransformWrapperHelper { + /** + * Templates to use for buildStylesheet(). + */ + private Templates builtTemplates; + + /** + * Get a general description of this wrapper itself. + * + * @return Uses TrAX to perform transforms from DOMSource(node) + */ + public String getDescription() { + return "Uses TrAX to perform transforms from DOMSource(node)"; + } + + /** + * Get a specific description of the wrappered processor. + * + * @return specific description of the underlying processor or transformer + * implementation: this should include both the general product name, as + * well as specific version info. If possible, should be implemented without + * actively creating an underlying processor. + */ + @Override + public Properties getProcessorInfo() { + Properties p = TraxWrapperUtils.getTraxInfo(); + p.put("traxwrapper.method", "dom"); + p.put("traxwrapper.desc", getDescription()); + return p; + } + + /** + * Actually create/initialize an underlying processor or factory. + * + * For TrAX/javax.xml.transform implementations, this creates a new + * TransformerFactory. For Xalan-J 1.x this creates an XSLTProcessor. Other + * implementations may or may not actually do any work in this method. + * + * @param options Properties of options, unused. + * + * @return (Object)getProcessor() as a side-effect, this will be null if + * there was any problem creating the processor OR if the underlying + * implementation doesn't use this + * @throws javax.xml.transform.TransformerConfigurationException when + * actual implementation doesn't support StreamSource or StreamResult. + */ + @Override + public TransformerFactory newProcessor(Properties options) throws TransformerConfigurationException { + newProcessorOpts = options; + reset(false); + factory = TransformerFactory.newInstance(); + // Verify the factory supports DOM! + if (!(factory.getFeature(DOMSource.FEATURE) + && factory.getFeature(DOMResult.FEATURE))) { + throw new TransformerConfigurationException("TraxDOMWrapper.newProcessor: factory does not support DOM!"); + } + // Set any of our options as Attributes on the factory + TraxWrapperUtils.setAttributes(factory, options); + return factory; + } + + /** + * Transform supplied xmlName file with the stylesheet in the xslName file + * into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed for any underlying processor implementation. + * + * @param xmlName local path\filename of XML file to transform + * @param xslName local path\filename of XSL stylesheet to use + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transform(String xmlName, String xslName, String resultName) + throws Exception { + preventFootShooting(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + + // Timed: read xsl into a DOM + Node xslNode = docBuilder.parse(new InputSource(filenameToURL(xslName))); + + // Untimed: create DOMSource and setSystemId + DOMSource xslSource = new DOMSource(xslNode); + xslSource.setSystemId(filenameToURL(xslName)); + + // Timed: build Transformer from DOMSource + Transformer transformer = factory.newTransformer(xslSource); + + // Timed: read xml into a DOM + Node xmlNode = docBuilder.parse(new InputSource(filenameToURL(xmlName))); + + // Untimed: create DOMSource and setSystemId + DOMSource xmlSource = new DOMSource(xmlNode); + xmlSource.setSystemId(filenameToURL(xmlName)); + + // Untimed: create DOMResult + Document outDoc = docBuilder.newDocument(); + DocumentFragment outNode = outDoc.createDocumentFragment(); + DOMResult domResult = new DOMResult(outNode); + + // Untimed: Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Untimed: Apply any parameters needed + applyParameters(transformer); + + // Timed: build xml (so to speak) and transform + transformer.transform(xmlSource, domResult); + + // Untimed: prepare serializer with outputProperties + // from the stylesheet + Transformer resultSerializer = factory.newTransformer(); + Properties serializationProps = transformer.getOutputProperties(); + resultSerializer.setOutputProperties(serializationProps); + + // Timed: writeResults from the DOMResult + resultSerializer.transform(new DOMSource(outNode), + new StreamResult(resultName)); + } + + /** + * Pre-build/pre-compile a stylesheet. + * + * Although the actual mechanics are implementation-dependent, most + * processors have some method of pre-setting up the data needed by the + * stylesheet itself for later use in transforms. In + * TrAX/javax.xml.transform, this equates to creating a Templates object. + * + * Sets isStylesheetReady() to true if it succeeds. Users can then call + * transformWithStylesheet(xmlName, resultName) to actually perform a + * transformation with this pre-built stylesheet. + * + * @param xslName local path\filename of XSL stylesheet to use + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + * + * @see #transformWithStylesheet(String xmlName, String resultName) + */ + @Override + public void buildStylesheet(String xslName) throws Exception { + preventFootShooting(); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + + // Read xsl into a DOM + Node xslNode = docBuilder.parse(new InputSource(filenameToURL(xslName))); + // Untimed: create DOMSource and setSystemId + DOMSource xslSource = new DOMSource(xslNode); + xslSource.setSystemId(filenameToURL(xslName)); + + // Build Templates from DOMSource + builtTemplates = factory.newTemplates(xslSource); + + m_stylesheetReady = true; + } + + /** + * Transform supplied xmlName file with a pre-built/pre-compiled stylesheet + * into a resultName file. + * + * User must have called buildStylesheet(xslName) beforehand, obviously. + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrappered processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation; throws an + * IllegalStateException if isStylesheetReady() == false. + * + * @see #buildStylesheet(String xslName) + */ + @Override + public void transformWithStylesheet(String xmlName, String resultName) + throws Exception { + if (!isStylesheetReady()) { + throw new IllegalStateException("transformWithStylesheet() when isStylesheetReady() == false"); + } + + preventFootShooting(); + + // Get Transformer from Templates + Transformer transformer = builtTemplates.newTransformer(); + + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + + // Read xml into a DOM + Node xmlNode = docBuilder.parse(new InputSource(filenameToURL(xmlName))); + + // Create DOMSource and setSystemId + DOMSource xmlSource = new DOMSource(xmlNode); + xmlSource.setSystemId(filenameToURL(xmlName)); + + // Create DOMResult + Document outNode = docBuilder.newDocument(); + DOMResult domResult = new DOMResult(outNode); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // Build xml (so to speak) and transform + transformer.transform(xmlSource, domResult); + + // Prepare serializer with outputProperties from the stylesheet + Transformer resultSerializer = factory.newTransformer(); + Properties serializationProps = transformer.getOutputProperties(); + resultSerializer.setOutputProperties(serializationProps); + + // writeResults from the DOMResult + resultSerializer.transform(new DOMSource(outNode), + new StreamResult(resultName)); + } + + /** + * Transform supplied xmlName file with a stylesheet found in an + * xml-stylesheet PI into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. Implementations will use whatever facilities + * exist in their wrapped processor to fetch and build the stylesheet to + * use for the transform. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transformEmbedded(String xmlName, String resultName) + throws Exception { + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setNamespaceAware(true); + DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); + + // read xml into a DOM + Node xmlNode = docBuilder.parse(new InputSource(filenameToURL(xmlName))); + + // create DOMSource and setSystemId + DOMSource xmlSource = new DOMSource(xmlNode); + xmlSource.setSystemId(filenameToURL(xmlName)); + + // readxsl from the xml document + Source xslSource = factory.getAssociatedStylesheet(xmlSource, + null, null, null); + + // build Transformer from Source + Transformer transformer = factory.newTransformer(xslSource); + + // create DOMResult + Document outNode = docBuilder.newDocument(); + DOMResult domResult = new DOMResult(outNode); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // Build xml (so to speak) and transform + transformer.transform(xmlSource, domResult); + + // Prepare serializer with outputProperties from the stylesheet + Transformer resultSerializer = factory.newTransformer(); + Properties serializationProps = transformer.getOutputProperties(); + resultSerializer.setOutputProperties(serializationProps); + + // writeResults from the DOMResult + resultSerializer.transform(new DOMSource(outNode), + new StreamResult(resultName)); + } + + /** + * Reset our parameters and wrapper state, and optionally force creation of + * a new underlying processor implementation. + * + * This always clears our built stylesheet and any parameters that have been + * set. If newProcessor is true, also forces a re-creation of our underlying + * processor as if by calling newProcessor(). + * + * @param newProcessor if we should reset our underlying processor + * implementation as well + */ + @Override + public void reset(boolean newProcessor) { + super.reset(newProcessor); // clears indent and parameters + m_stylesheetReady = false; + builtTemplates = null; + if (newProcessor) { + try { + newProcessor(newProcessorOpts); + } catch (TransformerConfigurationException ignore) {} + } + } + + /** + * Apply a single parameter to a Transformer. + * + * Overridden to take a Transformer and call setParameter(). + * + * @param transformer a Transformer object. + * @param namespace for the parameter, may be null + * @param name for the parameter, should not be null + * @param value for the parameter, may be null + */ + @Override + protected void applyParameter(Transformer transformer, String namespace, + String name, String value) { + try { + // Munge the namespace into the name per + // javax.xml.transform.Transformer.setParameter() + if (null != namespace) { + name = "{" + namespace + "}" + name; + } + transformer.setParameter(name, value); + } catch (Exception e) { + throw new IllegalArgumentException("applyParameter threw: " + e.toString()); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TraxFileWrapper.java 2015-01-09 15:42:29.077198718 -0800 @@ -0,0 +1,298 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.io.File; +import java.util.Properties; + +import javax.xml.transform.Source; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +/** + * Implementation of TransformWrapper that uses the TrAX API and uses files for + * it's sources. + * + * This is the second most common usage: transformer = + * factory.newTransformer(new StreamSource(new File(xslName))); + * transformer.transform(new StreamSource(new File(xmlName)), new + * StreamResult(resultFileName)); + * + * Important! The underlying System property of + * javax.xml.transform.TransformerFactory will determine the actual TrAX + * implementation used. This value will be reported out in our + * getProcessorInfo() method. + * + */ +public class TraxFileWrapper extends TransformWrapperHelper { + /** + * Templates to use for buildStylesheet(). + */ + private Templates builtTemplates; + + /** + * Get a general description of this wrapper itself. + * + * @return Uses TrAX to perform transforms from StreamSource(systemId) + */ + public String getDescription() { + return "Uses TrAX to perform transforms from StreamSource(new File(filename))"; + } + + /** + * Get a specific description of the wrappered processor. + * + * @return specific description of the underlying processor or transformer + * implementation: this should include both the general product name, as + * well as specific version info. If possible, should be implemented without + * actively creating an underlying processor. + */ + @Override + public Properties getProcessorInfo() { + Properties p = TraxWrapperUtils.getTraxInfo(); + p.put("traxwrapper.method", "file"); + p.put("traxwrapper.desc", getDescription()); + return p; + } + + /** + * Actually create/initialize an underlying processor or factory. + * + * For TrAX/javax.xml.transform implementations, this creates a new + * TransformerFactory. For Xalan-J 1.x this creates an XSLTProcessor. Other + * implmentations may or may not actually do any work in this method. + * + * @param options Hashtable of options, unused. + * + * @return (Object)getProcessor() as a side-effect, this will be null if + * there was any problem creating the processor OR if the underlying + * implementation doesn't use this + * @throws javax.xml.transform.TransformerConfigurationException when + * actual implementation doesn't support StreamSource or StreamResult. + */ + @Override + public TransformerFactory newProcessor(Properties options) throws TransformerConfigurationException { + newProcessorOpts = options; + reset(false); + factory = TransformerFactory.newInstance(); + // Verify the factory supports Streams! + if (!(factory.getFeature(StreamSource.FEATURE) + && factory.getFeature(StreamResult.FEATURE))) { + throw new TransformerConfigurationException("TraxFileWrapper.newProcessor: factory does not support Streams!"); + } + // Set any of our options as Attributes on the factory + TraxWrapperUtils.setAttributes(factory, options); + return factory; + } + + /** + * Transform supplied xmlName file with the stylesheet in the xslName file + * into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed for any underlying processor implementation. + * + * @param xmlName local path\filename of XML file to transform + * @param xslName local path\filename of XSL stylesheet to use + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transform(String xmlName, String xslName, String resultName) + throws Exception { + preventFootShooting(); + + // read/build xsl from a File + Transformer transformer = factory.newTransformer(new StreamSource(new File(xslName))); + + // Untimed: Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Untimed: Apply any parameters needed + applyParameters(transformer); + + // Timed: read/build xml, transform, and write results + transformer.transform(new StreamSource(new File(xmlName)), new StreamResult(resultName)); + } + + /** + * Pre-build/pre-compile a stylesheet. + * + * Although the actual mechanics are implementation-dependent, most + * processors have some method of pre-setting up the data needed by the + * stylesheet itself for later use in transforms. In + * TrAX/javax.xml.transform, this equates to creating a Templates object. + * + * Sets isStylesheetReady() to true if it succeeds. Users can then call + * transformWithStylesheet(xmlName, resultName) to actually perform a + * transformation with this pre-built stylesheet. + * + * @param xslName local path\filename of XSL stylesheet to use + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + * + * @see #transformWithStylesheet(String xmlName, String resultName) + */ + @Override + public void buildStylesheet(String xslName) throws Exception { + preventFootShooting(); + + // read/build xsl from a URL + builtTemplates = factory.newTemplates(new StreamSource(new File(xslName))); + m_stylesheetReady = true; + } + + /** + * Transform supplied xmlName file with a pre-built/pre-compiled stylesheet + * into a resultName file. + * + * User must have called buildStylesheet(xslName) beforehand, obviously. + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation; throws an + * IllegalStateException if isStylesheetReady() == false. + * + * @see #buildStylesheet(String xslName) + */ + @Override + public void transformWithStylesheet(String xmlName, String resultName) + throws Exception { + if (!isStylesheetReady()) { + throw new IllegalStateException("transformWithStylesheet() when isStylesheetReady() == false"); + } + + preventFootShooting(); + + // Get Transformer from Templates + Transformer transformer = builtTemplates.newTransformer(); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // read/build xml, transform, and write results + long startTime = System.currentTimeMillis(); + transformer.transform(new StreamSource(new File(xmlName)), + new StreamResult(resultName)); + } + + /** + * Transform supplied xmlName file with a stylesheet found in an + * xml-stylesheet PI into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. Implementations will use whatever facilities + * exist in their wrapped processor to fetch and build the stylesheet to + * use for the transform. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transformEmbedded(String xmlName, String resultName) + throws Exception { + preventFootShooting(); + // Read xsl from the xml document. + Source xslSource = factory.getAssociatedStylesheet( + new StreamSource(new File(xmlName)),null, null, null); + + // Build xsl from a URL + Transformer transformer = factory.newTransformer(xslSource); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // read/build xml, transform, and write results. + transformer.transform(new StreamSource(new File(xmlName)), + new StreamResult(resultName)); + } + + /** + * Reset our parameters and wrapper state, and optionally force creation of + * a new underlying processor implementation. + * + * This always clears our built stylesheet and any parameters that have been + * set. If newProcessor is true, also forces a re-creation of our underlying + * processor as if by calling newProcessor(). + * + * @param newProcessor if we should reset our underlying processor + * implementation as well + */ + @Override + public void reset(boolean newProcessor) { + super.reset(newProcessor); // clears indent and parameters + m_stylesheetReady = false; + builtTemplates = null; + if (newProcessor) { + try { + newProcessor(newProcessorOpts); + } catch (TransformerConfigurationException ignore) {} + } + } + + /** + * Apply a single parameter to a Transformer. + * + * Overridden to take a Transformer and call setParameter(). + * + * @param transformer a Transformer object. + * @param namespace for the parameter, may be null + * @param name for the parameter, should not be null + * @param value for the parameter, may be null + */ + @Override + protected void applyParameter(Transformer transformer, String namespace, + String name, String value) { + try { + // Munge the namespace into the name per + // javax.xml.transform.Transformer.setParameter() + if (null != namespace) { + name = "{" + namespace + "}" + name; + } + transformer.setParameter(name, value); + } catch (Exception e) { + throw new IllegalArgumentException("applyParameter threw: " + e.toString()); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TraxLocalPathWrapper.java 2015-01-09 15:42:29.376199185 -0800 @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.util.Properties; +import javax.xml.transform.Source; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +/** + * Implementation of TransformWrapper that uses the TrAX API and uses supplied + * local paths for it's sources. + * + * This is the most common usage: transformer = factory.newTransformer(new + * StreamSource(xslPath)); transformer.transform(new StreamSource(xmlPath), new + * StreamResult(resultFileName)); + * + * Note that URLs are theoretically required by the TrAX API's, so this is not + * necessarily a good test... It is essentially the same as TraxLocalPathWrapper + * without calling filenameToURL(). + * + * Important! The underlying System property of + * javax.xml.transform.TransformerFactory will determine the actual TrAX + * implementation used. This value will be reported out in our + * getProcessorInfo() method. + * + */ +public class TraxLocalPathWrapper extends TransformWrapperHelper { + /** + * Templates to use for buildStylesheet(). + */ + private Templates builtTemplates; + + /** + * Get a general description of this wrapper itself. + * + * @return Uses TrAX to perform transforms from StreamSource(localPath) + */ + public String getDescription() { + return "Uses TrAX to perform transforms from StreamSource(localPath)"; + } + + /** + * Get a specific description of the wrappered processor. + * + * @return specific description of the underlying processor or transformer + * implementation: this should include both the general product name, as + * well as specific version info. If possible, should be implemented without + * actively creating an underlying processor. + */ + @Override + public Properties getProcessorInfo() { + Properties p = TraxWrapperUtils.getTraxInfo(); + p.put("traxwrapper.method", "localPath"); + p.put("traxwrapper.desc", getDescription()); + return p; + } + + /** + * Actually create/initialize an underlying processor or factory. + * + * For TrAX/javax.xml.transform implementations, this creates a new + * TransformerFactory. For Xalan-J 1.x this creates an XSLTProcessor. Other + * implmentations may or may not actually do any work in this method. + * + * @param options Hashtable of options, unused. + * + * @return (Object)getProcessor() as a side-effect, this will be null if + * there was any problem creating the processor OR if the underlying + * implementation doesn't use this + * @throws javax.xml.transform.TransformerConfigurationException when + * actual implementation doesn't support StreamSource or StreamResult. + */ + @Override + public TransformerFactory newProcessor(Properties options) throws TransformerConfigurationException { + newProcessorOpts = options; + reset(false); + factory = TransformerFactory.newInstance(); + // Verify the factory supports Streams! + if (!(factory.getFeature(StreamSource.FEATURE) + && factory.getFeature(StreamResult.FEATURE))) { + throw new TransformerConfigurationException("TraxLocalPathWrapper.newProcessor: factory does not support Streams!"); + } + // Set any of our options as Attributes on the factory + TraxWrapperUtils.setAttributes(factory, options); + return factory; + } + + /** + * Transform supplied xmlName file with the stylesheet in the xslName file + * into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed for any underlying processor implementation. + * + * @param xmlName local path\filename of XML file to transform + * @param xslName local path\filename of XSL stylesheet to use + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transform(String xmlName, String xslName, String resultName) + throws Exception { + preventFootShooting(); + // read/build xsl from a URL + Transformer transformer = factory.newTransformer(new StreamSource(xslName)); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // read/build xml, transform, and write results. + transformer.transform(new StreamSource(xmlName), + new StreamResult(resultName)); + } + + /** + * Pre-build/pre-compile a stylesheet. + * + * Although the actual mechanics are implementation-dependent, most + * processors have some method of pre-setting up the data needed by the + * stylesheet itself for later use in transforms. In + * TrAX/javax.xml.transform, this equates to creating a Templates object. + * + * Sets isStylesheetReady() to true if it succeeds. Users can then call + * transformWithStylesheet(xmlName, resultName) to actually perform a + * transformation with this pre-built stylesheet. + * + * @param xslName local path\filename of XSL stylesheet to use + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + * + * @see #transformWithStylesheet(String xmlName, String resultName) + */ + @Override + public void buildStylesheet(String xslName) throws Exception { + preventFootShooting();// Timed: read/build xsl from a URL + builtTemplates = factory.newTemplates(new StreamSource(xslName)); + m_stylesheetReady = true; + } + + /** + * Transform supplied xmlName file with a pre-built/pre-compiled stylesheet + * into a resultName file. + * + * User must have called buildStylesheet(xslName) beforehand, obviously. + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation; throws an + * IllegalStateException if isStylesheetReady() == false. + * + * @see #buildStylesheet(String xslName) + */ + @Override + public void transformWithStylesheet(String xmlName, String resultName) + throws Exception { + if (!isStylesheetReady()) { + throw new IllegalStateException("transformWithStylesheet() when isStylesheetReady() == false"); + } + + preventFootShooting(); + + // Get Transformer from Templates + Transformer transformer = builtTemplates.newTransformer(); + // Untimed: Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // read/build xml, transform, and write results + transformer.transform(new StreamSource(xmlName), + new StreamResult(resultName)); + } + + /** + * Transform supplied xmlName file with a stylesheet found in an + * xml-stylesheet PI into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. Implementations will use whatever facilities + * exist in their wrapped processor to fetch and build the stylesheet to + * use for the transform. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transformEmbedded(String xmlName, String resultName) + throws Exception { + preventFootShooting(); + // Read xsl from the xml document + Source xslSource = factory.getAssociatedStylesheet( + new StreamSource(xmlName), null, null, null); + + // Build xsl from a URL + Transformer transformer = factory.newTransformer(xslSource); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // read/build xml, transform, and write results + transformer.transform(new StreamSource(xmlName), + new StreamResult(resultName)); + } + + /** + * Reset our parameters and wrapper state, and optionally force creation of + * a new underlying processor implementation. + * + * This always clears our built stylesheet and any parameters that have been + * set. If newProcessor is true, also forces a re-creation of our underlying + * processor as if by calling newProcessor(). + * + * @param newProcessor if we should reset our underlying processor + * implementation as well + */ + @Override + public void reset(boolean newProcessor) { + super.reset(newProcessor); // clears indent and parameters + m_stylesheetReady = false; + builtTemplates = null; + if (newProcessor) { + try { + newProcessor(newProcessorOpts); + } catch (TransformerConfigurationException ignore) {} + } + } + + /** + * Apply a single parameter to a Transformer. + * + * Overridden to take a Transformer and call setParameter(). + * + * @param transformer a Transformer object. + * @param namespace for the parameter, may be null + * @param name for the parameter, should not be null + * @param value for the parameter, may be null + */ + @Override + protected void applyParameter(Transformer transformer, String namespace, + String name, String value) { + try { + // Munge the namespace into the name per + // javax.xml.transform.Transformer.setParameter() + if (null != namespace) { + name = "{" + namespace + "}" + name; + } + transformer.setParameter(name, value); + } catch (Exception e) { + throw new IllegalArgumentException("applyParameter threw: " + e.toString()); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TraxSAXWrapper.java 2015-01-09 15:42:29.637199593 -0800 @@ -0,0 +1,463 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.io.ByteArrayOutputStream; +import java.io.FileOutputStream; +import java.util.Properties; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXResult; +import javax.xml.transform.sax.SAXSource; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TemplatesHandler; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + +/** + * Implementation of TransformWrapper that uses the TrAX API and uses + * SAXSource/SAXResult whenever possible. + * This implementation uses SAX to build the stylesheet and to perform the + * transformation. + *

Important! The underlying System property of + * javax.xml.transform.TransformerFactory will determine the actual TrAX + * implementation used. This value will be reported out in our + * getProcessorInfo() method.

+ * + */ +public class TraxSAXWrapper extends TransformWrapperHelper { + /** + * SAXTransformerFactory we actually use; constructed in newProcessor(). + */ + private SAXTransformerFactory saxFactory; + + /** + * Templates to use for buildStylesheet(). + */ + private Templates builtTemplates; + + /** + * Get a general description of this wrapper itself. + * + * @return Uses TrAX to perform transforms from SAXSource(systemId) + */ + public String getDescription() { + return "Uses TrAX to perform transforms from SAXSource(stream)"; + } + + /** + * Get a specific description of the wrappered processor. + * + * @return specific description of the underlying processor or transformer + * implementation: this should include both the general product name, as + * well as specific version info. If possible, should be implemented without + * actively creating an underlying processor. + */ + @Override + public Properties getProcessorInfo() { + Properties p = TraxWrapperUtils.getTraxInfo(); + p.put("traxwrapper.method", "sax"); + p.put("traxwrapper.desc", getDescription()); + return p; + } + + /** + * Actually create/initialize an underlying processor or factory. + * + * For TrAX/javax.xml.transform implementations, this creates a new + * TransformerFactory. + * + * @param options Hashtable of options, unused. + * + * @return (Object)getProcessor() as a side-effect, this will be null if + * there was any problem creating the processor OR if the underlying + * implementation doesn't use this + * @throws javax.xml.transform.TransformerConfigurationException when + * actual implementation doesn't support StreamSource or StreamResult. + */ + @Override + public TransformerFactory newProcessor(Properties options) throws TransformerConfigurationException { + newProcessorOpts = options; + reset(false); + factory = TransformerFactory.newInstance(); + // Verify the factory supports SAX! + if (!(factory.getFeature(SAXSource.FEATURE) + && factory.getFeature(SAXResult.FEATURE))) { + throw new TransformerConfigurationException("TraxSAXWrapper.newProcessor: factory does not support SAX!"); + } + // Set any of our options as Attributes on the factory + TraxWrapperUtils.setAttributes(factory, options); + saxFactory = (SAXTransformerFactory) factory; + return saxFactory; + } + + /** + * Transform supplied xmlName file with the stylesheet in the xslName file + * into a resultName file using SAX. + * + * Pseudocode: + * // Read/build stylesheet + * xslReader.setContentHandler(templatesHandler); + * xslReader.parse(xslName); + * + * xslOutputProps = templates.getOutputProperties(); + * // Set features and tie in DTD, lexical, etc. handling + * + * serializingHandler.getTransformer().setOutputProperties(xslOutputProps); + * serializingHandler.setResult(new StreamResult(outBytes)); + * stylesheetHandler.setResult(new SAXResult(serializingHandler)); + * xmlReader.setContentHandler(stylesheetHandler); + * // Perform Transform + * xmlReader.parse(xmlName); + * // Separately: write bytes to disk + * + * + * @param xmlName local path\filename of XML file to transform + * @param xslName local path\filename of XSL stylesheet to use + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrappered processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transform(String xmlName, String xslName, String resultName) + throws Exception { + preventFootShooting(); + + // Create a ContentHandler to handle parsing of the xsl + TemplatesHandler templatesHandler = saxFactory.newTemplatesHandler(); + + // Create an XMLReader and set its ContentHandler. + // Be sure to use the JAXP methods only! + XMLReader xslReader = getJAXPXMLReader(); + xslReader.setContentHandler(templatesHandler); + + // read/build Templates from StreamSource + xslReader.parse(filenameToURL(xslName)); + + // Get the Templates object from the ContentHandler. + Templates templates = templatesHandler.getTemplates(); + // Get the outputProperties from the stylesheet, so + // we can later use them for the serialization + Properties xslOutputProps = templates.getOutputProperties(); + + // Create a ContentHandler to handle parsing of the XML + TransformerHandler stylesheetHandler = saxFactory.newTransformerHandler(templates); + // Also set systemId to the stylesheet + stylesheetHandler.setSystemId(filenameToURL(xslName)); + + // Untimed: Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(stylesheetHandler.getTransformer(), newProcessorOpts); + + // Apply any parameters needed + applyParameters(stylesheetHandler.getTransformer()); + + // Use a new XMLReader to parse the XML document + XMLReader xmlReader = getJAXPXMLReader(); + xmlReader.setContentHandler(stylesheetHandler); + + // Set the ContentHandler to also function as LexicalHandler, + // includes "lexical" events (e.g., comments and CDATA). + xmlReader.setProperty( + "http://xml.org/sax/properties/lexical-handler", + stylesheetHandler); + + // Also attempt to set as a DeclHandler, which Xalan-J + // supports even though it is not required by JAXP + // Ignore exceptions for other processors since this + // is not a required setting + try { + xmlReader.setProperty( + "http://xml.org/sax/properties/declaration-handler", + stylesheetHandler); + } catch (SAXException se) { /* no-op - ignore */ } + + // added by sb. Tie together DTD and other handling + xmlReader.setDTDHandler(stylesheetHandler); + try { + xmlReader.setFeature( + "http://xml.org/sax/features/namespace-prefixes", + true); + } catch (SAXException se) { /* no-op - ignore */ } + try { + xmlReader.setFeature( + "http://apache.org/xml/features/validation/dynamic", + true); + } catch (SAXException se) { /* no-op - ignore */ } + + // Create a 'pipe'-like identity transformer, so we can + // easily get our results serialized to disk + TransformerHandler serializingHandler = saxFactory.newTransformerHandler(); + // Set the stylesheet's output properties into the output + // via it's Transformer + serializingHandler.getTransformer().setOutputProperties(xslOutputProps); + + // Create StreamResult to byte stream in memory + ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); + StreamResult byteResult = new StreamResult(outBytes); + serializingHandler.setResult(byteResult); + + // Create a SAXResult dumping into our 'pipe' serializer + // and tie in lexical handling (is any other handling needed?) + SAXResult saxResult = new SAXResult(serializingHandler); + saxResult.setLexicalHandler(serializingHandler); + + // Set the original stylesheet to dump into our result + stylesheetHandler.setResult(saxResult); + + // Parse the XML input document and do transform + xmlReader.parse(filenameToURL(xmlName)); + + // writeResults from the byte array + byte[] writeBytes = outBytes.toByteArray(); // Should this be timed too or not? + try (FileOutputStream writeStream = new FileOutputStream(resultName)) { + writeStream.write(writeBytes); + } + } + + /** + * Pre-build/pre-compile a stylesheet. + * + * Although the actual mechanics are implementation-dependent, most + * processors have some method of pre-setting up the data needed by the + * stylesheet itself for later use in transforms. In + * TrAX/javax.xml.transform, this equates to creating a Templates object. + * + * Sets isStylesheetReady() to true if it succeeds. Users can then call + * transformWithStylesheet(xmlName, resultName) to actually perform a + * transformation with this pre-built stylesheet. + * + * @param xslName local path\filename of XSL stylesheet to use + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + * + * @see #transformWithStylesheet(String xmlName, String resultName) + */ + @Override + public void buildStylesheet(String xslName) throws Exception { + preventFootShooting(); + + // Create a ContentHandler to handle parsing of the xsl + TemplatesHandler templatesHandler = saxFactory.newTemplatesHandler(); + + // Create an XMLReader and set its ContentHandler. + XMLReader xslReader = getJAXPXMLReader(); + xslReader.setContentHandler(templatesHandler); + + // read/build Templates from StreamSource + xslReader.parse(filenameToURL(xslName)); + + // Also set systemId to the stylesheet + templatesHandler.setSystemId(filenameToURL(xslName)); + + // Get the Templates object from the ContentHandler. + builtTemplates = templatesHandler.getTemplates(); + m_stylesheetReady = true; + } + + /** + * Transform supplied xmlName file with a pre-built/pre-compiled stylesheet + * into a resultName file. + * + * User must have called buildStylesheet(xslName) beforehand, obviously. + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrappered processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation; throws an + * IllegalStateException if isStylesheetReady() == false. + * + * @see #buildStylesheet(String xslName) + */ + @Override + public void transformWithStylesheet(String xmlName, String resultName) + throws Exception { + if (!isStylesheetReady()) { + throw new IllegalStateException("transformWithStylesheet() when isStylesheetReady() == false"); + } + preventFootShooting(); + + // Get the outputProperties from the stylesheet, so + // we can later use them for the serialization + Properties xslOutputProps = builtTemplates.getOutputProperties(); + + // Create a ContentHandler to handle parsing of the XML + TransformerHandler stylesheetHandler = saxFactory.newTransformerHandler(builtTemplates); + + // Untimed: Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(stylesheetHandler.getTransformer(), newProcessorOpts); + + // Apply any parameters needed + applyParameters(stylesheetHandler.getTransformer()); + + // Use a new XMLReader to parse the XML document + XMLReader xmlReader = getJAXPXMLReader(); + xmlReader.setContentHandler(stylesheetHandler); + + // Set the ContentHandler to also function as LexicalHandler, + // includes "lexical" events (e.g., comments and CDATA). + xmlReader.setProperty( + "http://xml.org/sax/properties/lexical-handler", + stylesheetHandler); + xmlReader.setProperty( + "http://xml.org/sax/properties/declaration-handler", + stylesheetHandler); + + // added by sb. Tie together DTD and other handling + xmlReader.setDTDHandler(stylesheetHandler); + try { + xmlReader.setFeature( + "http://xml.org/sax/features/namespace-prefixes", + true); + } catch (SAXException se) { /* no-op - ignore */ } + try { + xmlReader.setFeature( + "http://apache.org/xml/features/validation/dynamic", + true); + } catch (SAXException se) { /* no-op - ignore */ } + + // Create a 'pipe'-like identity transformer, so we can + // easily get our results serialized to disk + TransformerHandler serializingHandler = saxFactory.newTransformerHandler(); + // Set the stylesheet's output properties into the output + // via it's Transformer + serializingHandler.getTransformer().setOutputProperties(xslOutputProps); + + // Create StreamResult to byte stream in memory + ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); + StreamResult byteResult = new StreamResult(outBytes); + serializingHandler.setResult(byteResult); + + // Create a SAXResult dumping into our 'pipe' serializer + // and tie in lexical handling (is any other handling needed?) + SAXResult saxResult = new SAXResult(serializingHandler); + saxResult.setLexicalHandler(serializingHandler); + + // Set the original stylesheet to dump into our result + stylesheetHandler.setResult(saxResult); + + // Timed: Parse the XML input document and do transform + xmlReader.parse(filenameToURL(xmlName)); + + // Timed: writeResults from the byte array + byte[] writeBytes = outBytes.toByteArray(); // Should this be timed too or not? + try (FileOutputStream writeStream = new FileOutputStream(resultName)) { + writeStream.write(writeBytes); + } + } + + /** + * Transform supplied xmlName file with a stylesheet found in an + * xml-stylesheet PI into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. Implementations will use whatever facilities + * exist in their wrappered processor to fetch and build the stylesheet to + * use for the transform. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrappered processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transformEmbedded(String xmlName, String resultName) + throws Exception { + throw new RuntimeException("TraxSAXWrapper.transformEmbedded not implemented yet!"); + } + + /** + * Reset our parameters and wrapper state, and optionally force creation of + * a new underlying processor implementation. + * + * This always clears our built stylesheet and any parameters that have been + * set. If newProcessor is true, also forces a re-creation of our underlying + * processor as if by calling newProcessor(). + * + * @param newProcessor if we should reset our underlying processor + * implementation as well + */ + @Override + public void reset(boolean newProcessor) { + super.reset(newProcessor); // clears indent and parameters + m_stylesheetReady = false; + builtTemplates = null; + if (newProcessor) { + try { + newProcessor(newProcessorOpts); + } catch (TransformerConfigurationException ignore) {} + } + } + + /** + * Apply a single parameter to a Transformer. + * + * Overridden to take a Transformer and call setParameter(). + * + * @param transformer a Transformer object. + * @param namespace for the parameter, may be null + * @param name for the parameter, should not be null + * @param value for the parameter, may be null + */ + @Override + protected void applyParameter(Transformer transformer, String namespace, + String name, String value) { + try { + // Munge the namespace into the name per + // javax.xml.transform.Transformer.setParameter() + if (null != namespace) { + name = "{" + namespace + "}" + name; + } + transformer.setParameter(name, value); + } catch (Exception e) { + throw new IllegalArgumentException("applyParameter threw: " + e.toString()); + } + } + + /** + * Worker method to get an XMLReader. + * + * Not the most efficient of methods, but makes the code simpler. + * + * @return a new XMLReader for use, with setNamespaceAware(true) + * @throws java.lang.Exception + */ + protected XMLReader getJAXPXMLReader() throws Exception { + // Be sure to use the JAXP methods only! + SAXParserFactory sfactory = SAXParserFactory.newInstance(); + sfactory.setNamespaceAware(true); + return sfactory.newSAXParser().getXMLReader(); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TraxStreamWrapper.java 2015-01-09 15:42:29.901200005 -0800 @@ -0,0 +1,409 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.Properties; +import javax.xml.transform.Source; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import static jaxp.library.JAXPTestUtilities.filenameToURL; + +/** + * Implementation of TransformWrapper that uses the TrAX API and uses in-memory + * streams for it's sources. + * + *

+ * This implementation separates the process of reading xml and xsl files from + * disk into byte arrays out from the time processing of a new + * StreamSource(byte[]) takes to build a stylesheet. It also separates the time + * of performing the transformation to a StreamResult(byte[]) from the time + * spent simply sending the byte[] through a FileOutputStream to disk.

+ * + *

+ * Important! The underlying System property of + * javax.xml.transform.TransformerFactory will determine the actual TrAX + * implementation used. This value will be reported out in our + * getProcessorInfo() method.

+ * + */ +public class TraxStreamWrapper extends TransformWrapperHelper { + /** + * Templates to use for buildStylesheet(). + */ + private Templates builtTemplates; + + /** + * Get a general description of this wrapper itself. + * + * @return Uses TrAX to perform transforms from StreamSource(systemId) + */ + public String getDescription() { + return "Uses TrAX to perform transforms from StreamSource(stream)"; + } + + /** + * Get a specific description of the wrappered processor. + * + * @return specific description of the underlying processor or transformer + * implementation: this should include both the general product name, as + * well as specific version info. If possible, should be implemented without + * actively creating an underlying processor. + */ + @Override + public Properties getProcessorInfo() { + Properties p = TraxWrapperUtils.getTraxInfo(); + p.put("traxwrapper.method", "streams"); + p.put("traxwrapper.desc", getDescription()); + return p; + } + + /** + * Actually create/initialize an underlying processor or factory. + * + * For TrAX/javax.xml.transform implementations, this creates a new + * TransformerFactory. + * + * @param options Properties of options, unused. + * + * @return (Object)getProcessor() as a side-effect, this will be null if + * there was any problem creating the processor OR if the underlying + * implementation doesn't use this. + * @throws javax.xml.transform.TransformerConfigurationException when + * actual implementation doesn't support StreamSource or StreamResult. + */ + @Override + public TransformerFactory newProcessor(Properties options) + throws TransformerConfigurationException { + newProcessorOpts = options; + reset(false); + factory = TransformerFactory.newInstance(); + // Verify the factory supports Streams! + if (!(factory.getFeature(StreamSource.FEATURE) + && factory.getFeature(StreamResult.FEATURE))) { + throw new TransformerConfigurationException("TraxStreamWrapper.newProcessor: factory does not support Streams!"); + } + // Set any of our options as Attributes on the factory + TraxWrapperUtils.setAttributes(factory, options); + return factory; + } + + /** + * Transform supplied xmlName file with the stylesheet in the xslName file + * into a resultName file. + * + * Names are assumed to be local path\filename references, and will be read + * as byte streams before being passed to underlying StreamSources, etc. + * + * @param xmlName local path\filename of XML file to transform + * @param xslName local path\filename of XSL stylesheet to use + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrappered processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transform(String xmlName, String xslName, String resultName) + throws Exception { + preventFootShooting(); + + File xslFile = new File(xslName); + int xslLength = new Long(xslFile.length()).intValue(); + byte[] xslBytes = new byte[xslLength]; + File xmlFile = new File(xmlName); + int xmlLength = new Long(xmlFile.length()).intValue(); + byte[] xmlBytes = new byte[xmlLength]; + try (FileInputStream xslStream = new FileInputStream(xslFile); + FileInputStream xmlStream = new FileInputStream(xmlFile)) { + // Read xsl into a byte array + xslStream.read(xslBytes); + // Create StreamSource and setSystemId + StreamSource xslSource = new StreamSource(new ByteArrayInputStream(xslBytes)); + // Note that systemIds must be a legal URI + xslSource.setSystemId(filenameToURL(xslName)); + + // Build Transformer from StreamSource + Transformer transformer = factory.newTransformer(xslSource); + + // Read xml into a byte array + xmlStream.read(xmlBytes); + + // Create StreamSource and setSystemId + StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(xmlBytes)); + xmlSource.setSystemId(filenameToURL(xmlName)); + + // Create StreamResult + ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); + StreamResult byteResult = new StreamResult(outBytes); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // Build xml (so to speak) and transform + transformer.transform(xmlSource, byteResult); + + // writeResults from the byte array + byte[] writeBytes = outBytes.toByteArray(); // Should this be timed too or not? + try (FileOutputStream writeStream = new FileOutputStream(resultName)) { + writeStream.write(writeBytes); + } + } + } + + /** + * Pre-build/pre-compile a stylesheet. + * + * Although the actual mechanics are implementation-dependent, most + * processors have some method of pre-setting up the data needed by the + * stylesheet itself for later use in transforms. In + * TrAX/javax.xml.transform, this equates to creating a Templates object. + * + * Sets isStylesheetReady() to true if it succeeds. Users can then call + * transformWithStylesheet(xmlName, resultName) to actually perform a + * transformation with this pre-built stylesheet. + * + * @param xslName local path\filename of XSL stylesheet to use + * + * @throws Exception any underlying exceptions from the wrappered processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + * + * @see #transformWithStylesheet(String xmlName, String resultName) + */ + @Override + public void buildStylesheet(String xslName) throws Exception { + preventFootShooting(); + + File xslFile = new File(xslName); + int xslLength = new Long(xslFile.length()).intValue(); + byte[] xslBytes = new byte[xslLength]; + + try(FileInputStream xslStream = new FileInputStream(xslFile)) { + // Read xsl into a byte array + xslStream.read(xslBytes); + + // Create StreamSource and setSystemId + StreamSource xslSource = new StreamSource(new ByteArrayInputStream(xslBytes)); + // Note that systemIds must be a legal URI + xslSource.setSystemId(filenameToURL(xslName)); + + // Build Transformer from StreamSource + builtTemplates = factory.newTemplates(xslSource); + + // Set internal state that we have a templates ready + // Note: in theory, there's no need to check builtTemplates + // since the newTemplates should never return null + // (it might have thrown an exception, but we don't care) + m_stylesheetReady = true; + } + } + + /** + * Transform supplied xmlName file with a pre-built/pre-compiled stylesheet + * into a resultName file. + * + * User must have called buildStylesheet(xslName) beforehand, obviously. + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation; throws an + * IllegalStateException if isStylesheetReady() == false. + * + * @see #buildStylesheet(String xslName) + */ + @Override + public void transformWithStylesheet(String xmlName, String resultName) + throws Exception { + if (!isStylesheetReady()) { + throw new IllegalStateException("transformWithStylesheet() when isStylesheetReady() == false"); + } + + preventFootShooting(); + + try (FileOutputStream writeStream = new FileOutputStream(resultName)) { + // Get Transformer from Templates + Transformer transformer = builtTemplates.newTransformer(); + + File xmlFile = new File(xmlName); + int xmlLength = new Long(xmlFile.length()).intValue(); + byte[] xmlBytes = new byte[xmlLength]; + FileInputStream xmlStream = new FileInputStream(xmlFile); + // Read xml into a byte array + xmlStream.read(xmlBytes); + + // Create StreamSource and setSystemId + StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(xmlBytes)); + xmlSource.setSystemId(filenameToURL(xmlName)); + + // Create StreamResult + ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); + StreamResult byteResult = new StreamResult(outBytes); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Untimed: Apply any parameters needed + applyParameters(transformer); + + // Build xml (so to speak) and transform + transformer.transform(xmlSource, byteResult); + + // writeResults from the byte array + byte[] writeBytes = outBytes.toByteArray(); + writeStream.write(writeBytes); + } + } + + /** + * Transform supplied xmlName file with a stylesheet found in an + * xml-stylesheet PI into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. Implementations will use whatever facilities + * exist in their wrappered processor to fetch and build the stylesheet to + * use for the transform. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transformEmbedded(String xmlName, String resultName) + throws Exception { + preventFootShooting(); + + File xmlFile = new File(xmlName); + try (FileOutputStream writeStream = new FileOutputStream(resultName);) { + int xmlLength = new Long(xmlFile.length()).intValue(); + byte[] xmlBytes = new byte[xmlLength]; + FileInputStream xmlStream = new FileInputStream(xmlFile); + // Read xml into a byte array + xmlStream.read(xmlBytes); + + // Create StreamSource and setSystemId + StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(xmlBytes)); + xmlSource.setSystemId(filenameToURL(xmlName)); + + // Read xsl from the xml document + Source xslSource = factory.getAssociatedStylesheet(xmlSource, null, null, null); + + // Build xsl from a URL + Transformer transformer = factory.newTransformer(xslSource); + + // Re-read the XML file for use in transform; not timed + xmlFile = new File(xmlName); + xmlLength = new Long(xmlFile.length()).intValue(); + xmlBytes = new byte[xmlLength]; + xmlStream = new FileInputStream(xmlFile); + xmlStream.read(xmlBytes); + + // Create StreamSource and setSystemId + xmlSource = new StreamSource(new ByteArrayInputStream(xmlBytes)); + xmlSource.setSystemId(filenameToURL(xmlName)); + + // Create StreamResult + ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); + StreamResult byteResult = new StreamResult(outBytes); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // Build xml (so to speak) and transform + transformer.transform(xmlSource, byteResult); + + // writeResults from the byte array + byte[] writeBytes = outBytes.toByteArray(); + + writeStream.write(writeBytes); + } + + } + + /** + * Reset our parameters and wrapper state, and optionally force creation of + * a new underlying processor implementation. + * + * This always clears our built stylesheet and any parameters that have been + * set. If newProcessor is true, also forces a re-creation of our underlying + * processor as if by calling newProcessor(). + * + * @param newProcessor if we should reset our underlying processor + * implementation as well + */ + @Override + public void reset(boolean newProcessor) { + super.reset(newProcessor); // clears indent and parameters + m_stylesheetReady = false; + builtTemplates = null; + if (newProcessor) { + try { + newProcessor(newProcessorOpts); + } catch (TransformerConfigurationException ignore) {} + } + } + + /** + * Apply a single parameter to a Transformer. + * + * Overridden to take a Transformer and call setParameter(). + * + * @param transformer a Transformer object. + * @param namespace for the parameter, may be null + * @param name for the parameter, should not be null + * @param value for the parameter, may be null + */ + @Override + protected void applyParameter(Transformer transformer, String namespace, + String name, String value) { + try { + // Munge the namespace into the name per + // javax.xml.transform.Transformer.setParameter() + if (null != namespace) { + name = "{" + namespace + "}" + name; + } + transformer.setParameter(name, value); + } catch (Exception e) { + throw new IllegalArgumentException("applyParameter threw: " + e.toString()); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TraxSystemId3Wrapper.java 2015-01-09 15:42:30.184200447 -0800 @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.util.Properties; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import static jaxp.library.JAXPTestUtilities.filenameToURL; + +/** + * Implementation of TransformWrapper that uses the TrAX API and uses systemId + * URL's for it's sources; plus always transforms the xml file three + * times. + * + * This is the most common usage: transformer = factory.newTransformer(new + * StreamSource(xslURL)); transformer.transform(new StreamSource(xmlURL), new + * StreamResult(resultFileName)); + * + * Important! The underlying System property of + * javax.xml.transform.TransformerFactory will determine the actual TrAX + * implementation used. This value will be reported out in our + * getProcessorInfo() method. + */ +public class TraxSystemId3Wrapper extends TraxSystemIdWrapper { + + /** + * Get a general description of this wrapper itself. + * + * @return Uses TrAX to perform THREE transforms from StreamSource(systemId) + */ + @Override + public String getDescription() { + return "Uses TrAX to perform THREE transforms from StreamSource(systemId)"; + } + + /** + * Get a specific description of the wrappered processor. + * + * @return specific description of the underlying processor or transformer + * implementation: this should include both the general product name, as + * well as specific version info. If possible, should be implemented without + * actively creating an underlying processor. + */ + @Override + public Properties getProcessorInfo() { + Properties p = TraxWrapperUtils.getTraxInfo(); + p.put("traxwrapper.method", "systemId3"); + p.put("traxwrapper.desc", getDescription()); + return p; + } + + /** + * Transform supplied xmlName file with the stylesheet in the xslName file + * into a resultName file three times. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed for any underlying processor implementation. + * + * @param xmlName local path\filename of XML file to transform + * @param xslName local path\filename of XSL stylesheet to use + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transform(String xmlName, String xslName, String resultName) + throws Exception { + preventFootShooting(); + + // Read/build xsl from a URL + Transformer transformer = factory.newTransformer( + new StreamSource(filenameToURL(xslName))); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // Read/build xml, transform, and write results + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + + // This is to test transformer re-use + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + } + + /** + * Transform supplied xmlName file with a pre-built/pre-compiled stylesheet + * into a resultName file three times. + * + * User must have called buildStylesheet(xslName) beforehand, obviously. + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation; throws an + * IllegalStateException if isStylesheetReady() == false. + * + * @see #buildStylesheet(String xslName) + */ + @Override + public void transformWithStylesheet(String xmlName, String resultName) + throws Exception { + if (!isStylesheetReady()) { + throw new IllegalStateException("transformWithStylesheet() when isStylesheetReady() == false"); + } + + preventFootShooting(); + + // Get Transformer from Templates + Transformer transformer = builtTemplates.newTransformer(); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // read/build xml, transform, and write results + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + + // This is to test transformer re-use + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + } + + /** + * Transform supplied xmlName file with a stylesheet found in an + * xml-stylesheet PI into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. Implementations will use whatever facilities + * exist in their wrapped processor to fetch and build the stylesheet to + * use for the transform. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transformEmbedded(String xmlName, String resultName) + throws Exception { + preventFootShooting(); + // Read xsl from the xml document + Source xslSource = factory.getAssociatedStylesheet(new StreamSource(filenameToURL(xmlName)), + null, null, null); + + // Build xsl from a URL + Transformer transformer = factory.newTransformer(xslSource); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // read/build xml, transform, and write results + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + + // This is to test transformer re-use + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TraxSystemIdWrapper.java 2015-01-09 15:42:30.452200866 -0800 @@ -0,0 +1,299 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.util.Properties; +import javax.xml.transform.Source; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import static jaxp.library.JAXPTestUtilities.filenameToURL; + +/** + * Implementation of TransformWrapper that uses the TrAX API and uses systemId + * URL's for it's sources. + * + * This is the most common usage: transformer = factory.newTransformer(new + * StreamSource(xslURL)); transformer.transform(new StreamSource(xmlURL), new + * StreamResult(resultFileName)); + * + * Important! The underlying System property of + * javax.xml.transform.TransformerFactory will determine the actual TrAX + * implementation used. This value will be reported out in our + * getProcessorInfo() method. + */ +public class TraxSystemIdWrapper extends TransformWrapperHelper { + /** + * Templates to use for buildStylesheet(). + */ + protected Templates builtTemplates; + + /** + * Get a general description of this wrapper itself. + * + * @return Uses TrAX to perform transforms from StreamSource(systemId) + */ + public String getDescription() { + return "Uses TrAX to perform transforms from StreamSource(systemId)"; + } + + /** + * Get a specific description of the wrapped processor. + * + * @return specific description of the underlying processor or transformer + * implementation: this should include both the general product name, as + * well as specific version info. If possible, should be implemented without + * actively creating an underlying processor. + */ + @Override + public Properties getProcessorInfo() { + Properties p = TraxWrapperUtils.getTraxInfo(); + p.put("traxwrapper.method", "systemId"); + p.put("traxwrapper.desc", getDescription()); + return p; + } + + /** + * Actually create/initialize an underlying processor or factory. + * + * For TrAX/javax.xml.transform implementations, this creates a new + * TransformerFactory. For Xalan-J 1.x this creates an XSLTProcessor. Other + * implmentations may or may not actually do any work in this method. + * + * @param options Properties of options, unused. + * + * @return (Object)getProcessor() as a side-effect, this will be null if + * there was any problem creating the processor OR if the underlying + * implementation doesn't use this + * @throws javax.xml.transform.TransformerConfigurationException when + * actual implementation doesn't support StreamSource or StreamResult. + */ + @Override + public TransformerFactory newProcessor(Properties options) + throws TransformerConfigurationException { + newProcessorOpts = options; + reset(false); + factory = TransformerFactory.newInstance(); + // Verify the factory supports Streams! + if (!(factory.getFeature(StreamSource.FEATURE) + && factory.getFeature(StreamResult.FEATURE))) { + throw new TransformerConfigurationException("TraxSystemIdWrapper.newProcessor: factory does not support Streams!"); + } + // Set any of our options as Attributes on the factory + TraxWrapperUtils.setAttributes(factory, newProcessorOpts); + return factory; + } + + /** + * Transform supplied xmlName file with the stylesheet in the xslName file + * into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed for any underlying processor implementation. + * + * @param xmlName local path\filename of XML file to transform + * @param xslName local path\filename of XSL stylesheet to use + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transform(String xmlName, String xslName, String resultName) + throws Exception { + preventFootShooting(); + + // Read/build xsl from a URL + Transformer transformer = factory.newTransformer( + new StreamSource(filenameToURL(xslName))); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // Read/build xml, transform, and write results + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + } + + /** + * Pre-build/pre-compile a stylesheet. + * + * Although the actual mechanics are implementation-dependent, most + * processors have some method of pre-setting up the data needed by the + * stylesheet itself for later use in transforms. In + * TrAX/javax.xml.transform, this equates to creating a Templates object. + * + * Sets isStylesheetReady() to true if it succeeds. Users can then call + * transformWithStylesheet(xmlName, resultName) to actually perform a + * transformation with this pre-built stylesheet. + * + * @param xslName local path\filename of XSL stylesheet to use + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + * + * @see #transformWithStylesheet(String xmlName, String resultName) + */ + @Override + public void buildStylesheet(String xslName) throws Exception { + preventFootShooting(); + + // Read/build xsl from a URL + builtTemplates = factory.newTemplates( + new StreamSource(filenameToURL(xslName))); + m_stylesheetReady = true; + } + + /** + * Transform supplied xmlName file with a pre-built/pre-compiled stylesheet + * into a resultName file. + * + * User must have called buildStylesheet(xslName) beforehand, obviously. + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation; throws an + * IllegalStateException if isStylesheetReady() == false. + * + * @see #buildStylesheet(String xslName) + */ + @Override + public void transformWithStylesheet(String xmlName, String resultName) + throws Exception { + if (!isStylesheetReady()) { + throw new IllegalStateException("transformWithStylesheet() when isStylesheetReady() == false"); + } + + preventFootShooting(); + + // Get Transformer from Templates + Transformer transformer = builtTemplates.newTransformer(); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // Read/build xml, transform, and write results + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + } + + /** + * Transform supplied xmlName file with a stylesheet found in an + * xml-stylesheet PI into a resultName file. + * + * Names are assumed to be local path\filename references, and will be + * converted to URLs as needed. Implementations will use whatever facilities + * exist in their wrapped processor to fetch and build the stylesheet to + * use for the transform. + * + * @param xmlName local path\filename of XML file to transform + * @param resultName local path\filename to put result in + * + * @throws Exception any underlying exceptions from the wrapped processor + * are simply allowed to propagate; throws a RuntimeException if any other + * problems prevent us from actually completing the operation + */ + @Override + public void transformEmbedded(String xmlName, String resultName) + throws Exception { + preventFootShooting(); + // Read xsl from the xml document + Source xslSource = factory.getAssociatedStylesheet(new StreamSource(filenameToURL(xmlName)), + null, null, null); + + // Build xsl from a URL + Transformer transformer = factory.newTransformer(xslSource); + + // Set any of our options as Attributes on the transformer + TraxWrapperUtils.setAttributes(transformer, newProcessorOpts); + + // Apply any parameters needed + applyParameters(transformer); + + // Read/build xml, transform, and write results + transformer.transform(new StreamSource(filenameToURL(xmlName)), + new StreamResult(resultName)); + } + + /** + * Reset our parameters and wrapper state, and optionally force creation of + * a new underlying processor implementation. + * + * This always clears our built stylesheet and any parameters that have been + * set. If newProcessor is true, also forces a re-creation of our underlying + * processor as if by calling newProcessor(). + * + * @param newProcessor if we should reset our underlying processor + * implementation as well + */ + @Override + public void reset(boolean newProcessor) { + super.reset(newProcessor); // clears indent and parameters + m_stylesheetReady = false; + builtTemplates = null; + if (newProcessor) { + try { + newProcessor(newProcessorOpts); + } catch (TransformerConfigurationException ignore) { + } + } + } + + /** + * Apply a single parameter to a Transformer. + * + * Overridden to take a Transformer and call setParameter(). + * + * @param transformer a Transformer object. + * @param namespace for the parameter, may be null + * @param name for the parameter, should not be null + * @param value for the parameter, may be null + */ + @Override + protected void applyParameter(Transformer transformer, String namespace, + String name, String value) { + try { + // Munge the namespace into the name per + // javax.xml.transform.Transformer.setParameter() + if (null != namespace) { + name = "{" + namespace + "}" + name; + } + transformer.setParameter(name, value); + } catch (Exception e) { + throw new IllegalArgumentException("applyParameter threw: " + e.toString()); + } + } +} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/apache/qetest/xslwrapper/TraxWrapperUtils.java 2015-01-09 15:42:30.717201280 -0800 @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.qetest.xslwrapper; + +import java.lang.reflect.Field; +import java.util.Enumeration; +import java.util.Properties; + +import javax.xml.transform.ErrorListener; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; + +/** + * Cheap-o utilities for Trax*Wrapper implementations. + * + */ +public abstract class TraxWrapperUtils { + + /** + * Get a generic description of the TrAX related info. + * + * @return Properties block with basic info about any TrAX implementing + * processor, plus specific version information about Xalan-J 2.x or + * Xerces-J 1.x if found. + */ + public static Properties getTraxInfo() { + Properties p = new Properties(); + p.put("traxwrapper.api", "trax"); + p.put("traxwrapper.language", "java"); + try { + Properties sysProps = System.getProperties(); + p.put("traxwrapper.jaxp.transform", + sysProps.getProperty("javax.xml.transform.TransformerFactory", "unset")); + p.put("traxwrapper.jaxp.parser.dom", + sysProps.getProperty("javax.xml.parsers.DocumentBuilderFactory", "unset")); + p.put("traxwrapper.jaxp.parser.sax", + sysProps.getProperty("javax.xml.parsers.SAXParserFactory", "unset")); + } /* In case we're in an Applet */ + catch (SecurityException ignore) { /* no-op, ignore */ } + + // Look for some Xalan/Xerces specific version info + try { + Class clazz = Class.forName("org.apache.xerces.framework.Version"); + // Found 1.x, grab it's version fields + Field f = clazz.getField("fVersion"); + p.put("traxwrapper.xerces.version", (String) f.get(null)); + } catch (ClassNotFoundException | IllegalAccessException + | IllegalArgumentException | NoSuchFieldException + | SecurityException ignore) {} + + try { + Class clazz = Class.forName("org.apache.xalan.processor.XSLProcessorVersion"); + Field f = clazz.getField("S_VERSION"); + p.put("traxwrapper.xalan.version", (String) f.get(null)); + } catch (ClassNotFoundException | IllegalAccessException + | IllegalArgumentException | NoSuchFieldException + | SecurityException ignore) {} + + return p; + } + + /** + * Apply specific Attributes to a TransformerFactory OR Transformer, OR call + * specific setFoo() API's on a TransformerFactory OR Transformer. + * + * Filters on hash keys.startsWith("Processor.setAttribute"). Most Attributes + * are simply passed to factory.setAttribute(), however certain special + * cases are handled: setURIResolver, setErrorListener. Exceptions thrown by + * underlying transformer are propagated. + * + * This takes an Object so that an underlying worker method can process + * either a TransformerFactory or a Transformer. + * + * @param setPropsOn + * @param attrs potential attributes to set. + */ + public static void setAttributes(Object setPropsOn, + Properties attrs) throws IllegalArgumentException { + if ((null == setPropsOn) || (null == attrs)) { + return; + } + + Enumeration attrKeys; + try { + // Attempt to use as a Properties block.. + attrKeys = attrs.propertyNames(); + } catch (ClassCastException cce) { + // .. but fallback to get as Hashtable instead + attrKeys = attrs.keys(); + } + + while (attrKeys.hasMoreElements()) { + String key = (String) attrKeys.nextElement(); + // Only attempt to set the attr if it matches our marker + if ((null != key) + && (key.startsWith(TransformWrapper.SET_PROCESSOR_ATTRIBUTES))) { + Object value; + try { + // Attempt to use as a Properties block.. + value = attrs.getProperty(key); + // But, if null, then try getting as hash anyway + if (null == value) { + value = attrs.get(key); + } + } catch (ClassCastException cce) { + // .. but fallback to get as Hashtable instead + value = attrs.get(key); + } + // Strip off our marker for the property name + String processorKey = key.substring(TransformWrapper.SET_PROCESSOR_ATTRIBUTES.length()); + // Ugly, but it works -sc + if (setPropsOn instanceof TransformerFactory) { + setAttribute((TransformerFactory) setPropsOn, processorKey, value); + } else if (setPropsOn instanceof Transformer) { + setAttribute((Transformer) setPropsOn, processorKey, value); + } + } + } + + } + + /** + * Token specifying a call to setURIResolver. + */ + private final static String SET_URI_RESOLVER = "setURIResolver"; + + /** + * Token specifying a call to setErrorListener. + */ + private final static String SET_ERROR_LISTENER = "setErrorListener"; + + /** + * Apply specific Attributes to a TransformerFactory OR call specific + * setFoo() API's on a TransformerFactory. + * + * Filters on keys.startsWith("Processor.setAttribute.") Most Attributes + * are simply passed to factory.setAttribute(), however certain special + * cases are handled: setURIResolver, setErrorListener. Exceptions thrown by + * underlying transformer are propagated. + * + * @see setAttribute(Transformer, String, Object) + * @param factory TransformerFactory to call setAttributes on. + * @param key specific attribute or special case attribute. + * @param value to set for key. + */ + private static void setAttribute(TransformerFactory factory, + String key, Object value) throws IllegalArgumentException { + if ((null == factory) || (null == key)) { + return; + } + + // Note: allow exceptions to propagate here + // Check if this is a special case to call a specific + // API, or the general case to call setAttribute(key...) + switch(key) { + case SET_URI_RESOLVER: + factory.setURIResolver((URIResolver) value); + break; + case SET_ERROR_LISTENER: + factory.setErrorListener((ErrorListener) value);; + break; + default: + // General case; just call setAttribute + factory.setAttribute(key, value); + break; + } + } + + /** + * Apply specific Attributes to a Transformer OR call specific setFoo() + * API's on a Transformer. + * + * Filters on keys.startsWith("Processor.setAttribute.") Only certain + * special cases are handled: setURIResolver, setErrorListener. Exceptions + * thrown by underlying transformer are propagated. + * + * @see setAttribute(TransformerFactory, String, Object) + * @param factory TransformerFactory to call setAttributes on. + * @param key specific attribute or special case attribute. + * @param value to set for key. + */ + private static void setAttribute(Transformer transformer, + String key, Object value) throws IllegalArgumentException { + if ((null == transformer) || (null == key)) { + return; + } + + // Note: allow exceptions to propagate here + // Check if this is a special case to call a specific + // API, or the general case to call setAttribute(key...) + switch(key) { + case SET_URI_RESOLVER: + transformer.setURIResolver((URIResolver) value); + break; + case SET_ERROR_LISTENER: + transformer.setErrorListener((ErrorListener) value); + break; + } + } +} --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/MyAttrCHandler.java 2015-01-09 15:42:31.098201875 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2014, 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 org.xml.sax.ptests; - -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * Simple attributes handler. - */ -public class MyAttrCHandler extends DefaultHandler { - /** - * FileWriter to write string to output file. - */ - private final BufferedWriter bWriter; - - /** - * Initiate FileWriter - * @param fileName output file name. - * @throws IOException - */ - public MyAttrCHandler(String fileName) throws IOException { - bWriter = new BufferedWriter(new FileWriter(fileName)); - } - - /** - * Write element content before start access every element. - * @throws org.xml.sax.SAXException - */ - @Override - public void startElement(String uri, String localName, - String qName, Attributes attributes) throws SAXException { - try { - String string = "uri <" + uri + "> localName <" + localName + - "> qName <" + qName + ">"; - - bWriter.write( string, 0, string.length()); - bWriter.newLine(); - - int length = attributes.getLength(); - string = "length: " + length; - - bWriter.write( string, 0, string.length()); - bWriter.newLine(); - - for (int ind=0; ind < length ; ind++) { - string = "For index = " + ind + "\n"; - string += "getLocalName <" + attributes.getLocalName(ind) - +">" + "\n"; - string += "getQName <" + attributes.getQName(ind) +">" + "\n"; - string += "getType <" + attributes.getType(ind) +">" + "\n"; - string += "getURI <" + attributes.getURI(ind) +">" + "\n"; - string += "getValue <" + attributes.getValue(ind) +">" + "\n"; - - bWriter.write( string, 0, string.length()); - bWriter.newLine(); - - String gotLocalName = attributes.getLocalName(ind); - String gotQName = attributes.getQName(ind); - String gotURI = attributes.getURI(ind); - - string ="Using localName, qname and uri pertaining to index = " - + ind; - bWriter.write( string, 0, string.length()); - bWriter.newLine(); - - string = "getIndex(qName) <" + attributes.getIndex(gotQName) - +">" + "\n"; - string += "getIndex(uri, localName) <" + - attributes.getIndex(gotURI, gotLocalName) +">" + "\n"; - - string += "getType(qName) <" + - attributes.getType(gotQName) +">" + "\n"; - string += "getType(uri, localName) <" + - attributes.getType(gotURI, gotLocalName) +">" + "\n"; - - string += "getValue(qName) <" + - attributes.getValue(gotQName) +">" + "\n"; - string += "getValue(uri, localName) <" + - attributes.getValue(gotURI, gotLocalName) +">" + "\n"; - - bWriter.write( string, 0, string.length()); - bWriter.newLine(); - } - bWriter.newLine(); - } catch(IOException ex){ - throw new SAXException(ex); - } - } - - /** - * Flush the stream and close the file. - * @throws IOException when writing or closing file failed. - */ - public void flushAndClose() throws IOException { - bWriter.flush(); - bWriter.close(); - } -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/xml/sax/ptests/MyAttrCHandler.java 2015-01-09 15:42:30.981201692 -0800 @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2003, 2015, 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 org.xml.sax.ptests; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * Simple attributes handler. + */ +public class MyAttrCHandler extends DefaultHandler { + /** + * FileWriter to write string to output file. + */ + private final BufferedWriter bWriter; + + /** + * Initiate FileWriter + * @param fileName output file name. + * @throws IOException + */ + public MyAttrCHandler(String fileName) throws IOException { + bWriter = new BufferedWriter(new FileWriter(fileName)); + } + + /** + * Write element content before start access every element. + * @throws org.xml.sax.SAXException + */ + @Override + public void startElement(String uri, String localName, + String qName, Attributes attributes) throws SAXException { + try { + String string = "uri <" + uri + "> localName <" + localName + + "> qName <" + qName + ">"; + + bWriter.write( string, 0, string.length()); + bWriter.newLine(); + + int length = attributes.getLength(); + string = "length: " + length; + + bWriter.write( string, 0, string.length()); + bWriter.newLine(); + + for (int ind=0; ind < length ; ind++) { + string = "For index = " + ind + "\n"; + string += "getLocalName <" + attributes.getLocalName(ind) + +">" + "\n"; + string += "getQName <" + attributes.getQName(ind) +">" + "\n"; + string += "getType <" + attributes.getType(ind) +">" + "\n"; + string += "getURI <" + attributes.getURI(ind) +">" + "\n"; + string += "getValue <" + attributes.getValue(ind) +">" + "\n"; + + bWriter.write( string, 0, string.length()); + bWriter.newLine(); + + String gotLocalName = attributes.getLocalName(ind); + String gotQName = attributes.getQName(ind); + String gotURI = attributes.getURI(ind); + + string ="Using localName, qname and uri pertaining to index = " + + ind; + bWriter.write( string, 0, string.length()); + bWriter.newLine(); + + string = "getIndex(qName) <" + attributes.getIndex(gotQName) + +">" + "\n"; + string += "getIndex(uri, localName) <" + + attributes.getIndex(gotURI, gotLocalName) +">" + "\n"; + + string += "getType(qName) <" + + attributes.getType(gotQName) +">" + "\n"; + string += "getType(uri, localName) <" + + attributes.getType(gotURI, gotLocalName) +">" + "\n"; + + string += "getValue(qName) <" + + attributes.getValue(gotQName) +">" + "\n"; + string += "getValue(uri, localName) <" + + attributes.getValue(gotURI, gotLocalName) +">" + "\n"; + + bWriter.write( string, 0, string.length()); + bWriter.newLine(); + } + bWriter.newLine(); + } catch(IOException ex){ + throw new SAXException(ex); + } + } + + /** + * Flush the stream and close the file. + * @throws IOException when writing or closing file failed. + */ + public void flushAndClose() throws IOException { + bWriter.flush(); + bWriter.close(); + } +} --- old/test/javax/xml/jaxp/functional/org/xml/sax/ptests/MyNSContentHandler.java 2015-01-09 15:42:31.453202429 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,208 +0,0 @@ -/* - * Copyright (c) 2014, 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 org.xml.sax.ptests; - -import org.xml.sax.helpers.DefaultHandler; -import org.xml.sax.helpers.LocatorImpl; -import org.xml.sax.Locator; -import org.xml.sax.Attributes; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.FileWriter; -import org.xml.sax.SAXException; - -class MyNSContentHandler extends DefaultHandler { - /** - * Prefix for written string. - */ - private final static String WRITE_ERROR = "bWrite error"; - /** - * FileWriter to write output file. - */ - private final BufferedWriter bWriter; - - /** - * Default locator. - */ - Locator locator = new LocatorImpl(); - - /** - * Initiate FileWrite. - * @param outputFileName file name of output file. - * @throws SAXException when open output file failed. - */ - public MyNSContentHandler(String outputFileName) throws SAXException { - try { - bWriter = new BufferedWriter(new FileWriter(outputFileName)); - } catch (IOException ex) { - throw new SAXException(ex); - } - } - - /** - * Write characters tag along with content of characters when meet - * characters event. - * @throws IOException error happen when writing file. - */ - @Override - public void characters(char[] ch, int start, int length) - throws SAXException { - String s = new String(ch, start, length); - println("characters...length is:" + s.length() + "\n" - + "<" + s + ">"); - } - - /** - * Write endDocument tag then flush the content and close the file when meet - * endDocument event. - * @throws IOException error happen when writing file or closing file. - */ - @Override - public void endDocument() throws SAXException { - try { - println("endDocument..."); - bWriter.flush(); - bWriter.close(); - } catch (IOException ex) { - throw new SAXException(WRITE_ERROR, ex); - } - } - - /** - * Write endElement tag with namespaceURI, localName, qName to the file when - * meet endElement event. - * @throws IOException error happen when writing file. - */ - @Override - public void endElement(String namespaceURI, String localName, String qName) - throws SAXException { - println("endElement...\n" + "namespaceURI: <" + namespaceURI - + "> localName: <" + localName + "> qName: <" + qName + ">"); - } - - /** - * Write endPrefixMapping tag along with prefix to the file when meet - * endPrefixMapping event. - * @throws IOException error happen when writing file. - */ - @Override - public void endPrefixMapping(String prefix) throws SAXException { - println("endPrefixMapping...\n" + "prefix: <" + prefix + ">"); - } - - /** - * Write ignorableWhitespace tag along with white spaces when meet - * ignorableWhitespace event. - * @throws IOException error happen when writing file. - */ - @Override - public void ignorableWhitespace(char[] ch, int start, int length) - throws SAXException { - String s = new String(ch, start, length); - println("ignorableWhitespace...\n" + s - + " ignorable white space string length: " + s.length()); - } - - /** - * Write processingInstruction tag along with target name and target data - * when meet processingInstruction event. - * @throws IOException error happen when writing file. - */ - @Override - public void processingInstruction(String target, String data) - throws SAXException { - println("processingInstruction...target:<" + target - + "> data: <" + data + ">"); - } - - /** - * Write setDocumentLocator tag when meet setDocumentLocator event. - */ - @Override - public void setDocumentLocator(Locator locator) { - try { - this.locator = locator; - println("setDocumentLocator..."); - } catch (SAXException ex) { - System.err.println(WRITE_ERROR + ex); - } - } - - /** - * Write skippedEntity tag along with entity name when meet skippedEntity - * event. - * @throws IOException error happen when writing file. - */ - @Override - public void skippedEntity(String name) throws SAXException { - println("skippedEntity...\n" + "name: <" + name + ">"); - } - - /** - * Write startDocument tag when meet startDocument event. - * @throws IOException error happen when writing file. - */ - @Override - public void startDocument() throws SAXException { - println("startDocument..."); - } - - /** - * Write startElement tag along with namespaceURI, localName, qName, number - * of attributes and line number when meet startElement event. - * @throws IOException error happen when writing file. - */ - @Override - public void startElement(String namespaceURI, String localName, - String qName, Attributes atts) throws SAXException { - println("startElement...\n" + "namespaceURI: <" + namespaceURI - + "> localName: <" + localName + "> qName: <" + qName - + "> Number of Attributes: <" + atts.getLength() - + "> Line# <" + locator.getLineNumber() + ">"); - } - - /** - * Write startPrefixMapping tag along with prefix and uri when meet - * startPrefixMapping event. - * @throws IOException error happen when writing file. - */ - @Override - public void startPrefixMapping(String prefix, String uri) - throws SAXException { - println("startPrefixMapping...\n" + "prefix: <" + prefix - + "> uri: <" + uri + ">"); - } - /** - * Write outString to output file. - * @param outString string to be written. - * @throws SAXException - */ - private void println(String outString) throws SAXException { - try { - bWriter.write( outString, 0, outString.length()); - bWriter.newLine(); - } catch (IOException ex) { - throw new SAXException(WRITE_ERROR, ex); - } - } -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/org/xml/sax/ptests/MyNSContentHandler.java 2015-01-09 15:42:31.340202253 -0800 @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2003, 2015, 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 org.xml.sax.ptests; + +import org.xml.sax.helpers.DefaultHandler; +import org.xml.sax.helpers.LocatorImpl; +import org.xml.sax.Locator; +import org.xml.sax.Attributes; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.FileWriter; +import org.xml.sax.SAXException; + +class MyNSContentHandler extends DefaultHandler implements AutoCloseable{ + /** + * Prefix for written string. + */ + private final static String WRITE_ERROR = "bWrite error"; + + /** + * FileWriter to write output file. + */ + private final BufferedWriter bWriter; + + /** + * Default locator. + */ + Locator locator = new LocatorImpl(); + + /** + * Initiate FileWrite. + * @param outputFileName file name of output file. + * @throws SAXException when open output file failed. + */ + public MyNSContentHandler(String outputFileName) throws SAXException { + try { + bWriter = new BufferedWriter(new FileWriter(outputFileName)); + } catch (IOException ex) { + throw new SAXException(ex); + } + } + + /** + * Write characters tag along with content of characters when meet + * characters event. + * @throws IOException error happen when writing file. + */ + @Override + public void characters(char[] ch, int start, int length) + throws SAXException { + String s = new String(ch, start, length); + println("characters...length is:" + s.length() + "\n" + + "<" + s + ">"); + } + + /** + * Write endDocument tag then flush the content and close the file when meet + * endDocument event. + * @throws IOException error happen when writing file or closing file. + */ + @Override + public void endDocument() throws SAXException { + try { + println("endDocument..."); + bWriter.flush(); + bWriter.close(); + } catch (IOException ex) { + throw new SAXException(WRITE_ERROR, ex); + } + } + + /** + * Write endElement tag with namespaceURI, localName, qName to the file when + * meet endElement event. + * @throws IOException error happen when writing file. + */ + @Override + public void endElement(String namespaceURI, String localName, String qName) + throws SAXException { + println("endElement...\n" + "namespaceURI: <" + namespaceURI + + "> localName: <" + localName + "> qName: <" + qName + ">"); + } + + /** + * Write endPrefixMapping tag along with prefix to the file when meet + * endPrefixMapping event. + * @throws IOException error happen when writing file. + */ + @Override + public void endPrefixMapping(String prefix) throws SAXException { + println("endPrefixMapping...\n" + "prefix: <" + prefix + ">"); + } + + /** + * Write ignorableWhitespace tag along with white spaces when meet + * ignorableWhitespace event. + * @throws IOException error happen when writing file. + */ + @Override + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException { + String s = new String(ch, start, length); + println("ignorableWhitespace...\n" + s + + " ignorable white space string length: " + s.length()); + } + + /** + * Write processingInstruction tag along with target name and target data + * when meet processingInstruction event. + * @throws IOException error happen when writing file. + */ + @Override + public void processingInstruction(String target, String data) + throws SAXException { + println("processingInstruction...target:<" + target + + "> data: <" + data + ">"); + } + + /** + * Write setDocumentLocator tag when meet setDocumentLocator event. + */ + @Override + public void setDocumentLocator(Locator locator) { + try { + this.locator = locator; + println("setDocumentLocator..."); + } catch (SAXException ex) { + System.err.println(WRITE_ERROR + ex); + } + } + + /** + * Write skippedEntity tag along with entity name when meet skippedEntity + * event. + * @throws IOException error happen when writing file. + */ + @Override + public void skippedEntity(String name) throws SAXException { + println("skippedEntity...\n" + "name: <" + name + ">"); + } + + /** + * Write startDocument tag when meet startDocument event. + * @throws IOException error happen when writing file. + */ + @Override + public void startDocument() throws SAXException { + println("startDocument..."); + } + + /** + * Write startElement tag along with namespaceURI, localName, qName, number + * of attributes and line number when meet startElement event. + * @throws IOException error happen when writing file. + */ + @Override + public void startElement(String namespaceURI, String localName, + String qName, Attributes atts) throws SAXException { + println("startElement...\n" + "namespaceURI: <" + namespaceURI + + "> localName: <" + localName + "> qName: <" + qName + + "> Number of Attributes: <" + atts.getLength() + + "> Line# <" + locator.getLineNumber() + ">"); + } + + /** + * Write startPrefixMapping tag along with prefix and uri when meet + * startPrefixMapping event. + * @throws IOException error happen when writing file. + */ + @Override + public void startPrefixMapping(String prefix, String uri) + throws SAXException { + println("startPrefixMapping...\n" + "prefix: <" + prefix + + "> uri: <" + uri + ">"); + } + /** + * Write outString to output file. + * @param outString string to be written. + * @throws SAXException + */ + private void println(String outString) throws SAXException { + try { + bWriter.write( outString, 0, outString.length()); + bWriter.newLine(); + } catch (IOException ex) { + throw new SAXException(WRITE_ERROR, ex); + } + } + + /** + * Close writer if it's initiated. + * @throws IOException if any I/O error when close writer. + */ + @Override + public void close() throws IOException { + if (bWriter != null) + bWriter.close(); + } +} --- old/test/javax/xml/jaxp/functional/test/auctionportal/MyDOMErrorHandler.java 2015-01-09 15:42:31.833203023 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.auctionportal; - -import org.w3c.dom.DOMErrorHandler; -import org.w3c.dom.DOMError; - -/** - * Error handler for recording DOM processing error. - */ -public class MyDOMErrorHandler implements DOMErrorHandler { - /** - * flag shows if there is any error. - */ - private volatile boolean errorOccured = false; - - /** - * Set errorOcurred to true when an error occurs. - * @param error The error object that describes the error. This object - * may be reused by the DOM implementation across multiple calls to - * the handleError method. - * @return true that processing may continue depending on. - */ - @Override - public boolean handleError (DOMError error) { - System.err.println( "ERROR" + error.getMessage()); - System.err.println( "ERROR" + error.getRelatedData()); - errorOccured = true; - return true; - } - - /** - * Showing if any error was handled. - * @return true if there is one or more error. - * false no error occurs. - */ - public boolean isError() { - return errorOccured; - } -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/test/auctionportal/MyDOMErrorHandler.java 2015-01-09 15:42:31.720202846 -0800 @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2003, 2015, 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 test.auctionportal; + +import org.w3c.dom.DOMErrorHandler; +import org.w3c.dom.DOMError; + +/** + * Error handler for recording DOM processing error. + */ +public class MyDOMErrorHandler implements DOMErrorHandler { + /** + * flag shows if there is any error. + */ + private volatile boolean errorOccured = false; + + /** + * Set errorOcurred to true when an error occurs. + * @param error The error object that describes the error. This object + * may be reused by the DOM implementation across multiple calls to + * the handleError method. + * @return true that processing may continue depending on. + */ + @Override + public boolean handleError (DOMError error) { + System.err.println( "ERROR" + error.getMessage()); + System.err.println( "ERROR" + error.getRelatedData()); + errorOccured = true; + return true; + } + + /** + * Showing if any error was handled. + * @return true if there is one or more error. + * false no error occurs. + */ + public boolean isError() { + return errorOccured; + } +} --- old/test/javax/xml/jaxp/functional/test/auctionportal/MyDOMOutput.java 2015-01-09 15:42:32.208203609 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.auctionportal; - -import org.w3c.dom.ls.LSOutput; -import java.io.OutputStream; -import java.io.Writer; - -/** - * A Thread-safe LS output destination for DOM processing. LSOutput objects - * belong to the application. The DOM implementation will never modify them - * (though it may make copies and modify the copies, if necessary). - */ -public class MyDOMOutput implements LSOutput { - /** - * An attribute of a language and binding dependent type that represents a - * writable stream of bytes. - */ - private OutputStream bytestream; - - /** - * character encoding to use for the output. - */ - private String encoding; - - /** - * The system identifier. - */ - private String sysId; - - /** - * Writable stream to which 16-bit units can be output. - */ - private Writer writer; - - /** - * An attribute of a language and binding dependent type that represents a - * writable stream of bytes. - * - * @return a writable stream. - */ - @Override - public OutputStream getByteStream() { - return bytestream; - } - - /** - * An attribute of a language and binding dependent type that represents a - * writable stream to which 16-bit units can be output. - * - * @return writable stream instance. - */ - @Override - public Writer getCharacterStream() { - return writer; - } - - /** - * The character encoding to use for the output. - * - * @return the character encoding. - */ - @Override - public String getEncoding() { - return encoding; - } - - /** - * The system identifier for this output destination. - * - * @return system identifier. - */ - @Override - public String getSystemId() { - return sysId; - } - - /** - * Set writable stream of bytes. - * - * @param bs OutputStream instance - */ - @Override - public void setByteStream(OutputStream bs) { - bytestream = bs; - } - - /** - * Set 16 bits unit writable stream. - * - * @param bs a Writer instance - */ - @Override - public void setCharacterStream(Writer cs) { - writer = cs; - } - - /** - * Set character encoding to use for the output. - * - * @param encoding encoding set to the output - */ - @Override - public void setEncoding(String encoding) { - this.encoding = encoding; - } - - /** - * Set the system identifier for the output. - * - * @param sysId system identifier string. - */ - @Override - public void setSystemId(String sysId) { - this.sysId = sysId; - } -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/test/auctionportal/MyDOMOutput.java 2015-01-09 15:42:32.088203421 -0800 @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2003, 2015, 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 test.auctionportal; + +import org.w3c.dom.ls.LSOutput; +import java.io.OutputStream; +import java.io.Writer; + +/** + * A Thread-safe LS output destination for DOM processing. LSOutput objects + * belong to the application. The DOM implementation will never modify them + * (though it may make copies and modify the copies, if necessary). + */ +public class MyDOMOutput implements LSOutput { + /** + * An attribute of a language and binding dependent type that represents a + * writable stream of bytes. + */ + private OutputStream bytestream; + + /** + * character encoding to use for the output. + */ + private String encoding; + + /** + * The system identifier. + */ + private String sysId; + + /** + * Writable stream to which 16-bit units can be output. + */ + private Writer writer; + + /** + * An attribute of a language and binding dependent type that represents a + * writable stream of bytes. + * + * @return a writable stream. + */ + @Override + public OutputStream getByteStream() { + return bytestream; + } + + /** + * An attribute of a language and binding dependent type that represents a + * writable stream to which 16-bit units can be output. + * + * @return writable stream instance. + */ + @Override + public Writer getCharacterStream() { + return writer; + } + + /** + * The character encoding to use for the output. + * + * @return the character encoding. + */ + @Override + public String getEncoding() { + return encoding; + } + + /** + * The system identifier for this output destination. + * + * @return system identifier. + */ + @Override + public String getSystemId() { + return sysId; + } + + /** + * Set writable stream of bytes. + * + * @param bs OutputStream instance + */ + @Override + public void setByteStream(OutputStream bs) { + bytestream = bs; + } + + /** + * Set 16 bits unit writable stream. + * + * @param cs a Writer instance + */ + @Override + public void setCharacterStream(Writer cs) { + writer = cs; + } + + /** + * Set character encoding to use for the output. + * + * @param encoding encoding set to the output + */ + @Override + public void setEncoding(String encoding) { + this.encoding = encoding; + } + + /** + * Set the system identifier for the output. + * + * @param sysId system identifier string. + */ + @Override + public void setSystemId(String sysId) { + this.sysId = sysId; + } +} --- old/test/javax/xml/jaxp/functional/test/auctionportal/MyErrorHandler.java 2015-01-09 15:42:32.646204293 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.auctionportal; - -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * ErrorHandler for error handling. Set state if any method in error, warning - * or fatalError was called. - */ -public final class MyErrorHandler extends DefaultHandler { - /** - * Enumeration for ErrorHandler's state. - */ - private enum STATE { ERROR, FATAL, WARNING, NORMAL}; - - /** - * Set state as normal by default. - */ - private volatile STATE state = STATE.NORMAL; - - /** - * Keep exception for further investigation. - */ - private volatile SAXParseException exception; - - /** - * Save exception and set state to ERROR. - * @param e exception wrap error. - */ - @Override - public void error (SAXParseException e) { - state = STATE.ERROR; - exception = e; - } - - /** - * Save exception and set state to FATAL. - * @param e exception wrap error. - */ - @Override - public void fatalError (SAXParseException e) { - state = STATE.FATAL; - exception = e; - } - - /** - * Save exception and set state to WARNING. - * @param e exception wrap error. - */ - @Override - public void warning (SAXParseException e) { - state = STATE.WARNING; - exception = e; - } - - /** - * return ErrorHandle's state . - * @return true No error, fatalError and warning. - * false there is any error, fatalError or warning in processing. - */ - public boolean isAnyError() { - if (state != STATE.NORMAL) - System.out.println(exception); - return state != STATE.NORMAL; - } - - /** - * return whether fatalError is the only error. - * @return true fatalError is the only error. - * false there is no error, or other error besides fatalError. - */ - public boolean isFatalError() { - if (state == STATE.FATAL) - System.out.println(exception); - return state == STATE.FATAL; - } - -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/test/auctionportal/MyErrorHandler.java 2015-01-09 15:42:32.466204012 -0800 @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2003, 2015, 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 test.auctionportal; + +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * ErrorHandler for error handling. Set state if any method in error, warning + * or fatalError was called. + */ +public final class MyErrorHandler extends DefaultHandler { + /** + * Enumeration for ErrorHandler's state. + */ + private enum STATE { ERROR, FATAL, WARNING, NORMAL}; + + /** + * Set state as normal by default. + */ + private volatile STATE state = STATE.NORMAL; + + /** + * Keep exception for further investigation. + */ + private volatile SAXParseException exception; + + /** + * Save exception and set state to ERROR. + * @param e exception wrap error. + */ + @Override + public void error (SAXParseException e) { + state = STATE.ERROR; + exception = e; + } + + /** + * Save exception and set state to FATAL. + * @param e exception wrap error. + */ + @Override + public void fatalError (SAXParseException e) { + state = STATE.FATAL; + exception = e; + } + + /** + * Save exception and set state to WARNING. + * @param e exception wrap error. + */ + @Override + public void warning (SAXParseException e) { + state = STATE.WARNING; + exception = e; + } + + /** + * return ErrorHandle's state . + * @return true No error, fatalError and warning. + * false there is any error, fatalError or warning in processing. + */ + public boolean isAnyError() { + if (state != STATE.NORMAL) + System.out.println(exception); + return state != STATE.NORMAL; + } + + /** + * return whether fatalError is the only error. + * @return true fatalError is the only error. + * false there is no error, or other error besides fatalError. + */ + public boolean isFatalError() { + if (state == STATE.FATAL) + System.out.println(exception); + return state == STATE.FATAL; + } + +} --- old/test/javax/xml/jaxp/functional/test/auctionportal/XInclHandler.java 2015-01-09 15:42:33.046204918 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,382 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.auctionportal; - -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.util.stream.Collectors; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.ext.LexicalHandler; -import org.xml.sax.helpers.DefaultHandler; - -/** - * A SAX2 event handlers. - * This SAX2 ContentHandler receives callback event then print whole document - * that is parsed. - */ -public class XInclHandler extends DefaultHandler implements LexicalHandler { - /** - * Print writer. - */ - private final PrintWriter fOut; - - /** - * Canonical output. - */ - private volatile boolean fCanonical; - - /** - * Element depth. - */ - private volatile int fElementDepth; - - /** - * Sets whether output is canonical. - */ - public void setCanonical(boolean canonical) { - fCanonical = canonical; - } - - /** - * Sets the output stream for printing. - * @param stream OutputStream for message output. - * @param encoding File encoding for message output. - */ - public XInclHandler(OutputStream stream, String encoding) - throws UnsupportedEncodingException { - // At least set one encoding. - if (encoding == null) { - encoding = "UTF8"; - } - - fOut = new PrintWriter(new OutputStreamWriter(stream, encoding), false); - } - - /** - * Receive notification of the beginning of the document. Write the start - * document tag if it's not canonical mode. - * @exception org.xml.sax.SAXException Any SAX exception, possibly - * wrapping another exception. - */ - @Override - public void startDocument() throws SAXException { - fElementDepth = 0; - - if (!fCanonical) { - writeFlush(""); - } - } - - /** - * Receive notification of a processing instruction. - * @param target The processing instruction target. - * @param data The processing instruction data, or null if - * none is supplied. - * @exception org.xml.sax.SAXException Any SAX exception, possibly - * wrapping another exception. - */ - @Override - public void processingInstruction (String target, String data) - throws SAXException { - if (fElementDepth > 0) { - StringBuilder instruction = new StringBuilder(" 0) { - instruction.append(' ').append(data); - } - instruction.append("?>"); - writeFlush(instruction.toString()); - } - } - - /** - * Receive notification of the start of an element then write the normalized - * output to the file. - * @param uri The Namespace URI, or the empty string if the - * element has no Namespace URI or if Namespace - * processing is not being performed. - * @param localName The local name (without prefix), or the - * empty string if Namespace processing is not being - * performed. - * @param qName The qualified name (with prefix), or the - * empty string if qualified names are not available. - * @param attributes The attributes attached to the element. If - * there are no attributes, it shall be an empty - * Attributes object. - */ - @Override - public void startElement(String uri, String local, String raw, - Attributes attrs) throws SAXException { - fElementDepth++; - StringBuilder start = new StringBuilder().append('<').append(raw); - if (attrs != null) { - for (int i = 0; i < attrs.getLength(); i++) { - start.append(' ').append(attrs.getQName(i)).append("=\""). - append(normalizeAndPrint(attrs.getValue(i))).append('"'); - } - } - start.append('>'); - writeFlush(start.toString()); - } - - /** - * Receive notification of character data inside an element and write - * normalized characters to file. - * @param ch The characters. - * @param start The start position in the character array. - * @param length The number of characters to use from the - * character array. - * @exception org.xml.sax.SAXException Any SAX exception, possibly - * wrapping another exception. - */ - @Override - public void characters(char ch[], int start, int length) - throws SAXException { - writeFlush(normalizeAndPrint(ch, start, length)); - } - - /** - * Receiving notification of ignorable whitespace in element content and - * writing normalized ignorable characters to file. - * @param ch The characters. - * @param start The start position in the character array. - * @param length The number of characters to use from the - * character array. - * @exception org.xml.sax.SAXException Any SAX exception, possibly - * wrapping another exception. - */ - @Override - public void ignorableWhitespace(char ch[], int start, int length) - throws SAXException { - characters(ch, start, length); - } - - /** - * Receive notification of the end of an element and print end element. - * - * @param uri The Namespace URI, or the empty string if the - * element has no Namespace URI or if Namespace - * processing is not being performed. - * @param localName The local name (without prefix), or the - * empty string if Namespace processing is not being - * performed. - * @param qName The qualified name (with prefix), or the - * empty string if qualified names are not available. - */ - @Override - public void endElement(String uri, String local, String raw) - throws SAXException { - fElementDepth--; - writeFlush(""); - } - - /** - * Receive notification of a parser warning and print it out. - * @param e The warning information encoded as an exception. - * @exception org.xml.sax.SAXException Any SAX exception, possibly - * wrapping another exception. - */ - @Override - public void warning(SAXParseException ex) throws SAXException { - printError("Warning", ex); - } - - /** - * Receive notification of a parser error and print it out. - * @param e The error information encoded as an exception. - * @exception org.xml.sax.SAXException Any SAX exception, possibly - * wrapping another exception. - - */ - @Override - public void error(SAXParseException ex) throws SAXException { - printError("Error", ex); - } - - /** - * Receive notification of a parser fatal error. Throw out fatal error - * following print fatal error message. - * @param e The fatal error information encoded as an exception. - * @exception org.xml.sax.SAXException Any SAX exception, possibly - * wrapping another exception. - - */ - @Override - public void fatalError(SAXParseException ex) throws SAXException { - printError("Fatal Error", ex); - throw ex; - } - - /** - * Do nothing on start DTD. - * @param name The document type name. - * @param publicId The declared public identifier for the - * external DTD subset, or null if none was declared. - * @param systemId The declared system identifier for the - * external DTD subset, or null if none was declared. - * (Note that this is not resolved against the document - * base URI.) - * @exception SAXException The application may raise an - * exception. - */ - @Override - public void startDTD(String name, String publicId, String systemId) - throws SAXException { - } - - /** - * Do nothing on end DTD. - * @exception SAXException The application may raise an exception. - */ - @Override - public void endDTD() throws SAXException { - } - - /** - * Do nothing on start entity. - * @param name The name of the entity. If it is a parameter - * entity, the name will begin with '%', and if it is the - * external DTD subset, it will be "[dtd]". - * @exception SAXException The application may raise an exception. - */ - @Override - public void startEntity(String name) throws SAXException { - } - - /** - * Do nothing on end entity. - * @param name The name of the entity. If it is a parameter - * entity, the name will begin with '%', and if it is the - * external DTD subset, it will be "[dtd]". - * @exception SAXException The application may raise an exception. - */ - @Override - public void endEntity(String name) throws SAXException { - } - - /** - * Do nothing on start CDATA section. - * @exception SAXException The application may raise an exception. - */ - @Override - public void startCDATA() throws SAXException { - } - - /** - * Do nothing on end CDATA section. - * @exception SAXException The application may raise an exception. - */ - @Override - public void endCDATA() throws SAXException { - } - - /** - * Report an normalized XML comment when receive a comment in the document. - * - * @param ch An array holding the characters in the comment. - * @param start The starting position in the array. - * @param length The number of characters to use from the array. - * @exception SAXException The application may raise an exception. - */ - @Override - public void comment(char ch[], int start, int length) throws SAXException { - if (!fCanonical && fElementDepth > 0) { - writeFlush(""); - } - } - - /** - * Normalizes and prints the given string. - * @param s String to be normalized - */ - private String normalizeAndPrint(String s) { - return s.chars().mapToObj(c -> normalizeAndPrint((char)c)). - collect(Collectors.joining()); - } - - /** - * Normalizes and prints the given array of characters. - * @param ch The characters to be normalized. - * @param start The start position in the character array. - * @param length The number of characters to use from the - * character array. - */ - private String normalizeAndPrint(char[] ch, int offset, int length) { - return normalizeAndPrint(new String(ch, offset, length)); - } - - /** - * Normalizes given character. - * @param c char to be normalized. - */ - private String normalizeAndPrint(char c) { - switch (c) { - case '<': - return "<"; - case '>': - return ">"; - case '&': - return "&"; - case '"': - return """; - case '\r': - case '\n': - return fCanonical ? "&#" + Integer.toString(c) + ";" : String.valueOf(c); - default: - return String.valueOf(c); - } - } - - /** - * Prints the error message. - * @param type error type - * @param ex exception that need to be printed - */ - private void printError(String type, SAXParseException ex) { - System.err.print("[" + type + "] "); - String systemId = ex.getSystemId(); - if (systemId != null) { - int index = systemId.lastIndexOf('/'); - if (index != -1) - systemId = systemId.substring(index + 1); - System.err.print(systemId); - } - System.err.print(':' + ex.getLineNumber()); - System.err.print(':' + ex.getColumnNumber()); - System.err.println(": " + ex.getMessage()); - System.err.flush(); - } - - /** - * Write out and flush. - * @param out string to be written. - */ - private void writeFlush(String out) { - fOut.print(out); - fOut.flush(); - } -} --- /dev/null 2014-09-08 10:45:56.830930409 -0700 +++ new/test/javax/xml/jaxp/libs/test/auctionportal/XInclHandler.java 2015-01-09 15:42:32.928204733 -0800 @@ -0,0 +1,389 @@ +/* + * Copyright (c) 2003, 2015, 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 test.auctionportal; + +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.util.stream.Collectors; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.ext.LexicalHandler; +import org.xml.sax.helpers.DefaultHandler; + +/** + * A SAX2 event handlers. + * This SAX2 ContentHandler receives callback event then print whole document + * that is parsed. + */ +public class XInclHandler extends DefaultHandler implements LexicalHandler { + /** + * Print writer. + */ + private final PrintWriter fOut; + + /** + * Canonical output. + */ + private volatile boolean fCanonical; + + /** + * Element depth. + */ + private volatile int fElementDepth; + + /** + * Sets whether output is canonical. + * + * @param canonical if the output is canonical format. + */ + public void setCanonical(boolean canonical) { + fCanonical = canonical; + } + + /** + * Sets the output stream for printing. + * @param stream OutputStream for message output. + * @param encoding File encoding for message output. + * @throws UnsupportedEncodingException if given encoding is an unsupported + * encoding name or invalid encoding name. + */ + public XInclHandler(OutputStream stream, String encoding) + throws UnsupportedEncodingException { + // At least set one encoding. + if (encoding == null) { + encoding = "UTF8"; + } + + fOut = new PrintWriter(new OutputStreamWriter(stream, encoding), false); + } + + /** + * Receive notification of the beginning of the document. Write the start + * document tag if it's not canonical mode. + * @exception org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + */ + @Override + public void startDocument() throws SAXException { + fElementDepth = 0; + + if (!fCanonical) { + writeFlush(""); + } + } + + /** + * Receive notification of a processing instruction. + * @param target The processing instruction target. + * @param data The processing instruction data, or null if + * none is supplied. + * @exception SAXException Any SAX exception, possibly wrapping another + * exception. + */ + @Override + public void processingInstruction (String target, String data) + throws SAXException { + if (fElementDepth > 0) { + StringBuilder instruction = new StringBuilder(" 0) { + instruction.append(' ').append(data); + } + instruction.append("?>"); + writeFlush(instruction.toString()); + } + } + + /** + * Receive notification of the start of an element then write the normalized + * output to the file. + * @param uri The Namespace URI, or the empty string if the + * element has no Namespace URI or if Namespace + * processing is not being performed. + * @param local The local name (without prefix), or the + * empty string if Namespace processing is not being + * performed. + * @param raw The qualified name (with prefix), or the + * empty string if qualified names are not available. + * @param attrs The attributes attached to the element. If + * there are no attributes, it shall be an empty + * Attributes object. + * @throws SAXException Any SAX exception, possibly wrapping another + * exception. + */ + @Override + public void startElement(String uri, String local, String raw, + Attributes attrs) throws SAXException { + fElementDepth++; + StringBuilder start = new StringBuilder().append('<').append(raw); + if (attrs != null) { + for (int i = 0; i < attrs.getLength(); i++) { + start.append(' ').append(attrs.getQName(i)).append("=\""). + append(normalizeAndPrint(attrs.getValue(i))).append('"'); + } + } + start.append('>'); + writeFlush(start.toString()); + } + + /** + * Receive notification of character data inside an element and write + * normalized characters to file. + * @param ch The characters. + * @param start The start position in the character array. + * @param length The number of characters to use from the + * character array. + * @exception org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + */ + @Override + public void characters(char ch[], int start, int length) + throws SAXException { + writeFlush(normalizeAndPrint(ch, start, length)); + } + + /** + * Receiving notification of ignorable whitespace in element content and + * writing normalized ignorable characters to file. + * @param ch The characters. + * @param start The start position in the character array. + * @param length The number of characters to use from the + * character array. + * @exception org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + */ + @Override + public void ignorableWhitespace(char ch[], int start, int length) + throws SAXException { + characters(ch, start, length); + } + + /** + * Receive notification of the end of an element and print end element. + * + * @param uri The Namespace URI, or the empty string if the + * element has no Namespace URI or if Namespace + * processing is not being performed. + * @param local The local name (without prefix), or the + * empty string if Namespace processing is not being + * performed. + * @param raw The qualified name (with prefix), or the + * empty string if qualified names are not available. + * @throws org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + */ + @Override + public void endElement(String uri, String local, String raw) + throws SAXException { + fElementDepth--; + writeFlush(""); + } + + /** + * Receive notification of a parser warning and print it out. + * @param ex The warning information encoded as an exception. + * @exception org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + */ + @Override + public void warning(SAXParseException ex) throws SAXException { + printError("Warning", ex); + } + + /** + * Receive notification of a parser error and print it out. + * @param ex The error information encoded as an exception. + * @exception org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + */ + @Override + public void error(SAXParseException ex) throws SAXException { + printError("Error", ex); + } + + /** + * Receive notification of a parser fatal error. Throw out fatal error + * following print fatal error message. + * @param ex The fatal error information encoded as an exception. + * @exception org.xml.sax.SAXException Any SAX exception, possibly + * wrapping another exception. + + */ + @Override + public void fatalError(SAXParseException ex) throws SAXException { + printError("Fatal Error", ex); + throw ex; + } + + /** + * Do nothing on start DTD. + * @param name The document type name. + * @param publicId The declared public identifier for the + * external DTD subset, or null if none was declared. + * @param systemId The declared system identifier for the + * external DTD subset, or null if none was declared. + * (Note that this is not resolved against the document + * base URI.) + * @exception SAXException The application may raise an + * exception. + */ + @Override + public void startDTD(String name, String publicId, String systemId) + throws SAXException { + } + + /** + * Do nothing on end DTD. + * @exception SAXException The application may raise an exception. + */ + @Override + public void endDTD() throws SAXException { + } + + /** + * Do nothing on start entity. + * @param name The name of the entity. If it is a parameter + * entity, the name will begin with '%', and if it is the + * external DTD subset, it will be "[dtd]". + * @exception SAXException The application may raise an exception. + */ + @Override + public void startEntity(String name) throws SAXException { + } + + /** + * Do nothing on end entity. + * @param name The name of the entity. If it is a parameter + * entity, the name will begin with '%', and if it is the + * external DTD subset, it will be "[dtd]". + * @exception SAXException The application may raise an exception. + */ + @Override + public void endEntity(String name) throws SAXException { + } + + /** + * Do nothing on start CDATA section. + * @exception SAXException The application may raise an exception. + */ + @Override + public void startCDATA() throws SAXException { + } + + /** + * Do nothing on end CDATA section. + * @exception SAXException The application may raise an exception. + */ + @Override + public void endCDATA() throws SAXException { + } + + /** + * Report an normalized XML comment when receive a comment in the document. + * + * @param ch An array holding the characters in the comment. + * @param start The starting position in the array. + * @param length The number of characters to use from the array. + * @exception SAXException The application may raise an exception. + */ + @Override + public void comment(char ch[], int start, int length) throws SAXException { + if (!fCanonical && fElementDepth > 0) { + writeFlush(""); + } + } + + /** + * Normalizes and prints the given string. + * @param s String to be normalized + */ + private String normalizeAndPrint(String s) { + return s.chars().mapToObj(c -> normalizeAndPrint((char)c)). + collect(Collectors.joining()); + } + + /** + * Normalizes and prints the given array of characters. + * @param ch The characters to be normalized. + * @param start The start position in the character array. + * @param length The number of characters to use from the + * character array. + */ + private String normalizeAndPrint(char[] ch, int offset, int length) { + return normalizeAndPrint(new String(ch, offset, length)); + } + + /** + * Normalizes given character. + * @param c char to be normalized. + */ + private String normalizeAndPrint(char c) { + switch (c) { + case '<': + return "<"; + case '>': + return ">"; + case '&': + return "&"; + case '"': + return """; + case '\r': + case '\n': + return fCanonical ? "&#" + Integer.toString(c) + ";" : String.valueOf(c); + default: + return String.valueOf(c); + } + } + + /** + * Prints the error message. + * @param type error type + * @param ex exception that need to be printed + */ + private void printError(String type, SAXParseException ex) { + System.err.print("[" + type + "] "); + String systemId = ex.getSystemId(); + if (systemId != null) { + int index = systemId.lastIndexOf('/'); + if (index != -1) + systemId = systemId.substring(index + 1); + System.err.print(systemId); + } + System.err.print(':' + ex.getLineNumber()); + System.err.print(':' + ex.getColumnNumber()); + System.err.println(": " + ex.getMessage()); + System.err.flush(); + } + + /** + * Write out and flush. + * @param out string to be written. + */ + private void writeFlush(String out) { + fOut.print(out); + fOut.flush(); + } +} --- old/test/javax/xml/jaxp/functional/javax/xml/parsers/ptests/DocumentBuilderFactory02.java 2015-01-09 15:42:33.397205466 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.parsers.ptests; - -import static jaxp.library.JAXPTestUtilities.FILE_SEP; -import static jaxp.library.JAXPTestUtilities.USER_DIR; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.sax.SAXResult; - -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; - -/** - * This tests the setIgnoringElementWhitespace and setIgnoringComments of - * DocumentBuilderFactory - */ -public class DocumentBuilderFactory02 { - - /** - * This testcase tests for the isIgnoringElementContentWhitespace and the - * setIgnoringElementContentWhitespace. The xml file has all kinds of - * whitespace,tab and newline characters, it uses the MyNSContentHandler - * which does not invoke the characters callback when this - * setIgnoringElementContentWhitespace is set to true. - */ - @Test - public void testCheckElementContentWhitespace() { - try { - String goldFile = TestUtils.GOLDEN_DIR + FILE_SEP + "dbfactory02GF.out"; - String outputFile = USER_DIR + FILE_SEP + "dbfactory02.out"; - MyErrorHandler eh = MyErrorHandler.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setValidating(true); - assertFalse(dbf.isIgnoringElementContentWhitespace()); - dbf.setIgnoringElementContentWhitespace(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(eh); - Document doc = db.parse(new File(TestUtils.XML_DIR, "DocumentBuilderFactory06.xml")); - assertFalse(eh.errorOccured); - DOMSource domSource = new DOMSource(doc); - TransformerFactory tfactory = TransformerFactory.newInstance(); - Transformer transformer = tfactory.newTransformer(); - SAXResult saxResult = new SAXResult(); - saxResult.setHandler(MyCHandler.newInstance(new File(outputFile))); - transformer.transform(domSource, saxResult); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) { - failUnexpected(e); - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest002.java 2015-01-09 15:42:33.594205774 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXSource; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerhandler() method which takes SAXSource as argument can - * be set to XMLReader. - */ -public class SAXTFactoryTest002 { - /** - * SAXTFactory.newTransformerhandler() method which takes SAXSource as - * argument can be set to XMLReader. SAXSource has input XML file as its - * input source. XMLReader has a content handler which write out the result - * to output file. Test verifies output file is same as golden file. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf002.out"; - String goldFile = GOLDEN_DIR + "saxtf002GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile); - FileInputStream fis = new FileInputStream(xsltFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory) TransformerFactory.newInstance(); - SAXSource ss = new SAXSource(); - ss.setInputSource(new InputSource(fis)); - - TransformerHandler handler = saxTFactory.newTransformerHandler(ss); - Result result = new StreamResult(fos); - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest003.java 2015-01-09 15:42:33.790206080 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerhandler() method which takes DOMSource as argument can - * be set to XMLReader. - */ -public class SAXTFactoryTest003 { - /** - * Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is - * namespace awareness, DocumentBuilder parse xslt file as DOMSource. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf003.out"; - String goldFile = GOLDEN_DIR + "saxtf003GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new File(xsltFile)); - Node node = (Node)document; - DOMSource domSource= new DOMSource(node); - - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - TransformerHandler handler = - saxTFactory.newTransformerHandler(domSource); - Result result = new StreamResult(fos); - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (TransformerConfigurationException | ParserConfigurationException - | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest004.java 2015-01-09 15:42:33.986206386 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.File; -import java.io.IOException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; - -/* - * TransformerConfigurationException expected when there is relative URI is used - * in citiesinclude.xsl file - */ -public class SAXTFactoryTest004 { - /** - * Negative test for newTransformerHandler when relative URI is in XML file. - * @throws TransformerConfigurationException If for some reason the - * TransformerHandler can not be created. - */ - @Test(expectedExceptions = TransformerConfigurationException.class) - public void transformerHandlerTest01() throws TransformerConfigurationException { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new File(XML_DIR + "citiesinclude.xsl")); - DOMSource domSource= new DOMSource(document); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - saxTFactory.newTransformerHandler(domSource); - } catch (ParserConfigurationException | IOException | SAXException ex) { - failUnexpected(ex); - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest005.java 2015-01-09 15:42:34.185206697 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test SAXSource API when relative URI is used in xsl file and SystemId was set - */ -public class SAXTFactoryTest005 { - /** - * Unit test for XMLReader parsing when relative URI is used in xsl file and - * SystemId was set. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf005.out"; - String goldFile = GOLDEN_DIR + "saxtf005GF.out"; - String xsltFile = XML_DIR + "citiesinclude.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new File(xsltFile)); - Node node = (Node)document; - DOMSource domSource= new DOMSource(node); - - domSource.setSystemId("file:///" + XML_DIR); - - TransformerHandler handler = - saxTFactory.newTransformerHandler(domSource); - Result result = new StreamResult(fos); - - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (TransformerConfigurationException | ParserConfigurationException - | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest006.java 2015-01-09 15:42:34.384207008 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerHandler with a DOMSource and StreamResult set. - */ -public class SAXTFactoryTest006 extends TransformerTestConst{ - /** - * Unit test newTransformerHandler with a DOMSource. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf006.out"; - String goldFile = GOLDEN_DIR + "saxtf006GF.out"; - String xsltFile = XML_DIR + "citiesinclude.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Node node = (Node)docBuilder.parse(new File(xsltFile)); - - DOMSource domSource = new DOMSource(node, "file:///" + XML_DIR); - TransformerHandler handler = - saxTFactory.newTransformerHandler(domSource); - - Result result = new StreamResult(fos); - handler.setResult(result); - reader.setContentHandler(handler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (TransformerConfigurationException | ParserConfigurationException - | SAXException | IOException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest008.java 2015-01-09 15:42:34.588207327 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TemplatesHandler; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerHandler with a Template Handler. - */ -public class SAXTFactoryTest008 { - /** - * Test newTransformerHandler with a Template Handler. - */ - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf008.out"; - String goldFile = GOLDEN_DIR + "saxtf008GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - - TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); - reader.setContentHandler(thandler); - reader.parse(xsltFile); - TransformerHandler tfhandler - = saxTFactory.newTransformerHandler(thandler.getTemplates()); - - Result result = new StreamResult(fos); - tfhandler.setResult(result); - - reader.setContentHandler(tfhandler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } - -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest009.java 2015-01-09 15:42:34.787207638 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.Result; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TemplatesHandler; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test newTransformerHandler with a Template Handler along with a relative URI - * in the xslt file. - */ -public class SAXTFactoryTest009 { - /** - * Test newTransformerHandler with a Template Handler along with a relative - * URI in the xslt file. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf009.out"; - String goldFile = GOLDEN_DIR + "saxtf009GF.out"; - String xsltFile = XML_DIR + "citiesinclude.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try (FileOutputStream fos = new FileOutputStream(outputFile)) { - XMLReader reader = XMLReaderFactory.createXMLReader(); - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - - TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); - thandler.setSystemId("file:///" + XML_DIR); - reader.setContentHandler(thandler); - reader.parse(xsltFile); - TransformerHandler tfhandler= - saxTFactory.newTransformerHandler(thandler.getTemplates()); - Result result = new StreamResult(fos); - tfhandler.setResult(result); - reader.setContentHandler(tfhandler); - reader.parse(xmlFile); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest010.java 2015-01-09 15:42:34.985207947 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.stream.StreamSource; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLFilter; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test XMLFilter parse InputSource along with customized ContentHandler. - */ -public class SAXTFactoryTest010 { - /** - * Unit test for contentHandler setter/getter along reader as handler's - * parent. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf010.out"; - String goldFile = GOLDEN_DIR + "saxtf010GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try { - // The transformer will use a SAX parser as it's reader. - XMLReader reader = XMLReaderFactory.createXMLReader(); - - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - XMLFilter filter = - saxTFactory.newXMLFilter(new StreamSource(xsltFile)); - - filter.setParent(reader); - filter.setContentHandler(new MyContentHandler(outputFile)); - - // Now, when you call transformer.parse, it will set itself as - // the content handler for the parser object (it's "parent"), and - // will then call the parse method on the parser. - filter.parse(new InputSource(xmlFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest011.java 2015-01-09 15:42:35.184208258 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLFilter; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test XMLFilter parse InputSource along with customized ContentHandler by - * using SAX parser as it's reader. - */ -public class SAXTFactoryTest011 { - /** - * Unit test for contentHandler setter/getter with parent. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf011.out"; - String goldFile = GOLDEN_DIR + "saxtf011GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try { - // The transformer will use a SAX parser as it's reader. - XMLReader reader = XMLReaderFactory.createXMLReader(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder docBuilder = dbf.newDocumentBuilder(); - Document document = docBuilder.parse(new File(xsltFile)); - Node node = (Node)document; - DOMSource domSource= new DOMSource(node); - - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory)TransformerFactory.newInstance(); - XMLFilter filter = saxTFactory.newXMLFilter(domSource); - - filter.setParent(reader); - filter.setContentHandler(new MyContentHandler(outputFile)); - - // Now, when you call transformer.parse, it will set itself as - // the content handler for the parser object (it's "parent"), and - // will then call the parse method on the parser. - filter.parse(new InputSource(xmlFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException - | ParserConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest012.java 2015-01-09 15:42:35.381208566 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXSource; -import javax.xml.transform.sax.SAXTransformerFactory; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLFilter; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test XMLFilter parse InputSource along with customized ContentHandler by - * using SAX parser as it's reader. - */ -public class SAXTFactoryTest012 { - /** - * Unit test for contentHandler setter/getter. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf012.out"; - String goldFile = GOLDEN_DIR + "saxtf012GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - try { - // The transformer will use a SAX parser as it's reader. - XMLReader reader = XMLReaderFactory.createXMLReader(); - - InputSource is = new InputSource(new FileInputStream(xsltFile)); - SAXSource saxSource = new SAXSource(); - saxSource.setInputSource(is); - - SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance(); - XMLFilter filter = saxTFactory.newXMLFilter(saxSource); - - filter.setParent(reader); - filter.setContentHandler(new MyContentHandler(outputFile)); - - // Now, when you call transformer.parse, it will set itself as - // the content handler for the parser object (it's "parent"), and - // will then call the parse method on the parser. - filter.parse(new InputSource(xmlFile)); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -} --- old/test/javax/xml/jaxp/functional/javax/xml/transform/ptests/SAXTFactoryTest013.java 2015-01-09 15:42:35.581208878 -0800 +++ /dev/null 2014-09-08 10:45:56.830930409 -0700 @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2014, 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 javax.xml.transform.ptests; - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import static javax.xml.transform.ptests.TransformerTestConst.CLASS_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.GOLDEN_DIR; -import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TemplatesHandler; -import static jaxp.library.JAXPTestUtilities.compareWithGold; -import static jaxp.library.JAXPTestUtilities.failCleanup; -import static jaxp.library.JAXPTestUtilities.failUnexpected; -import static org.testng.Assert.assertTrue; -import org.testng.annotations.Test; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLFilter; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * Test XMLFilter parse InputSource along with TemplatesHandler. - */ -public class SAXTFactoryTest013 { - /** - * Unit test for TemplatesHandler setter/getter. - */ - @Test - public void testcase01() { - String outputFile = CLASS_DIR + "saxtf013.out"; - String goldFile = GOLDEN_DIR + "saxtf013GF.out"; - String xsltFile = XML_DIR + "cities.xsl"; - String xmlFile = XML_DIR + "cities.xml"; - - try { - // The transformer will use a SAX parser as it's reader. - XMLReader reader = XMLReaderFactory.createXMLReader(); - - SAXTransformerFactory saxTFactory - = (SAXTransformerFactory) TransformerFactory.newInstance(); - TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); - // I have put this as it was complaining about systemid - thandler.setSystemId("file:///" + CLASS_DIR); - - reader.setContentHandler(thandler); - reader.parse(xsltFile); - XMLFilter filter - = saxTFactory.newXMLFilter(thandler.getTemplates()); - filter.setParent(reader); - - filter.setContentHandler( - new MyContentHandler(outputFile)); - filter.parse(new InputSource(new FileInputStream(xmlFile))); - assertTrue(compareWithGold(goldFile, outputFile)); - } catch (SAXException | IOException | TransformerConfigurationException ex) { - failUnexpected(ex); - } finally { - try { - Path outputPath = Paths.get(outputFile); - if(Files.exists(outputPath)) - Files.delete(outputPath); - } catch (IOException ex) { - failCleanup(ex, outputFile); - } - } - } -}