This commit is contained in:
Lana Steuck 2014-12-04 15:22:42 -08:00
commit 7f77ef2719
655 changed files with 64590 additions and 0 deletions

View File

@ -1,3 +1,6 @@
# This file identifies the root of the test-suite hierarchy.
# It also contains test-suite configuration information.
# Tests that must run in othervm mode
othervm.dirs=javax/xml/jaxp/unittest

View File

@ -0,0 +1,3 @@
# jaxp test uses TestNG
TestNG.dirs = unittest

View File

@ -0,0 +1,69 @@
/*
* 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.common;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6350682
* @summary Test SAXParserFactory and TransformerFactory can newInstance when setContextClassLoader(null).
*/
public class Bug6350682 {
@Test
public void testSAXParserFactory() {
try {
Thread.currentThread().setContextClassLoader(null);
if (Bug6350682.class.getClassLoader() == null)
System.out.println("this class loader is NULL");
else
System.out.println("this class loader is NOT NULL");
SAXParserFactory factory = SAXParserFactory.newInstance();
Assert.assertTrue(factory != null, "Failed to get an instance of a SAXParserFactory");
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception occured: " + e.getMessage());
}
}
@Test
public void testTransformerFactory() {
try {
Thread.currentThread().setContextClassLoader(null);
TransformerFactory factory = TransformerFactory.newInstance();
Assert.assertTrue(factory != null, "Failed to get an instance of a TransformerFactory");
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception occured: " + e.getMessage());
} catch (TransformerFactoryConfigurationError error) {
error.printStackTrace();
Assert.fail(error.toString());
}
}
}

View File

@ -0,0 +1,64 @@
/*
* 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.common;
import org.testng.annotations.Test;
import org.testng.Assert;
import java.net.URL;
import java.net.URLClassLoader;
import javax.xml.parsers.SAXParserFactory;
/*
* @bug 6723276
* @summary Test JAXP class can be loaded by bootstrap classloader.
*/
public class Bug6723276Test {
@Test
public void test1() {
try {
SAXParserFactory.newInstance();
} catch (Exception e) {
if (e.getMessage().indexOf("org.apache.xerces.jaxp.SAXParserFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
}
}
}
@Test
public void test2() {
try {
System.out.println(Thread.currentThread().getContextClassLoader());
System.out.println(ClassLoader.getSystemClassLoader().getParent());
Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[0], ClassLoader.getSystemClassLoader().getParent()));
SAXParserFactory.newInstance();
} catch (Exception e) {
if (e.getMessage().indexOf("org.apache.xerces.jaxp.SAXParserFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
}
}
}
}

View File

@ -0,0 +1,10 @@
<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Bug6941169.xsd">
<fooTest>
test
information
</fooTest>
</root>

View File

@ -0,0 +1,11 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="fooTest" type="xs:anySimpleType" fixed="test information"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

View File

@ -0,0 +1,501 @@
/*
* 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.common;
import java.io.InputStream;
import java.io.StringWriter;
import java.security.AllPermission;
import java.security.Permission;
import java.security.Permissions;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/*
* @bug 6941169
* @summary Test use-service-mechanism feature.
*/
public class Bug6941169Test {
static final String SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
private static final String DOM_FACTORY_ID = "javax.xml.parsers.DocumentBuilderFactory";
private static final String SAX_FACTORY_ID = "javax.xml.parsers.SAXParserFactory";
// impl specific feature
final String ORACLE_FEATURE_SERVICE_MECHANISM = "http://www.oracle.com/feature/use-service-mechanism";
static String _xml = Bug6941169Test.class.getResource("Bug6941169.xml").getPath();
static String _xsd = Bug6941169Test.class.getResource("Bug6941169.xsd").getPath();
@Test
public void testValidation_SAX_withoutServiceMech() {
System.out.println("Validation using SAX Source; Service mechnism is turned off; SAX Impl should be the default:");
InputSource is = new InputSource(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml"));
SAXSource ss = new SAXSource(is);
System.setProperty(SAX_FACTORY_ID, "MySAXFactoryImpl");
long start = System.currentTimeMillis();
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, false);
Schema schema = factory.newSchema(new StreamSource(_xsd));
Validator validator = schema.newValidator();
validator.validate(ss, null);
} catch (Exception e) {
// e.printStackTrace();
String error = e.getMessage();
if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl is used");
}
// System.out.println(e.getMessage());
}
long end = System.currentTimeMillis();
double elapsedTime = ((end - start));
System.out.println("Time elapsed: " + elapsedTime);
System.clearProperty(SAX_FACTORY_ID);
}
@Test
public void testValidation_SAX_withServiceMech() {
System.out.println("Validation using SAX Source. Using service mechnism (by default) to find SAX Impl:");
InputSource is = new InputSource(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml"));
SAXSource ss = new SAXSource(is);
System.setProperty(SAX_FACTORY_ID, "MySAXFactoryImpl");
long start = System.currentTimeMillis();
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(_xsd));
Validator validator = schema.newValidator();
validator.validate(ss, null);
Assert.fail("User impl MySAXFactoryImpl should be used.");
} catch (Exception e) {
String error = e.getMessage();
if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) {
// expected
}
// System.out.println(e.getMessage());
}
long end = System.currentTimeMillis();
double elapsedTime = ((end - start));
System.out.println("Time elapsed: " + elapsedTime);
System.clearProperty(SAX_FACTORY_ID);
}
@Test
public void testValidation_SAX_withSM() {
System.out.println("Validation using SAX Source with security manager:");
InputSource is = new InputSource(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml"));
SAXSource ss = new SAXSource(is);
System.setProperty(SAX_FACTORY_ID, "MySAXFactoryImpl");
Permissions granted = new java.security.Permissions();
granted.add(new AllPermission());
System.setSecurityManager(new MySM(granted));
long start = System.currentTimeMillis();
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, false);
Schema schema = factory.newSchema(new StreamSource(_xsd));
Validator validator = schema.newValidator();
validator.validate(ss, null);
} catch (Exception e) {
String error = e.getMessage();
if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl is used");
}
// System.out.println(e.getMessage());
} finally {
System.clearProperty(SAX_FACTORY_ID);
System.setSecurityManager(null);
}
long end = System.currentTimeMillis();
double elapsedTime = ((end - start));
System.out.println("Time elapsed: " + elapsedTime);
System.setSecurityManager(null);
}
@Test
public void testTransform_DOM_withoutServiceMech() {
System.out.println("Transform using DOM Source; Service mechnism is turned off; Default DOM Impl should be the default:");
DOMSource domSource = new DOMSource();
domSource.setSystemId(_xml);
// DOMSource domSource = new
// DOMSource(getDocument(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml")));
System.setProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
long start = System.currentTimeMillis();
try {
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, false);
Transformer t = factory.newTransformer();
StringWriter result = new StringWriter();
StreamResult streamResult = new StreamResult(result);
t.transform(domSource, streamResult);
System.out.println("Writing to " + result.toString());
} catch (Exception e) {
// e.printStackTrace();
String error = e.getMessage();
if (error.indexOf("Provider MyDOMFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl is used");
}
// System.out.println(e.getMessage());
} catch (Error e) {
// e.printStackTrace();
String error = e.getMessage();
if (error.indexOf("Provider MyDOMFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl is used");
}
// System.out.println(e.getMessage());
}
long end = System.currentTimeMillis();
double elapsedTime = ((end - start));
System.out.println("Time elapsed: " + elapsedTime);
System.clearProperty(DOM_FACTORY_ID);
}
/** this is by default */
@Test
public void testTransform_DOM_withServiceMech() {
System.out.println("Transform using DOM Source; By default, the factory uses services mechanism to look up impl:");
DOMSource domSource = new DOMSource();
domSource.setSystemId(_xml);
// DOMSource domSource = new
// DOMSource(getDocument(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml")));
System.setProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
long start = System.currentTimeMillis();
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer t = factory.newTransformer();
StringWriter result = new StringWriter();
StreamResult streamResult = new StreamResult(result);
t.transform(domSource, streamResult);
System.out.println("Writing to " + result.toString());
Assert.fail("User impl MyDOMFactoryImpl should be used.");
} catch (Exception e) {
String error = e.getMessage();
if (error.indexOf("Provider MyDOMFactoryImpl not found") > 0) {
// expected
}
System.out.println(error);
} catch (Error e) {
String error = e.getMessage();
if (error.indexOf("Provider MyDOMFactoryImpl not found") > 0) {
// expected
}
System.out.println(error);
}
long end = System.currentTimeMillis();
double elapsedTime = ((end - start));
System.out.println("Time elapsed: " + elapsedTime);
System.clearProperty(DOM_FACTORY_ID);
}
@Test
public void testTransform_DOM_withSM() {
System.out.println("Transform using DOM Source; Security Manager is set:");
DOMSource domSource = new DOMSource();
domSource.setSystemId(_xml);
// DOMSource domSource = new
// DOMSource(getDocument(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml")));
Permissions granted = new java.security.Permissions();
granted.add(new AllPermission());
System.setSecurityManager(new MySM(granted));
System.setProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
long start = System.currentTimeMillis();
try {
TransformerFactory factory = TransformerFactory.newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl",
TransformerFactory.class.getClassLoader());
Transformer t = factory.newTransformer();
StringWriter result = new StringWriter();
StreamResult streamResult = new StreamResult(result);
t.transform(domSource, streamResult);
System.out.println("Writing to " + result.toString());
} catch (Exception e) {
String error = e.getMessage();
if (error.indexOf("Provider MyDOMFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl is used");
}
// System.out.println(e.getMessage());
} catch (Error e) {
String error = e.getMessage();
if (error.indexOf("Provider MyDOMFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl is used");
}
// System.out.println(e.getMessage());
} finally {
System.clearProperty(DOM_FACTORY_ID);
System.setSecurityManager(null);
}
long end = System.currentTimeMillis();
double elapsedTime = ((end - start));
System.out.println("Time elapsed: " + elapsedTime);
System.clearProperty(DOM_FACTORY_ID);
}
@Test
public void testXPath_DOM_withoutServiceMech() {
final String XPATH_EXPRESSION = "/fooTest";
System.out.println("Evaluate DOM Source; Service mechnism is turned off; Default DOM Impl should be used:");
Document doc = getDocument(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml"));
System.setProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
long start = System.currentTimeMillis();
try {
XPathFactory xPathFactory = XPathFactory.newInstance();
xPathFactory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, false);
XPath xPath = xPathFactory.newXPath();
String xPathResult = xPath.evaluate(XPATH_EXPRESSION, doc);
} catch (Exception e) {
// e.printStackTrace();
String error = e.getMessage();
if (error.indexOf("MyDOMFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl is used");
}
// System.out.println(e.getMessage());
} catch (Error e) {
// e.printStackTrace();
String error = e.getMessage();
if (error.indexOf("MyDOMFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl is used");
}
// System.out.println(e.getMessage());
}
long end = System.currentTimeMillis();
double elapsedTime = ((end - start));
System.out.println("Time elapsed: " + elapsedTime);
System.clearProperty(DOM_FACTORY_ID);
}
@Test
public void testXPath_DOM_withServiceMech() {
final String XPATH_EXPRESSION = "/fooTest";
System.out.println("Evaluate DOM Source; Service mechnism is on by default; It would try to use MyDOMFactoryImpl:");
InputStream input = getClass().getResourceAsStream("Bug6941169.xml");
InputSource source = new InputSource(input);
System.setProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
long start = System.currentTimeMillis();
try {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
String xPathResult = xPath.evaluate(XPATH_EXPRESSION, source);
Assert.fail("User impl MyDOMFactoryImpl should be used.");
} catch (Exception e) {
// e.printStackTrace();
String error = e.getMessage();
if (error.indexOf("MyDOMFactoryImpl not found") > 0) {
System.out.println("Tried to locate MyDOMFactoryImpl");
} else {
Assert.fail(e.getMessage());
}
// System.out.println(e.getMessage());
} catch (Error e) {
// e.printStackTrace();
String error = e.getMessage();
if (error.indexOf("MyDOMFactoryImpl not found") > 0) {
System.out.println("Tried to locate MyDOMFactoryImpl");
} else {
Assert.fail(e.getMessage());
}
// System.out.println(e.getMessage());
}
long end = System.currentTimeMillis();
double elapsedTime = ((end - start));
System.out.println("Time elapsed: " + elapsedTime);
System.clearProperty(DOM_FACTORY_ID);
}
@Test
public void testXPath_DOM_withSM() {
final String XPATH_EXPRESSION = "/fooTest";
System.out.println("Evaluate DOM Source; Security Manager is set:");
Permissions granted = new java.security.Permissions();
granted.add(new AllPermission());
System.setSecurityManager(new MySM(granted));
InputStream input = getClass().getResourceAsStream("Bug6941169.xml");
InputSource source = new InputSource(input);
System.setProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
long start = System.currentTimeMillis();
try {
XPathFactory xPathFactory = XPathFactory.newInstance("http://java.sun.com/jaxp/xpath/dom",
"com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl", null);
XPath xPath = xPathFactory.newXPath();
String xPathResult = xPath.evaluate(XPATH_EXPRESSION, source);
System.out.println("Use default impl");
} catch (Exception e) {
// e.printStackTrace();
String error = e.getMessage();
if (error.indexOf("MyDOMFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl should be used");
}
// System.out.println(e.getMessage());
} catch (Error e) {
// e.printStackTrace();
String error = e.getMessage();
if (error.indexOf("MyDOMFactoryImpl not found") > 0) {
Assert.fail(e.getMessage());
} else {
System.out.println("Default impl should be used");
}
// System.out.println(e.getMessage());
} finally {
System.clearProperty(DOM_FACTORY_ID);
System.setSecurityManager(null);
}
long end = System.currentTimeMillis();
double elapsedTime = ((end - start));
System.out.println("Time elapsed: " + elapsedTime);
System.clearProperty(DOM_FACTORY_ID);
}
@Test
public void testSM() {
SecurityManager sm = System.getSecurityManager();
if (System.getSecurityManager() != null) {
System.out.println("Security manager not cleared: " + sm.toString());
} else {
System.out.println("Security manager cleared: ");
}
}
private static Document getDocument(InputStream in) {
Document document = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(in);
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.toString());
}
return document;
}
class MySM extends SecurityManager {
Permissions granted;
public MySM(Permissions perms) {
granted = perms;
}
@Override
public void checkPermission(Permission perm) {
if (granted.implies(perm)) {
return;
}
super.checkPermission(perm);
}
}
}

View File

@ -0,0 +1,44 @@
/*
* 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.common;
import org.testng.annotations.Test;
import com.sun.org.apache.xalan.internal.xslt.EnvironmentCheck;
/*
* @bug 6979306
* @summary Test JAXP component version.
*/
public class Bug6979306Test {
@Test
public void test() {
String[] input = {};
EnvironmentCheck.main(input);
com.sun.org.apache.xerces.internal.impl.Version.main(input);
com.sun.org.apache.xalan.internal.Version._main(input);
}
}

View File

@ -0,0 +1,159 @@
/*
* 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.common;
import java.security.AllPermission;
import java.security.Permission;
import java.security.Permissions;
import javax.xml.XMLConstants;
import javax.xml.transform.TransformerFactory;
import javax.xml.validation.SchemaFactory;
import javax.xml.xpath.XPathFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 7143711
* @summary Test set use-service-mechanism shall not override what's set by the constructor in secure mode.
*/
public class Bug7143711Test {
static final String SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
private static final String DOM_FACTORY_ID = "javax.xml.parsers.DocumentBuilderFactory";
private static final String SAX_FACTORY_ID = "javax.xml.parsers.SAXParserFactory";
// impl specific feature
final String ORACLE_FEATURE_SERVICE_MECHANISM = "http://www.oracle.com/feature/use-service-mechanism";
@Test
public void testValidation_SAX_withSM() {
System.out.println("Validation using SAX Source with security manager:");
System.setProperty(SAX_FACTORY_ID, "MySAXFactoryImpl");
Permissions granted = new java.security.Permissions();
granted.add(new AllPermission());
System.setSecurityManager(new MySM(granted));
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// should not allow
factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, true);
if ((boolean) factory.getFeature(ORACLE_FEATURE_SERVICE_MECHANISM)) {
Assert.fail("should not override in secure mode");
}
} catch (Exception e) {
Assert.fail(e.getMessage());
} finally {
System.clearProperty(SAX_FACTORY_ID);
System.setSecurityManager(null);
}
System.setSecurityManager(null);
}
@Test
public void testTransform_DOM_withSM() {
System.out.println("Transform using DOM Source; Security Manager is set:");
Permissions granted = new java.security.Permissions();
granted.add(new AllPermission());
System.setSecurityManager(new MySM(granted));
System.setProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
try {
TransformerFactory factory = TransformerFactory.newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl",
TransformerFactory.class.getClassLoader());
factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, true);
if (((com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl) factory).useServicesMechnism()) {
Assert.fail("should not override in secure mode");
}
} catch (Exception e) {
Assert.fail(e.getMessage());
} finally {
System.clearProperty(DOM_FACTORY_ID);
System.setSecurityManager(null);
}
System.clearProperty(DOM_FACTORY_ID);
}
@Test
public void testXPath_DOM_withSM() {
System.out.println("Evaluate DOM Source; Security Manager is set:");
Permissions granted = new java.security.Permissions();
granted.add(new AllPermission());
System.setSecurityManager(new MySM(granted));
System.setProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
try {
XPathFactory xPathFactory = XPathFactory.newInstance("http://java.sun.com/jaxp/xpath/dom",
"com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl", null);
xPathFactory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, true);
if ((boolean) xPathFactory.getFeature(ORACLE_FEATURE_SERVICE_MECHANISM)) {
Assert.fail("should not override in secure mode");
}
} catch (Exception e) {
Assert.fail(e.getMessage());
} finally {
System.clearProperty(DOM_FACTORY_ID);
System.setSecurityManager(null);
}
System.clearProperty(DOM_FACTORY_ID);
}
@Test
public void testSM() {
SecurityManager sm = System.getSecurityManager();
if (System.getSecurityManager() != null) {
System.out.println("Security manager not cleared: " + sm.toString());
} else {
System.out.println("Security manager cleared: ");
}
}
class MySM extends SecurityManager {
Permissions granted;
public MySM(Permissions perms) {
granted = perms;
}
@Override
public void checkPermission(Permission perm) {
if (granted.implies(perm)) {
return;
}
super.checkPermission(perm);
}
}
}

View File

@ -0,0 +1,104 @@
/*
* 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.datatype;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6320118
* @summary Test xml datatype XMLGregorianCalendar.
*/
public class Bug6320118 {
DatatypeFactory df;
@Test
public void test1() {
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
Assert.fail(e.getMessage());
}
try {
XMLGregorianCalendar calendar = df.newXMLGregorianCalendar(1970, 1, 1, 24, 0, 0, 0, 0);
} catch (IllegalArgumentException e) {
Assert.fail(e.getMessage());
}
}
@Test
public void test2() {
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
Assert.fail(e.getMessage());
}
try {
XMLGregorianCalendar calendar = df.newXMLGregorianCalendarTime(24, 0, 0, 0);
} catch (IllegalArgumentException e) {
Assert.fail(e.getMessage());
}
}
@Test
public void test3() {
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
Assert.fail(e.getMessage());
}
try {
XMLGregorianCalendar calendar = df.newXMLGregorianCalendar();
// Must fail as other params are not 0 but undefined
calendar.setHour(24);
Assert.fail("test3() - Expected IllegalArgumentException not thrown");
} catch (IllegalArgumentException e) {
// falls through
}
}
@Test
public void test4() {
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
Assert.fail(e.getMessage());
}
try {
XMLGregorianCalendar calendar = df.newXMLGregorianCalendar();
calendar.setTime(24, 0, 0, 0);
} catch (IllegalArgumentException e) {
Assert.fail(e.getMessage());
}
}
}

View File

@ -0,0 +1,49 @@
/*
* 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.datatype;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6937951
* @summary Test midnight is same as the start of the next day in XMLGregorianCalendar.
*/
public class Bug6937951Test {
@Test
public void test() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
XMLGregorianCalendar c1 = dtf.newXMLGregorianCalendar("1999-12-31T24:00:00");
XMLGregorianCalendar c2 = dtf.newXMLGregorianCalendar("2000-01-01T00:00:00");
System.out.println("c1: " + c1.getYear() + "-" + c1.getMonth() + "-" + c1.getDay() + "T" + c1.getHour());
System.out.println(c1.equals(c2) ? "pass" : "fail"); // fails
if (!c1.equals(c2))
Assert.fail("hour 24 needs to be treated as equal to hour 0 of the next day");
if (c1.getYear() != 2000 && c1.getHour() != 0)
Assert.fail("hour 24 needs to be treated as equal to hour 0 of the next day");
}
}

View File

@ -0,0 +1,262 @@
/*
* 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.datatype;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.xml.namespace.QName;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6937964
* @summary Test Duration is normalized.
*/
public class Bug6937964Test {
/**
* Print debugging to System.err.
*/
private static final boolean DEBUG = false;
/**
* Constant to indicate expected lexical test failure.
*/
private static final String TEST_VALUE_FAIL = "*FAIL*";
private static final String FIELD_UNDEFINED = "FIELD_UNDEFINED";
static final DatatypeConstants.Field[] fields = { DatatypeConstants.YEARS, DatatypeConstants.MONTHS, DatatypeConstants.DAYS, DatatypeConstants.HOURS,
DatatypeConstants.MINUTES, DatatypeConstants.SECONDS };
@Test
public void test() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationYearMonth("P20Y15M");
int years = d.getYears();
System.out.println(d.getYears() == 21 ? "pass" : "fail");
}
@Test
public void testNewDurationYearMonthLexicalRepresentation() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationYearMonth("P20Y15M");
int years = d.getYears();
Assert.assertTrue(years == 21, "Return value should be normalized");
}
@Test
public void testNewDurationYearMonthMilliseconds() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationYearMonth(671976000000L);
int years = d.getYears();
System.out.println("Years: " + years);
Assert.assertTrue(years == 21, "Return value should be normalized");
}
@Test
public void testNewDurationYearMonthBigInteger() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
BigInteger year = new BigInteger("20");
BigInteger mon = new BigInteger("15");
Duration d = dtf.newDurationYearMonth(true, year, mon);
int years = d.getYears();
Assert.assertTrue(years == 21, "Return value should be normalized");
}
@Test
public void testNewDurationYearMonthInt() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationYearMonth(true, 20, 15);
int years = d.getYears();
Assert.assertTrue(years == 21, "Return value should be normalized");
}
@Test
public void testNewDurationDayTimeLexicalRepresentation() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationDayTime("P1DT23H59M65S");
int days = d.getDays();
Assert.assertTrue(days == 2, "Return value should be normalized");
}
@Test
public void testNewDurationDayTimeMilliseconds() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationDayTime(172805000L);
int days = d.getDays();
Assert.assertTrue(days == 2, "Return value should be normalized");
}
@Test
public void testNewDurationDayTimeBigInteger() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
BigInteger day = new BigInteger("1");
BigInteger hour = new BigInteger("23");
BigInteger min = new BigInteger("59");
BigInteger sec = new BigInteger("65");
Duration d = dtf.newDurationDayTime(true, day, hour, min, sec);
int days = d.getDays();
System.out.println("Days: " + days);
Assert.assertTrue(days == 2, "Return value should be normalized");
}
@Test
public void testNewDurationDayTimeInt() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationDayTime(true, 1, 23, 59, 65);
int days = d.getDays();
System.out.println("Days: " + days);
Assert.assertTrue(days == 2, "Return value should be normalized");
}
@Test
public final void testNewDurationYearMonthLexicalRepresentation1() {
/**
* Lexical test values to test.
*/
final String[] TEST_VALUES_LEXICAL = { "P13M", "P1Y1M", "-P13M", "-P1Y1M", "P1Y", "P1Y", "-P1Y", "-P1Y", "P1Y25M", "P3Y1M", "-P1Y25M", "-P3Y1M" };
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES_LEXICAL.length; onTestValue = onTestValue + 2) {
if (DEBUG) {
System.err.println("testing value: \"" + TEST_VALUES_LEXICAL[onTestValue] + "\", expecting: \"" + TEST_VALUES_LEXICAL[onTestValue + 1] + "\"");
}
try {
Duration duration = datatypeFactory.newDurationYearMonth(TEST_VALUES_LEXICAL[onTestValue]);
if (DEBUG) {
System.err.println("Duration created: \"" + duration.toString() + "\"");
}
// was this expected to fail?
if (TEST_VALUES_LEXICAL[onTestValue + 1].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" is invalid yet it created the Duration \"" + duration.toString() + "\"");
}
// right XMLSchemaType?
// TODO: enable test, it should pass, it fails with Exception(s)
// for now due to a bug
try {
QName xmlSchemaType = duration.getXMLSchemaType();
if (!xmlSchemaType.equals(DatatypeConstants.DURATION_YEARMONTH)) {
Assert.fail("Duration created with XMLSchemaType of\"" + xmlSchemaType + "\" was expected to be \""
+ DatatypeConstants.DURATION_YEARMONTH + "\" and has the value \"" + duration.toString() + "\"");
}
} catch (IllegalStateException illegalStateException) {
// TODO; this test really should pass
System.err.println("Please fix this bug that is being ignored, for now: " + illegalStateException.getMessage());
}
// does it have the right value?
if (!TEST_VALUES_LEXICAL[onTestValue + 1].equals(duration.toString())) {
Assert.fail("Duration created with \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_LEXICAL[onTestValue + 1] + "\" and has the value \"" + duration.toString() + "\"");
}
// Duration created with correct value
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating duration: \"" + exception.toString() + "\"");
}
// was this expected to succed?
if (!TEST_VALUES_LEXICAL[onTestValue + 1].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
}
}
/**
* TCK test failure
*/
@Test
public void testNewDurationDayTime005() {
BigInteger one = new BigInteger("1");
BigInteger zero = new BigInteger("0");
BigDecimal bdZero = new BigDecimal("0");
BigDecimal bdOne = new BigDecimal("1");
Object[][] values = {
// lex, isPositive, years, month, days, hours, minutes, seconds
{ "P1D", Boolean.TRUE, null, null, one, zero, zero, bdZero }, { "PT1H", Boolean.TRUE, null, null, zero, one, zero, bdZero },
{ "PT1M", Boolean.TRUE, null, null, zero, zero, one, bdZero }, { "PT1.1S", Boolean.TRUE, null, null, zero, zero, zero, bdOne },
{ "-PT1H1.1S", Boolean.FALSE, null, null, zero, one, zero, bdOne }, };
StringBuffer result = new StringBuffer();
DatatypeFactory df = null;
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
Assert.fail(e.toString());
}
for (int valueIndex = 0; valueIndex < values.length; ++valueIndex) {
Duration duration = null;
try {
duration = df.newDurationDayTime(values[valueIndex][1].equals(Boolean.TRUE), ((BigInteger) values[valueIndex][4]).intValue(),
((BigInteger) values[valueIndex][5]).intValue(), ((BigInteger) values[valueIndex][6]).intValue(),
((BigDecimal) values[valueIndex][7]).intValue());
} catch (IllegalArgumentException e) {
result.append("; unexpected " + e + " trying to create duration \'" + values[valueIndex][0] + "\'");
}
if (duration != null) {
if ((duration.getSign() == 1) != values[valueIndex][1].equals(Boolean.TRUE)) {
result.append("; " + values[valueIndex][0] + ": wrong sign " + duration.getSign() + ", expected " + values[valueIndex][1]);
}
for (int i = 0; i < fields.length; ++i) {
Number value = duration.getField(fields[i]);
if ((value != null && values[valueIndex][2 + i] == null) || (value == null && values[valueIndex][2 + i] != null)
|| (value != null && !value.equals(values[valueIndex][2 + i]))) {
result.append("; " + values[valueIndex][0] + ": wrong value of the field " + fields[i] + ": \'" + value + "\'" + ", expected \'"
+ values[valueIndex][2 + i] + "\'");
}
}
}
}
if (result.length() > 0) {
Assert.fail(result.substring(2));
}
System.out.println("OK");
}
}

View File

@ -0,0 +1,52 @@
/*
* 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.datatype;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 7042647
* @summary Test getFirstDayOfWeek is correct after converting XMLGregorianCalendar to a GregorianCalendar.
*/
public class Bug7042647Test {
@Test
public void test() throws DatatypeConfigurationException {
XMLGregorianCalendar xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(1970, 1, 1, 0, 0, 0, 0, 0);
GregorianCalendar calendar = xmlCalendar.toGregorianCalendar();
int firstDayOfWeek = calendar.getFirstDayOfWeek();
Calendar defaultCalendar = Calendar.getInstance();
int defaultFirstDayOfWeek = defaultCalendar.getFirstDayOfWeek();
if (firstDayOfWeek != defaultFirstDayOfWeek) {
Assert.fail("Failed firstDayOfWeek=" + firstDayOfWeek + " != defaultFirstDayOfWeek=" + defaultFirstDayOfWeek);
} else {
System.out.println("Success firstDayOfWeek=" + firstDayOfWeek + " == defaultFirstDayOfWeek=" + defaultFirstDayOfWeek);
}
}
}

View File

@ -0,0 +1,631 @@
/*
* 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.datatype;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.xml.namespace.QName;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @summary Test DatatypeFactory.
*/
public class DatatypeFactoryTest {
private static final boolean DEBUG = false;
private static final String TEST_VALUE_FAIL = "*FAIL*";
private static final String FIELD_UNDEFINED = "FIELD_UNDEFINED";
static int parseInt(String value) {
return FIELD_UNDEFINED.equals(value) ? DatatypeConstants.FIELD_UNDEFINED : Integer.parseInt(value);
}
static BigDecimal parseBigDecimal(String value) {
return FIELD_UNDEFINED.equals(value) ? null : new BigDecimal(value);
}
static BigInteger parseBigInteger(String value) {
return FIELD_UNDEFINED.equals(value) ? null : new BigInteger(value);
}
@Test
public final void testNewDurationMilliseconds() {
/*
* to generate millisecond values
* final TimeZone GMT = TimeZone.getTimeZone("GMT"); GregorianCalendar
* gregorianCalendar = new GregorianCalendar(GMT);
* gregorianCalendar.setTimeInMillis(0);
* gregorianCalendar.add(Calendar.HOUR_OF_DAY, 1);
* gregorianCalendar.add(Calendar.MINUTE, 1);
* System.err.println("1 hour, 1 minute = " +
* gregorianCalendar.getTimeInMillis() + " milliseconds");
*/
/**
* Millisecond test values to test.
*/
final long[] TEST_VALUES_MILLISECONDS = { 0L, // 0
1L, // 1 millisecond
-1L, 1000L, // 1 second
-1000L, 1001L, // 1 second, 1 millisecond
-1001L, 60000L, // 1 minute
-60000L, 61000L, // 1 minute, 1 second
-61000L, 3600000L, // 1 hour
-3600000L, 3660000L, // 1 hour, 1 minute
-3660000L, 86400000L, // 1 day
-86400000L, 90000000L, // 1 day, 1 hour
-90000000L, 2678400000L, // 1 month
-2678400000L, 2764800000L, // 1 month, 1 day
-2764800000L, 31536000000L, // 1 year
-31536000000L, 34214400000L, // 1 year, 1 month
-34214400000L };
/**
* Millisecond test value results of test.
*/
final String[] TEST_VALUES_MILLISECONDS_RESULTS = { "P0Y0M0DT0H0M0.000S", // 0
"P0Y0M0DT0H0M0.001S", // 1 millisecond
"-P0Y0M0DT0H0M0.001S", "P0Y0M0DT0H0M1.000S", // 1 second
"-P0Y0M0DT0H0M1.000S", "P0Y0M0DT0H0M1.001S", // 1 second, 1
// millisecond
"-P0Y0M0DT0H0M1.001S", "P0Y0M0DT0H1M0.000S", // 1 minute
"-P0Y0M0DT0H1M0.000S", "P0Y0M0DT0H1M1.000S", // 1 minute, 1
// second
"-P0Y0M0DT0H1M1.000S", "P0Y0M0DT1H0M0.000S", // 1 hour
"-P0Y0M0DT1H0M0.000S", "P0Y0M0DT1H1M0.000S", // 1 hour, 1 minute
"-P0Y0M0DT1H1M0.000S", "P0Y0M1DT0H0M0.000S", // 1 day
"-P0Y0M1DT0H0M0.000S", "P0Y0M1DT1H0M0.000S", // 1 day, 1 hour
"-P0Y0M1DT1H0M0.000S", "P0Y1M0DT0H0M0.000S", // 1 month
"-P0Y1M0DT0H0M0.000S", "P0Y1M1DT0H0M0.000S", // 1 month, 1 day
"-P0Y1M1DT0H0M0.000S", "P1Y0M0DT0H0M0.000S", // 1 year
"-P1Y0M0DT0H0M0.000S", "P1Y1M0DT0H0M0.000S", // 1 year, 1 month
"-P1Y1M0DT0H0M0.000S" };
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES_MILLISECONDS.length; onTestValue++) {
if (DEBUG) {
System.err.println("testing value: \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\", expecting: \""
+ TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\"");
}
try {
Duration duration = datatypeFactory.newDuration(TEST_VALUES_MILLISECONDS[onTestValue]);
if (DEBUG) {
System.err.println("Duration created: \"" + duration.toString() + "\"");
}
// was this expected to fail?
if (TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is invalid yet it created the Duration \"" + duration.toString()
+ "\"");
}
// right XMLSchemaType?
QName xmlSchemaType = duration.getXMLSchemaType();
if (!xmlSchemaType.equals(DatatypeConstants.DURATION)) {
Assert.fail("Duration created with XMLSchemaType of\"" + xmlSchemaType + "\" was expected to be \"" + DatatypeConstants.DURATION
+ "\" and has the value \"" + duration.toString() + "\"");
}
// does it have the right value?
if (!TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(duration.toString())) {
Assert.fail("Duration created with \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\" and has the value \"" + duration.toString() + "\"");
}
// Duration created with correct value
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating duration: \"" + exception.toString() + "\"");
}
// was this expected to succed?
if (!TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
}
}
/**
* Test {@link DatatypeFactory.newDurationYearMonth(String
* lexicalRepresentation)}.
*/
@Test
public final void testNewDurationYearMonthLexicalRepresentation() {
/**
* Lexical test values to test.
*/
final String[] TEST_VALUES_LEXICAL = { null, TEST_VALUE_FAIL, "", TEST_VALUE_FAIL, "-", TEST_VALUE_FAIL, "P", TEST_VALUE_FAIL, "-P", TEST_VALUE_FAIL,
"P1D", TEST_VALUE_FAIL, "P1Y1M1D", TEST_VALUE_FAIL, "P1M", "P1M", "-P1M", "-P1M", "P1Y", "P1Y", "-P1Y", "-P1Y", "P1Y1M", "P1Y1M", "-P1Y1M",
"-P1Y1M" };
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES_LEXICAL.length; onTestValue = onTestValue + 2) {
if (DEBUG) {
System.err.println("testing value: \"" + TEST_VALUES_LEXICAL[onTestValue] + "\", expecting: \"" + TEST_VALUES_LEXICAL[onTestValue + 1] + "\"");
}
try {
Duration duration = datatypeFactory.newDurationYearMonth(TEST_VALUES_LEXICAL[onTestValue]);
if (DEBUG) {
System.err.println("Duration created: \"" + duration.toString() + "\"");
}
// was this expected to fail?
if (TEST_VALUES_LEXICAL[onTestValue + 1].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" is invalid yet it created the Duration \"" + duration.toString() + "\"");
}
// right XMLSchemaType?
// TODO: enable test, it should pass, it fails with Exception(s)
// for now due to a bug
try {
QName xmlSchemaType = duration.getXMLSchemaType();
if (!xmlSchemaType.equals(DatatypeConstants.DURATION_YEARMONTH)) {
Assert.fail("Duration created with XMLSchemaType of\"" + xmlSchemaType + "\" was expected to be \""
+ DatatypeConstants.DURATION_YEARMONTH + "\" and has the value \"" + duration.toString() + "\"");
}
} catch (IllegalStateException illegalStateException) {
// TODO; this test really should pass
System.err.println("Please fix this bug that is being ignored, for now: " + illegalStateException.getMessage());
}
// does it have the right value?
if (!TEST_VALUES_LEXICAL[onTestValue + 1].equals(duration.toString())) {
Assert.fail("Duration created with \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_LEXICAL[onTestValue + 1] + "\" and has the value \"" + duration.toString() + "\"");
}
// Duration created with correct value
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating duration: \"" + exception.toString() + "\"");
}
// was this expected to succed?
if (!TEST_VALUES_LEXICAL[onTestValue + 1].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
}
}
/**
* Test {@link DatatypeFactory.newDurationYearMonth(long milliseconds)}.
*
*/
@Test
public final void testNewDurationYearMonthMilliseconds() {
/**
* Millisecond test values to test.
*/
final long[] TEST_VALUES_MILLISECONDS = { 0L, 1L, -1L, 2678400000L, // 31
// days,
// e.g.
// 1
// month
-2678400000L, 5270400000L, // 61 days, e.g. 2 months
-5270400000L, 31622400000L, // 366 days, e.g. 1 year
-31622400000L, 34300800000L, // 397 days, e.g. 1 year, 1 month
-34300800000L };
/**
* Millisecond test value results of test.
*/
final String[] TEST_VALUES_MILLISECONDS_RESULTS = { "P0Y0M", "P0Y0M", "P0Y0M", "P0Y1M", "-P0Y1M", "P0Y2M", "-P0Y2M", "P1Y0M", "-P1Y0M", "P1Y1M",
"-P1Y1M" };
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES_MILLISECONDS.length; onTestValue++) {
if (DEBUG) {
System.err.println("testing value: \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\", expecting: \""
+ TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\"");
}
try {
Duration duration = datatypeFactory.newDurationYearMonth(TEST_VALUES_MILLISECONDS[onTestValue]);
if (DEBUG) {
System.err.println("Duration created: \"" + duration.toString() + "\"");
}
// was this expected to fail?
if (TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is invalid yet it created the Duration \"" + duration.toString()
+ "\"");
}
// right XMLSchemaType?
QName xmlSchemaType = duration.getXMLSchemaType();
if (!xmlSchemaType.equals(DatatypeConstants.DURATION_YEARMONTH)) {
Assert.fail("Duration created with XMLSchemaType of\"" + xmlSchemaType + "\" was expected to be \"" + DatatypeConstants.DURATION_YEARMONTH
+ "\" and has the value \"" + duration.toString() + "\"");
}
// does it have the right value?
if (!TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(duration.toString())) {
Assert.fail("Duration created with \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\" and has the value \"" + duration.toString() + "\"");
}
// only YEAR & MONTH should have values
int days = duration.getDays();
int hours = duration.getHours();
int minutes = duration.getMinutes();
if (days != 0 || hours != 0 || minutes != 0) {
Assert.fail("xdt:yearMonthDuration created without discarding remaining milliseconds: " + " days = " + days + ", hours = " + hours
+ ", minutess = " + minutes);
}
// Duration created with correct values
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating duration: \"" + exception.toString() + "\"");
}
// was this expected to succed?
if (!TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
}
}
/**
* Test {@link DatatypeFactory.newDurationDayTime(long milliseconds)}.
*/
@Test
public final void testNewDurationDayTime() {
/**
* Millisecond test values to test.
*/
final long[] TEST_VALUES_MILLISECONDS = { 0L, 1L, -1L, 2678400000L, // 31
// days,
// e.g.
// 1
// month
-2678400000L, 5270400000L, // 61 days, e.g. 2 months
-5270400000L, 31622400000L, // 366 days, e.g. 1 year
-31622400000L, 34300800000L, // 397 days, e.g. 1 year, 1 month
-34300800000L };
/**
* Millisecond test value results of test.
*/
final String[] TEST_VALUES_MILLISECONDS_RESULTS = { "P0Y0M0DT0H0M0.000S", "P0Y0M0DT0H0M0.001S", "-P0Y0M0DT0H0M0.001S", "P0Y1M", "-P0Y1M", "P0Y2M",
"-P0Y2M", "P1Y0M", "-P1Y0M", "P1Y1M", "-P1Y1M" };
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES_MILLISECONDS.length; onTestValue++) {
if (DEBUG) {
System.err.println("testing value: \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\", expecting: \""
+ TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\"");
}
try {
Duration duration = datatypeFactory.newDurationDayTime(TEST_VALUES_MILLISECONDS[onTestValue]);
if (DEBUG) {
System.err.println("Duration created: \"" + duration.toString() + "\"");
}
// was this expected to fail?
if (TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is invalid yet it created the Duration \"" + duration.toString()
+ "\"");
}
// does it have the right value?
if (!TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(duration.toString())) {
// TODO: this is bug that should be fixed
if (false) {
Assert.fail("Duration created with \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\" and has the value \"" + duration.toString() + "\"");
} else {
System.err.println("Please fix this bug: " + "Duration created with \"" + TEST_VALUES_MILLISECONDS[onTestValue]
+ "\" was expected to be \"" + TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\" and has the value \"" + duration.toString()
+ "\"");
}
}
// only day, hour, minute, and second should have values
QName xmlSchemaType = duration.getXMLSchemaType();
int years = duration.getYears();
int months = duration.getMonths();
if (!xmlSchemaType.equals(DatatypeConstants.DURATION_DAYTIME) || years != 0 || months != 0) {
// TODO: this is bug that should be fixed
if (false) {
Assert.fail("xdt:dayTimeDuration created without discarding remaining milliseconds: " + " XMLSchemaType = " + xmlSchemaType
+ ", years = " + years + ", months = " + months);
} else {
System.err.println("Please fix this bug: " + "xdt:dayTimeDuration created without discarding remaining milliseconds: "
+ " XMLSchemaType = " + xmlSchemaType + ", years = " + years + ", months = " + months);
}
}
// Duration created with correct values
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating duration: \"" + exception.toString() + "\"");
}
// was this expected to succed?
if (!TEST_VALUES_MILLISECONDS_RESULTS[onTestValue].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
}
}
/**
* Test {@link DatatypeFactory.newXMLGregorianCalendar(String
* lexicalRepresentation)}.
*/
@Test
public final void testNewXMLGregorianCalendarLexicalRepresentation() {
/**
* Lexical test values to test.
*/
final String[] TEST_VALUES_LEXICAL = { null, TEST_VALUE_FAIL, "", TEST_VALUE_FAIL, "---01", "---01", // gDay
"---01Z", "---01Z", // gDay, UTC
"---01-08:00", "---01-08:00", // gDay, PDT
"--01--", TEST_VALUE_FAIL, // gMonth pre errata, --MM--(z?)
"--01", "--01", // gMonth
"--01Z", "--01Z", // gMonth, UTC
"--01-08:00", "--01-08:00", // gMonth, PDT
"--01-01", "--01-01", // gMonthDay
"--01-01Z", "--01-01Z", // gMonthDay, UTC
"--01-01-08:00", "--01-01-08:00" // gMonthDay, PDT
};
// get a DatatypeFactory
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES_LEXICAL.length; onTestValue = onTestValue + 2) {
if (DEBUG) {
System.err.println("testing value: \"" + TEST_VALUES_LEXICAL[onTestValue] + "\", expecting: \"" + TEST_VALUES_LEXICAL[onTestValue + 1] + "\"");
}
try {
XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(TEST_VALUES_LEXICAL[onTestValue]);
if (DEBUG) {
System.err.println("XMLGregorianCalendar created: \"" + xmlGregorianCalendar.toString() + "\"");
}
// was this expected to fail?
if (TEST_VALUES_LEXICAL[onTestValue + 1].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" is invalid yet it created the XMLGregorianCalendar \""
+ xmlGregorianCalendar.toString() + "\"");
}
// does it have the right value?
if (!TEST_VALUES_LEXICAL[onTestValue + 1].equals(xmlGregorianCalendar.toString())) {
Assert.fail("XMLGregorianCalendar created with \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_LEXICAL[onTestValue + 1] + "\" and has the value \"" + xmlGregorianCalendar.toString() + "\"");
}
// XMLGregorianCalendar created with correct value
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating XMLGregorianCalendar: \"" + exception.toString() + "\"");
}
// was this expected to succed?
if (!TEST_VALUES_LEXICAL[onTestValue + 1].equals(TEST_VALUE_FAIL)) {
Assert.fail("the value \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
}
}
/**
* Test {@link DatatypeFactory.newXMLGregorianCalendar( BigInteger year, int
* month, int day, int hour, int minute, int second, BigDecimal
* fractionalSecond, int timezone)} and
* DatatypeFactory.newXMLGregorianCalendar( int year, int month, int day,
* int hour, int minute, int second, int fractionalSecond, int timezone)} .
*/
@Test
public final void testNewXMLGregorianCalendarYearMonthDayHourMinuteSecondFractionalSecondTimezone() {
final String[][] invalidDates = {
{ "1970", "-1", "1", "0", "0", "0", "0", "0" },
{ "1970", "0", "1", "0", "0", "0", "0", "0" },
{ "1970", "13", "1", "0", "0", "0", "0", "0" },
{ "1970", "1", "-1", "0", "0", "0", "0", "0" },
{ "1970", "1", "0", "0", "0", "0", "0", "0" },
{ "1970", "1", "32", "0", "0", "0", "0", "0" },
{ "1970", "1", "1", "-1", "0", "0", "0", "0" },
// valid per Schema Errata:
// http://www.w3.org/2001/05/xmlschema-errata#e2-45
// {"1970", "1", "1", "24", "0", "0", "0", "0" }
// put in a repeat value to preserve offsets & TCK tests
{ "1970", "1", "1", "0", "-1", "0", "0", "0" }, { "1970", "1", "1", "0", "-1", "0", "0", "0" }, { "1970", "1", "1", "0", "60", "0", "0", "0" },
{ "1970", "1", "1", "0", "0", "-1", "0", "0" }, { "1970", "1", "1", "0", "0", "61", "0", "0" },
{ "1970", "1", "1", "0", "0", "0", "-0.000001", "0" }, { "1970", "1", "1", "0", "0", "0", "1.0001", "0" },
{ "1970", "1", "1", "0", "0", "0", "0", "841" }, { "1970", "1", "1", "0", "0", "0", "0", "-841" }, };
// get a DatatypeFactory
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
// test values, expect failure
for (int valueIndex = 0; valueIndex < invalidDates.length; ++valueIndex) {
try {
if (DEBUG) {
System.err.println("testing DatatypeFactory.newXMLGregorianCalendar(" + invalidDates[valueIndex][0] + ", " + invalidDates[valueIndex][1]
+ ", " + invalidDates[valueIndex][2] + ", " + invalidDates[valueIndex][3] + ", " + invalidDates[valueIndex][4] + ", "
+ invalidDates[valueIndex][5] + ", " + invalidDates[valueIndex][6] + ", " + invalidDates[valueIndex][7] + ")");
}
XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(parseBigInteger(invalidDates[valueIndex][0]),
parseInt(invalidDates[valueIndex][1]), parseInt(invalidDates[valueIndex][2]), parseInt(invalidDates[valueIndex][3]),
parseInt(invalidDates[valueIndex][4]), parseInt(invalidDates[valueIndex][5]), parseBigDecimal(invalidDates[valueIndex][6]),
parseInt(invalidDates[valueIndex][7]));
if (DEBUG) {
System.err.println("created XMLGregorianCalendar: " + xmlGregorianCalendar.toString());
}
// unexpected success, should have failed
Assert.fail("expected IllegalArgumentException " + "for DatatypeFactory.newXMLGregorianCalendar(" + invalidDates[valueIndex][0] + ", "
+ invalidDates[valueIndex][1] + ", " + invalidDates[valueIndex][2] + ", " + invalidDates[valueIndex][3] + ", "
+ invalidDates[valueIndex][4] + ", " + invalidDates[valueIndex][5] + ", " + invalidDates[valueIndex][6] + ", "
+ invalidDates[valueIndex][7] + "). " + "Instead, XMLGregorianCalendar: \"" + xmlGregorianCalendar.toString() + "\" was created.");
} catch (IllegalArgumentException illegalArgumentException) {
// expected failure
if (DEBUG) {
System.err.println("Exception creating XMLGregorianCalendar: " + illegalArgumentException.toString());
}
}
}
// test with all ints
int[] testIndex = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, };
for (int i = 0; i < testIndex.length; ++i) {
int valueIndex = testIndex[i];
try {
if (DEBUG) {
System.err.println("testing DatatypeFactory.newXMLGregorianCalendar(" + invalidDates[valueIndex][0] + ", " + invalidDates[valueIndex][1]
+ ", " + invalidDates[valueIndex][2] + ", " + invalidDates[valueIndex][3] + ", " + invalidDates[valueIndex][4] + ", "
+ invalidDates[valueIndex][5] + ", " + invalidDates[valueIndex][6] + ", " + invalidDates[valueIndex][7] + ")");
}
XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(parseInt(invalidDates[valueIndex][0]),
parseInt(invalidDates[valueIndex][1]), parseInt(invalidDates[valueIndex][2]), parseInt(invalidDates[valueIndex][3]),
parseInt(invalidDates[valueIndex][4]), parseInt(invalidDates[valueIndex][5]), parseInt(invalidDates[valueIndex][6]),
parseInt(invalidDates[valueIndex][7]));
if (DEBUG) {
System.err.println("created XMLGregorianCalendar: " + xmlGregorianCalendar.toString());
}
// unexpected success, should have failed
Assert.fail("expected IllegalArgumentException " + "for DatatypeFactory.newXMLGregorianCalendar(" + invalidDates[valueIndex][0] + ", "
+ invalidDates[valueIndex][1] + ", " + invalidDates[valueIndex][2] + ", " + invalidDates[valueIndex][3] + ", "
+ invalidDates[valueIndex][4] + ", " + invalidDates[valueIndex][5] + ", " + invalidDates[valueIndex][6] + ", "
+ invalidDates[valueIndex][7] + "). " + "Instead, XMLGregorianCalendar: \"" + xmlGregorianCalendar.toString() + "\" was created.");
} catch (IllegalArgumentException illegalArgumentException) {
// expected failure
if (DEBUG) {
System.err.println("Exception creating XMLGregorianCalendar: " + illegalArgumentException.toString());
}
}
}
}
}

View File

@ -0,0 +1,476 @@
/*
* 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.datatype;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.xml.namespace.QName;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/*
* @summary Test Duration.
*/
public class DurationTest {
private final static boolean DEBUG = true;
protected Duration duration = null;
@BeforeMethod
protected void setUp() {
try {
duration = DatatypeFactory.newInstance().newDuration(100);
} catch (DatatypeConfigurationException dce) {
dce.printStackTrace();
Assert.fail("Failed to create instance of DatatypeFactory " + dce.getMessage());
}
}
@Test
public void testDurationSubtract() {
try {
Duration bigDur = DatatypeFactory.newInstance().newDuration(20000);
Duration smallDur = DatatypeFactory.newInstance().newDuration(10000);
if (smallDur.subtract(bigDur).getSign() != -1) {
Assert.fail("smallDur.subtract(bigDur).getSign() is not -1");
}
if (bigDur.subtract(smallDur).getSign() != 1) {
Assert.fail("bigDur.subtract(smallDur).getSign() is not 1");
}
if (smallDur.subtract(smallDur).getSign() != 0) {
Assert.fail("smallDur.subtract(smallDur).getSign() is not 0");
}
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
}
@Test
public void testDurationMultiply() {
int num = 5000; // millisends. 5 seconds
int factor = 2;
try {
Duration dur = DatatypeFactory.newInstance().newDuration(num);
if (dur.multiply(factor).getSeconds() != 10) {
Assert.fail("duration.multiply() return wrong value");
}
// factor is 2*10^(-1)
if (dur.multiply(new BigDecimal(new BigInteger("2"), 1)).getSeconds() != 1) {
Assert.fail("duration.multiply() return wrong value");
}
if (dur.subtract(DatatypeFactory.newInstance().newDuration(1000)).multiply(new BigDecimal(new BigInteger("2"), 1)).getSeconds() != 0) {
Assert.fail("duration.multiply() return wrong value");
}
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
}
@Test
public void testDurationAndCalendar1() {
int year = 1;
int month = 2;
int day = 3;
int hour = 4;
int min = 5;
int sec = 6;
String lexicalRepresentation = "P" + year + "Y" + month + "M" + day + "DT" + hour + "H" + min + "M" + sec + "S";
try {
Duration dur = DatatypeFactory.newInstance().newDuration(lexicalRepresentation);
System.out.println(dur.toString());
AssertJUnit.assertTrue("year should be 1", dur.getYears() == year);
AssertJUnit.assertTrue("month should be 2", dur.getMonths() == month);
AssertJUnit.assertTrue("day should be 3", dur.getDays() == day);
AssertJUnit.assertTrue("hour should be 4", dur.getHours() == hour);
AssertJUnit.assertTrue("minute should be 5", dur.getMinutes() == min);
AssertJUnit.assertTrue("second should be 6", dur.getSeconds() == sec);
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
}
@Test
public void testDurationAndCalendar2() {
try {
AssertJUnit.assertTrue("10.00099S means 10 sec since it will be rounded to zero", DatatypeFactory.newInstance().newDuration("PT10.00099S")
.getTimeInMillis(new Date()) == 10000);
AssertJUnit.assertTrue("10.00099S means 10 sec since it will be rounded to zero", DatatypeFactory.newInstance().newDuration("-PT10.00099S")
.getTimeInMillis(new Date()) == -10000);
AssertJUnit.assertTrue("10.00099S means 10 sec since it will be rounded to zero", DatatypeFactory.newInstance().newDuration("PT10.00099S")
.getTimeInMillis(new GregorianCalendar()) == 10000);
AssertJUnit.assertTrue("10.00099S means 10 sec since it will be rounded to zero", DatatypeFactory.newInstance().newDuration("-PT10.00099S")
.getTimeInMillis(new GregorianCalendar()) == -10000);
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
}
@Test
public void testDurationAndCalendar3() {
try {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.SECOND, 59);
DatatypeFactory.newInstance().newDuration(10000).addTo(cal);
AssertJUnit.assertTrue("sec will be 9", cal.get(Calendar.SECOND) == 9);
Date date = new Date();
date.setSeconds(59);
DatatypeFactory.newInstance().newDuration(10000).addTo(date);
AssertJUnit.assertTrue("sec will be 9", date.getSeconds() == 9);
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
}
@Test
public void testEqualsWithDifferentObjectParam() {
AssertJUnit.assertFalse("equals method should return false for any object other than Duration", duration.equals(new Integer(0)));
}
@Test
public void testEqualsWithNullObjectParam() {
AssertJUnit.assertFalse("equals method should return false for null parameter", duration.equals(null));
}
@Test
public void testEqualsWithEqualObjectParam() {
try {
AssertJUnit.assertTrue("equals method is expected to return true", duration.equals(DatatypeFactory.newInstance().newDuration(100)));
} catch (DatatypeConfigurationException dce) {
dce.printStackTrace();
Assert.fail("Failed to create instance of DatatypeFactory " + dce.getMessage());
}
}
/**
* Inspired by CR 5077522 Duration.compare makes mistakes for some values.
*/
@Test
public void testCompareWithInderterminateRelation() {
final String[][] partialOrder = { // partialOrder
{ "P1Y", "<>", "P365D" }, { "P1Y", "<>", "P366D" }, { "P1M", "<>", "P28D" }, { "P1M", "<>", "P29D" }, { "P1M", "<>", "P30D" }, { "P1M", "<>", "P31D" },
{ "P5M", "<>", "P150D" }, { "P5M", "<>", "P151D" }, { "P5M", "<>", "P152D" }, { "P5M", "<>", "P153D" }, { "PT2419200S", "<>", "P1M" },
{ "PT2678400S", "<>", "P1M" }, { "PT31536000S", "<>", "P1Y" }, { "PT31622400S", "<>", "P1Y" }, { "PT525600M", "<>", "P1Y" },
{ "PT527040M", "<>", "P1Y" }, { "PT8760H", "<>", "P1Y" }, { "PT8784H", "<>", "P1Y" }, { "P365D", "<>", "P1Y" }, };
DatatypeFactory df = null;
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException ex) {
ex.printStackTrace();
Assert.fail(ex.toString());
}
boolean compareErrors = false;
for (int valueIndex = 0; valueIndex < partialOrder.length; ++valueIndex) {
Duration duration1 = df.newDuration(partialOrder[valueIndex][0]);
Duration duration2 = df.newDuration(partialOrder[valueIndex][2]);
int cmp = duration1.compare(duration2);
int expected = ">".equals(partialOrder[valueIndex][1]) ? DatatypeConstants.GREATER
: "<".equals(partialOrder[valueIndex][1]) ? DatatypeConstants.LESSER : "==".equals(partialOrder[valueIndex][1]) ? DatatypeConstants.EQUAL
: DatatypeConstants.INDETERMINATE;
// just note any errors, do not fail until all cases have been
// tested
if (expected != cmp) {
compareErrors = true;
System.err.println("returned " + cmp2str(cmp) + " for durations \'" + duration1 + "\' and " + duration2 + "\', but expected "
+ cmp2str(expected));
}
}
if (compareErrors) {
// TODO; fix bug, these tests should pass
if (false) {
Assert.fail("Errors in comparing indeterminate relations, see Stderr");
} else {
System.err.println("Please fix this bug: " + "Errors in comparing indeterminate relations, see Stderr");
}
}
}
public static String cmp2str(int cmp) {
return cmp == DatatypeConstants.LESSER ? "LESSER" : cmp == DatatypeConstants.GREATER ? "GREATER" : cmp == DatatypeConstants.EQUAL ? "EQUAL"
: cmp == DatatypeConstants.INDETERMINATE ? "INDETERMINATE" : "UNDEFINED";
}
/**
* Inspired by CR 6238220 javax.xml.datatype.Duration has no clear
* description concerning return values range.
*/
@Test
public void testNormalizedReturnValues() throws Exception {
final Object[] TEST_VALUES = {
// test 61 seconds -> 1 minute, 1 second
true, // isPositive,
BigInteger.ZERO, // years,
BigInteger.ZERO, // months
BigInteger.ZERO, // days
BigInteger.ZERO, // hours
BigInteger.ZERO, // minutes
new BigDecimal(61), // seconds
61000L, // durationInMilliSeconds,
"P0Y0M0DT0H0M61S", // lexicalRepresentation
// test - 61 seconds -> - 1 minute, 1 second
false, // isPositive,
BigInteger.ZERO, // years,
BigInteger.ZERO, // months
BigInteger.ZERO, // days
BigInteger.ZERO, // hours
BigInteger.ZERO, // minutes
new BigDecimal(61), // seconds
61000L, // durationInMilliSeconds,
"-P0Y0M0DT0H0M61S", // lexicalRepresentation
};
final Object[] NORM_VALUES = {
// test 61 seconds -> 1 minute, 1 second
true, // normalized isPositive,
BigInteger.ZERO, // normalized years,
BigInteger.ZERO, // normalized months
BigInteger.ZERO, // normalized days
BigInteger.ZERO, // normalized hours
BigInteger.ONE, // normalized minutes
BigDecimal.ONE, // normalized seconds
61000L, // normalized durationInMilliSeconds,
"P0Y0M0DT0H1M1.000S", // normalized lexicalRepresentation
// test - 61 seconds -> - 1 minute, 1 second
false, // normalized isPositive,
BigInteger.ZERO, // normalized years,
BigInteger.ZERO, // normalized months
BigInteger.ZERO, // normalized days
BigInteger.ZERO, // normalized hours
BigInteger.ONE, // normalized minutes
BigDecimal.ONE, // normalized seconds
61000L, // normalized durationInMilliSeconds,
"-P0Y0M0DT0H1M1.000S" // normalized lexicalRepresentation
};
for (int onValue = 0; onValue < TEST_VALUES.length; onValue += 9) {
newDurationTester(((Boolean) TEST_VALUES[onValue]).booleanValue(), // isPositive,
((Boolean) NORM_VALUES[onValue]).booleanValue(), // normalized
// isPositive,
(BigInteger) TEST_VALUES[onValue + 1], // years,
(BigInteger) NORM_VALUES[onValue + 1], // normalized years,
(BigInteger) TEST_VALUES[onValue + 2], // months
(BigInteger) NORM_VALUES[onValue + 2], // normalized months
(BigInteger) TEST_VALUES[onValue + 3], // days
(BigInteger) NORM_VALUES[onValue + 3], // normalized days
(BigInteger) TEST_VALUES[onValue + 4], // hours
(BigInteger) NORM_VALUES[onValue + 4], // normalized hours
(BigInteger) TEST_VALUES[onValue + 5], // minutes
(BigInteger) NORM_VALUES[onValue + 5], // normalized minutes
(BigDecimal) TEST_VALUES[onValue + 6], // seconds
(BigDecimal) NORM_VALUES[onValue + 6], // normalized seconds
((Long) TEST_VALUES[onValue + 7]).longValue(), // durationInMilliSeconds,
((Long) NORM_VALUES[onValue + 7]).longValue(), // normalized
// durationInMilliSeconds,
(String) TEST_VALUES[onValue + 8], // lexicalRepresentation
(String) NORM_VALUES[onValue + 8]); // normalized
// lexicalRepresentation
newDurationDayTimeTester(((Boolean) TEST_VALUES[onValue]).booleanValue(), // isPositive,
((Boolean) NORM_VALUES[onValue]).booleanValue(), // normalized
// isPositive,
BigInteger.ZERO, // years,
BigInteger.ZERO, // normalized years,
BigInteger.ZERO, // months
BigInteger.ZERO, // normalized months
(BigInteger) TEST_VALUES[onValue + 3], // days
(BigInteger) NORM_VALUES[onValue + 3], // normalized days
(BigInteger) TEST_VALUES[onValue + 4], // hours
(BigInteger) NORM_VALUES[onValue + 4], // normalized hours
(BigInteger) TEST_VALUES[onValue + 5], // minutes
(BigInteger) NORM_VALUES[onValue + 5], // normalized minutes
(BigDecimal) TEST_VALUES[onValue + 6], // seconds
(BigDecimal) NORM_VALUES[onValue + 6], // normalized seconds
((Long) TEST_VALUES[onValue + 7]).longValue(), // durationInMilliSeconds,
((Long) NORM_VALUES[onValue + 7]).longValue(), // normalized
// durationInMilliSeconds,
(String) TEST_VALUES[onValue + 8], // lexicalRepresentation
(String) NORM_VALUES[onValue + 8]); // normalized
// lexicalRepresentation
}
}
private void newDurationTester(boolean isPositive, boolean normalizedIsPositive, BigInteger years, BigInteger normalizedYears, BigInteger months,
BigInteger normalizedMonths, BigInteger days, BigInteger normalizedDays, BigInteger hours, BigInteger normalizedHours, BigInteger minutes,
BigInteger normalizedMinutes, BigDecimal seconds, BigDecimal normalizedSeconds, long durationInMilliSeconds, long normalizedDurationInMilliSeconds,
String lexicalRepresentation, String normalizedLexicalRepresentation) {
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException ex) {
ex.printStackTrace();
Assert.fail(ex.toString());
}
// create 4 Durations using the 4 different constructors
Duration durationBigInteger = datatypeFactory.newDuration(isPositive, years, months, days, hours, minutes, seconds);
durationAssertEquals(durationBigInteger, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);
Duration durationInt = datatypeFactory.newDuration(isPositive, years.intValue(), months.intValue(), days.intValue(), hours.intValue(),
minutes.intValue(), seconds.intValue());
durationAssertEquals(durationInt, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);
Duration durationMilliseconds = datatypeFactory.newDuration(durationInMilliSeconds);
durationAssertEquals(durationMilliseconds, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);
Duration durationLexical = datatypeFactory.newDuration(lexicalRepresentation);
durationAssertEquals(durationLexical, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);
}
private void newDurationDayTimeTester(boolean isPositive, boolean normalizedIsPositive, BigInteger years, BigInteger normalizedYears, BigInteger months,
BigInteger normalizedMonths, BigInteger days, BigInteger normalizedDays, BigInteger hours, BigInteger normalizedHours, BigInteger minutes,
BigInteger normalizedMinutes, BigDecimal seconds, BigDecimal normalizedSeconds, long durationInMilliSeconds, long normalizedDurationInMilliSeconds,
String lexicalRepresentation, String normalizedLexicalRepresentation) {
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException ex) {
ex.printStackTrace();
Assert.fail(ex.toString());
}
// create 4 dayTime Durations using the 4 different constructors
Duration durationDayTimeBigInteger = datatypeFactory.newDurationDayTime(isPositive, days, hours, minutes, seconds.toBigInteger());
durationAssertEquals(durationDayTimeBigInteger, DatatypeConstants.DURATION_DAYTIME, normalizedIsPositive, normalizedYears.intValue(),
normalizedMonths.intValue(), normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);
/*
* Duration durationDayTimeInt = datatypeFactory.newDurationDayTime(
* isPositive, days.intValue(), hours.intValue(), minutes.intValue(),
* seconds.intValue()); Duration durationDayTimeMilliseconds =
* datatypeFactory.newDurationDayTime( durationInMilliSeconds); Duration
* durationDayTimeLexical = datatypeFactory.newDurationDayTime(
* lexicalRepresentation);
* Duration durationYearMonthBigInteger =
* datatypeFactory.newDurationYearMonth( isPositive, years, months);
* Duration durationYearMonthInt = datatypeFactory.newDurationYearMonth(
* isPositive, years.intValue(), months.intValue()); Duration
* durationYearMonthMilliseconds = datatypeFactory.newDurationYearMonth(
* durationInMilliSeconds); Duration durationYearMonthLexical =
* datatypeFactory.newDurationYearMonth( lexicalRepresentation) ;
*/
}
private void durationAssertEquals(Duration duration, QName xmlSchemaType, boolean isPositive, int years, int months, int days, int hours, int minutes,
int seconds, long milliseconds, String lexical) {
final TimeZone GMT = TimeZone.getTimeZone("GMT");
final GregorianCalendar EPOCH = new GregorianCalendar(GMT);
EPOCH.clear();
if (DEBUG) {
System.out.println("Testing Duration: " + duration.toString());
}
// sign
if (DEBUG) {
boolean actual = (duration.getSign() == 1) ? true : false;
System.out.println("sign:");
System.out.println(" expected: \"" + isPositive + "\"");
System.out.println(" actual: \"" + actual + "\"");
}
if (DEBUG) {
System.out.println("years:");
System.out.println(" expected: \"" + years + "\"");
System.out.println(" actual: \"" + duration.getYears() + "\"");
}
if (DEBUG) {
System.out.println("months:");
System.out.println(" expected: \"" + months + "\"");
System.out.println(" actual: \"" + duration.getMonths() + "\"");
}
if (DEBUG) {
System.out.println("days:");
System.out.println(" expected: \"" + days + "\"");
System.out.println(" actual: \"" + duration.getDays() + "\"");
}
if (DEBUG) {
System.out.println("hours:");
System.out.println(" expected: \"" + hours + "\"");
System.out.println(" actual: \"" + duration.getHours() + "\"");
}
if (DEBUG) {
System.out.println("minutes:");
System.out.println(" expected: \"" + minutes + "\"");
System.out.println(" actual: \"" + duration.getMinutes() + "\"");
}
if (DEBUG) {
System.out.println("seconds:");
System.out.println(" expected: \"" + seconds + "\"");
System.out.println(" actual: \"" + duration.getSeconds() + "\"");
}
if (DEBUG) {
System.out.println("milliseconds:");
System.out.println(" expected: \"" + milliseconds + "\"");
System.out.println(" actual: \"" + duration.getTimeInMillis(EPOCH) + "\"");
}
if (DEBUG) {
System.out.println("lexical:");
System.out.println(" expected: \"" + lexical + "\"");
System.out.println(" actual: \"" + duration.toString() + "\"");
}
}
}

View File

@ -0,0 +1,76 @@
/*
* 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.datatype;
import java.net.URL;
import java.net.URLClassLoader;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @summary Test Classloader for DatatypeFactory.
*/
public class FactoryFindTest {
boolean myClassLoaderUsed = false;
public FactoryFindTest(String name) {
}
@Test
public void testFactoryFind() {
try {
// System.setProperty("jaxp.debug", "true");
DatatypeFactory factory = DatatypeFactory.newInstance();
Assert.assertTrue(factory.getClass().getClassLoader() == null);
Thread.currentThread().setContextClassLoader(null);
factory = DatatypeFactory.newInstance();
Assert.assertTrue(factory.getClass().getClassLoader() == null);
Thread.currentThread().setContextClassLoader(new MyClassLoader());
factory = DatatypeFactory.newInstance();
if (System.getSecurityManager() == null)
Assert.assertTrue(myClassLoaderUsed);
else
Assert.assertFalse(myClassLoaderUsed);
} catch (Exception ex) {
}
}
class MyClassLoader extends URLClassLoader {
public MyClassLoader() {
super(new URL[0]);
}
public Class loadClass(String name) throws ClassNotFoundException {
myClassLoaderUsed = true;
return super.loadClass(name);
}
}
}

View File

@ -0,0 +1,219 @@
/*
* 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.datatype;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/*
* @summary Test XMLGregorianCalendar.
*/
public class XMLGregorianCalendarTest {
private static final boolean DEBUG = false;
private static final int TEST_VALUE_FAIL = 0;
private static final int TEST_VALUE_PASS = 1;
private XMLGregorianCalendar calendar;
@BeforeMethod
protected void setUp() {
try {
calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar();
} catch (DatatypeConfigurationException dce) {
dce.printStackTrace();
Assert.fail("Failed to create instance of DatatypeFactory " + dce.getMessage());
}
}
@Test
public final void testSetTime() {
/**
* Hour, minute, second values to test and expected result.
*/
final int[] TEST_VALUES = { 24, 0, 0, TEST_VALUE_PASS, 24, 1, 0, TEST_VALUE_FAIL, 24, 0, 1, TEST_VALUE_FAIL, 24, DatatypeConstants.FIELD_UNDEFINED, 0,
TEST_VALUE_FAIL, 24, 0, DatatypeConstants.FIELD_UNDEFINED, TEST_VALUE_FAIL };
// create DatatypeFactory
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
// create XMLGregorianCalendar
XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar();
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES.length; onTestValue = onTestValue + 4) {
if (DEBUG) {
System.err.println("testing values: (" + TEST_VALUES[onTestValue] + ", " + TEST_VALUES[onTestValue + 1] + ", " + TEST_VALUES[onTestValue + 2]
+ ") expected (0=fail, 1=pass): " + TEST_VALUES[onTestValue + 3]);
}
try {
// set time
xmlGregorianCalendar.setTime(TEST_VALUES[onTestValue], TEST_VALUES[onTestValue + 1], TEST_VALUES[onTestValue + 2]);
if (DEBUG) {
System.err.println("XMLGregorianCalendar created: \"" + xmlGregorianCalendar.toString() + "\"");
}
// was this expected to fail?
if (TEST_VALUES[onTestValue + 3] == TEST_VALUE_FAIL) {
Assert.fail("the values: (" + TEST_VALUES[onTestValue] + ", " + TEST_VALUES[onTestValue + 1] + ", " + TEST_VALUES[onTestValue + 2]
+ ") are invalid, " + "yet it created the XMLGregorianCalendar \"" + xmlGregorianCalendar.toString() + "\"");
}
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating XMLGregorianCalendar: \"" + exception.toString() + "\"");
}
// was this expected to succed?
if (TEST_VALUES[onTestValue + 3] == TEST_VALUE_PASS) {
Assert.fail("the values: (" + TEST_VALUES[onTestValue] + ", " + TEST_VALUES[onTestValue + 1] + ", " + TEST_VALUES[onTestValue + 2]
+ ") are valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
}
}
@Test
public final void testSetHour() {
/**
* Hour values to test and expected result.
*/
final int[] TEST_VALUES = {
// setTime(H, M, S), hour override, expected result
0, 0, 0, 0, TEST_VALUE_PASS, 0, 0, 0, 23, TEST_VALUE_PASS, 0, 0, 0, 24, TEST_VALUE_PASS,
// creates invalid state
0, 0, 0, DatatypeConstants.FIELD_UNDEFINED, TEST_VALUE_FAIL,
// violates Schema Errata
0, 0, 1, 24, TEST_VALUE_FAIL };
// create DatatypeFactory
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
// create XMLGregorianCalendar
XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar();
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES.length; onTestValue = onTestValue + 5) {
if (DEBUG) {
System.err.println("testing values: (" + TEST_VALUES[onTestValue] + ", " + TEST_VALUES[onTestValue + 1] + ", " + TEST_VALUES[onTestValue + 2]
+ ", " + TEST_VALUES[onTestValue + 3] + ") expected (0=fail, 1=pass): " + TEST_VALUES[onTestValue + 4]);
}
try {
// set time to known valid value
xmlGregorianCalendar.setTime(TEST_VALUES[onTestValue], TEST_VALUES[onTestValue + 1], TEST_VALUES[onTestValue + 2]);
// now explicitly set hour
xmlGregorianCalendar.setHour(TEST_VALUES[onTestValue + 3]);
if (DEBUG) {
System.err.println("XMLGregorianCalendar created: \"" + xmlGregorianCalendar.toString() + "\"");
}
// was this expected to fail?
if (TEST_VALUES[onTestValue + 4] == TEST_VALUE_FAIL) {
Assert.fail("the values: (" + TEST_VALUES[onTestValue] + ", " + TEST_VALUES[onTestValue + 1] + ", " + TEST_VALUES[onTestValue + 2] + ", "
+ TEST_VALUES[onTestValue + 3] + ") are invalid, " + "yet it created the XMLGregorianCalendar \"" + xmlGregorianCalendar.toString()
+ "\"");
}
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating XMLGregorianCalendar: \"" + exception.toString() + "\"");
}
// was this expected to succed?
if (TEST_VALUES[onTestValue + 4] == TEST_VALUE_PASS) {
Assert.fail("the values: (" + TEST_VALUES[onTestValue] + ", " + TEST_VALUES[onTestValue + 1] + ", " + TEST_VALUES[onTestValue + 2] + ", "
+ TEST_VALUES[onTestValue + 3] + ") are valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
}
}
@Test
public void testEqualsWithDifferentObjectParam() {
Assert.assertFalse(calendar.equals(new Integer(0)), "equals method should return false for any object other" + " than XMLGregorianCalendar");
}
@Test
public void testEqualsWithNullObjectParam() {
Assert.assertFalse(calendar.equals(null), "equals method should return false for null parameter");
}
@Test
public void testEqualsWithEqualObjectParam() {
try {
Assert.assertTrue(calendar.equals(DatatypeFactory.newInstance().newXMLGregorianCalendar()), "equals method is expected to return true");
} catch (DatatypeConfigurationException dce) {
dce.printStackTrace();
Assert.fail("Failed to create instance of DatatypeFactory " + dce.getMessage());
}
}
@Test
public void testToString() {
try {
String inputDateTime = "2006-10-23T22:15:01.000000135+08:00";
DatatypeFactory factory = DatatypeFactory.newInstance();
XMLGregorianCalendar calendar = factory.newXMLGregorianCalendar(inputDateTime);
String toStr = calendar.toString();
Assert.assertTrue(toStr.indexOf("E") == -1, "String value cannot contain exponent");
} catch (DatatypeConfigurationException dce) {
dce.printStackTrace();
Assert.fail("Failed to create instance of DatatypeFactory " + dce.getMessage());
}
}
}

View File

@ -0,0 +1,63 @@
/*
* 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;
import java.io.File;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.helpers.DefaultHandler;
/*
* @bug 4674384
* @summary Test large maxOccurs.
*/
public class Bug4674384_MAX_OCCURS_Test {
@Test
public final void testLargeMaxOccurs() {
String XML_FILE_NAME = "Bug4674384_MAX_OCCURS_Test.xml";
try {
// create and initialize the parser
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser parser = spf.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
File xmlFile = new File(getClass().getResource(XML_FILE_NAME).getPath());
parser.parse(xmlFile, new DefaultHandler());
} catch (Exception e) {
System.err.println("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.");
e.printStackTrace();
Assert.fail("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs. " + e.getMessage());
}
System.out.println("Success: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.");
}
}

View File

@ -0,0 +1,8 @@
<?xml version="1.0"?>
<test:a
xmlns:test="test"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="test Bug4674384_MAX_OCCURS_Test.xsd">
<b>1</b>
<b>2</b>
</test:a>

View File

@ -0,0 +1,15 @@
<?xml version="1.0"?>
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="test"
targetNamespace="test">
<xsd:element name="a" type="A"/>
<xsd:complexType name="A">
<xsd:sequence>
<xsd:element name="b" type="xsd:string" maxOccurs="3000"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>

View File

@ -0,0 +1,70 @@
/*
* 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;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import util.DraconianErrorHandler;
/*
* @bug 4934208
* @summary Test SAXParser can parse keyref constraint with a selector that is a union xpath expression selecting a node and its child.
*/
public class Bug4934208 {
@Test
public void test1() throws Exception {
parse(new InputSource(Bug4934208.class.getResourceAsStream("test1.xml")));
}
@Test
public void test2() throws Exception {
try {
parse(new InputSource(Bug4934208.class.getResourceAsStream("test2.xml")));
} catch (SAXException e) {
Assert.assertTrue(e.getMessage().startsWith("cvc-complex-type.2.4.a"));
}
}
private void parse(InputSource is) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser parser = spf.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", Bug4934208.class.getResourceAsStream("test.xsd"));
XMLReader r = parser.getXMLReader();
r.setErrorHandler(new DraconianErrorHandler());
r.parse(is);
}
}

View File

@ -0,0 +1,97 @@
/*
* 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;
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
/*
* @bug 4967002
* @summary Test DocumentBuilderFactory.newDocumentBuilder() throws ParserConfigurationException
* when it uses the "http://java.sun.com/xml/jaxp/properties/schemaSource" property
* and/or the "http://java.sun.com/xml/jaxp/properties/schemaLanguage" property
* in conjunction with setting a Schema object.
*/
public class Bug4967002 {
String schemaSource = "<?xml version='1.0'?>\n" + "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>\n" + " <xsd:element name='test101'>\n"
+ " <xsd:complexType>\n" + " <xsd:attribute name='attr'/>\n" + " <xsd:attribute name='attr2' default='DEF'/>\n"
+ " </xsd:complexType>\n" + " </xsd:element>\n" + "</xsd:schema>\n";
Schema createSchema() {
SchemaFactory schFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema sch = schFactory.newSchema(new StreamSource(new StringReader(schemaSource)));
return sch;
} catch (Exception se) {
throw new IllegalStateException("No Schema : " + se);
}
}
@Test
public void test1() {
setAttr(true);
}
@Test
public void test2() {
setAttr(false);
}
void setAttr(boolean setSrc) {
DocumentBuilderFactory docBFactory = DocumentBuilderFactory.newInstance();
Schema sch = createSchema();
docBFactory.setSchema(sch);
docBFactory.setNamespaceAware(true);
docBFactory.setValidating(true);
final String aSchemaLanguage = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
final String aSchemaSource = "http://java.sun.com/xml/jaxp/properties/schemaSource";
docBFactory.setAttribute(aSchemaLanguage, "http://www.w3.org/2001/XMLSchema");
// System.out.println("---- Set schemaLanguage: " +
// docBFactory.getAttribute(aSchemaLanguage));
if (setSrc) {
docBFactory.setAttribute(aSchemaSource, new InputSource(new StringReader(schemaSource)));
// System.out.println("---- Set schemaSource: " +
// docBFactory.getAttribute(aSchemaSource));
}
try {
docBFactory.newDocumentBuilder();
Assert.fail("ParserConfigurationException expected");
} catch (ParserConfigurationException pce) {
return; // success
}
}
}

View File

@ -0,0 +1,64 @@
/*
* 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;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/*
* @bug 4985486
* @summary Test SAXParser can parse large characters(more than 10000).
*/
public class Bug4985486 {
@Test
public void test1() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
System.out.println(spf.getClass().getName());
spf.setNamespaceAware(true);
spf.newSAXParser().parse(Bug4985486.class.getResourceAsStream("Bug4985486.xml"), new Handler());
}
private class Handler extends DefaultHandler {
StringBuffer buf = new StringBuffer();
public void characters(char[] ch, int start, int length) throws SAXException {
buf.append(ch, start, length);
}
public void endDocument() throws SAXException {
String contents = buf.toString();
Assert.assertTrue(contents.endsWith("[END]"));
while (contents.length() >= 10) {
Assert.assertTrue(contents.startsWith("0123456789"));
contents = contents.substring(10);
}
}
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,52 @@
/*
* 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;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.annotations.Test;
/*
* @bug 4991020
* @summary Test XPath like "node_name/." can be parsed.
*/
public class Bug4991020 {
protected static SAXParser createParser() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser parser = spf.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
return parser;
}
@Test
public void test1() throws Exception {
SAXParser parser = createParser();
parser.parse(Bug4991020.class.getResource("Bug4991020.xml").toExternalForm(), new util.DraconianErrorHandler());
}
}

View File

@ -0,0 +1,5 @@
<?xml version="1.0"?>
<test:root xmlns:test="test"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="test Bug4991020.xsd"
><child>123</child></test:root>

View File

@ -0,0 +1,16 @@
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test">
<xsd:element name="root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="child" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:key name="key1">
<xsd:selector xpath="."/>
<xsd:field xpath="child/."/>
</xsd:key>
</xsd:element>
</xsd:schema>

View File

@ -0,0 +1,52 @@
/*
* 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;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.annotations.Test;
/*
* @bug 4991946
* @summary Can parse the element type is anyType in the schema and is substituted by the simple type via the 'xsi:type' attribute in xml document.
*/
public class Bug4991946 {
protected static SAXParser createParser() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser parser = spf.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
return parser;
}
@Test
public void test1() throws Exception {
SAXParser parser = createParser();
parser.parse(Bug4991946.class.getResource("Bug4991946.xml").toExternalForm(), new util.DraconianErrorHandler());
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0"?>
<test:root xmlns:test="test"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="test Bug4991946.xsd"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<child xsi:type="xsd:string">123</child>
</test:root>

View File

@ -0,0 +1,16 @@
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="test">
<xsd:element name="root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="child" type="xsd:anyType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:key name="key1">
<xsd:selector xpath="."/>
<xsd:field xpath="child"/>
</xsd:key>
</xsd:element>
</xsd:schema>

View File

@ -0,0 +1,73 @@
/*
* 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;
import javax.xml.validation.SchemaFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/*
* @bug 5010072
* @summary Test SchemaFactory throws SAXException if xpath is "@".
*/
public class Bug5010072 {
protected static class ErrorHandler extends DefaultHandler {
public int errorCounter = 0;
public void error(SAXParseException e) throws SAXException {
System.err.println("Error: " + "[[" + e.getPublicId() + "][" + e.getSystemId() + "]]" + "[[" + e.getLineNumber() + "][" + e.getColumnNumber()
+ "]]" + e);
errorCounter++;
throw e;
}
public void fatalError(SAXParseException e) throws SAXException {
System.err.println("Fatal Error: " + e);
errorCounter++;
}
}
@Test
public void test1() throws Exception {
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
ErrorHandler errorHandler = new ErrorHandler();
schemaFactory.setErrorHandler(errorHandler);
try {
schemaFactory.newSchema(Bug5010072.class.getResource("Bug5010072.xsd"));
Assert.fail("should fail to compile");
} catch (SAXException e) {
; // as expected
}
}
}

View File

@ -0,0 +1,14 @@
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="root">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="tid" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:unique id="foo123" name="uid">
<xsd:selector xpath=".//tid"/>
<xsd:field xpath="@"/>
</xsd:unique>
</xsd:element>
</xsd:schema>

View File

@ -0,0 +1,85 @@
/*
* 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;
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/*
* @bug 5025825
* @summary Test if SAXParserFactory set a Schema object, when SAXParser sets "http://java.sun.com/xml/jaxp/properties/schemaSource" property
* and/or "http://java.sun.com/xml/jaxp/properties/schemaLanguage" property, it shall throw SAXException.
*/
public class Bug5025825 {
String schemaSource = "<?xml version='1.0'?>\n" + "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>\n" + " <xsd:element name='test101'>\n"
+ " <xsd:complexType>\n" + " <xsd:attribute name='attr'/>\n" + " <xsd:attribute name='attr2' default='DEF'/>\n"
+ " </xsd:complexType>\n" + " </xsd:element>\n" + "</xsd:schema>\n";
private Schema createSchema() throws SAXException {
SchemaFactory schFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
return schFactory.newSchema(new StreamSource(new StringReader(schemaSource)));
}
@Test
public void test1() throws Exception {
Schema sch = createSchema();
Assert.assertNotNull(sch);
SAXParserFactory spFactory = SAXParserFactory.newInstance();
spFactory.setNamespaceAware(true);
spFactory.setValidating(true);
spFactory.setSchema(sch);
SAXParser sParser = spFactory.newSAXParser();
final String aSchemaLanguage = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
final String aSchemaSource = "http://java.sun.com/xml/jaxp/properties/schemaSource";
try {
sParser.setProperty(aSchemaLanguage, "http://www.w3.org/2001/XMLSchema");
Assert.fail("---- Set schemaLanguage: " + sParser.getProperty(aSchemaLanguage));
} catch (SAXException e) {
; // as expected
}
try {
sParser.setProperty(aSchemaSource, new InputSource(new StringReader(schemaSource)));
Assert.fail("---- Set schemaSource: " + sParser.getProperty(aSchemaSource));
} catch (SAXException e) {
; // as expected
}
}
}

View File

@ -0,0 +1,380 @@
/*
* 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;
import java.io.File;
import java.io.InputStream;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.xml.sax.SAXParseException;
/*
* @bug 6309988
* @summary Test elementAttributeLimit, maxOccurLimit, entityExpansionLimit.
*/
public class Bug6309988 {
DocumentBuilderFactory dbf = null;
static boolean _isSecureMode = false;
static {
if (System.getSecurityManager() != null) {
_isSecureMode = true;
System.out.println("Security Manager is present");
} else {
System.out.println("Security Manager is NOT present");
}
}
/*
* Given XML document has more than 10000 attributes. Exception is expected
*/
@Test
public void testDOMParserElementAttributeLimit() {
try {
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = dbf.newDocumentBuilder();
Document doc = parser.parse(this.getClass().getResourceAsStream("DosTest.xml"));
Assert.fail("SAXParserException is expected, as given XML document contains more than 10000 attributes");
} catch (SAXParseException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
Assert.fail("Exception " + e.getMessage());
}
}
/*
* Given XML document has more than 10000 attributes. It should report an
* error.
*/
@Test
public void testDOMNSParserElementAttributeLimit() {
try {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder parser = dbf.newDocumentBuilder();
Document doc = parser.parse(this.getClass().getResourceAsStream("DosTest.xml"));
Assert.fail("SAXParserException is expected, as given XML document contains more than 10000 attributes");
} catch (SAXParseException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
Assert.fail("Exception " + e.getMessage());
}
}
/*
* Given XML document has more than 10000 attributes. Parsing this XML
* document in non-secure mode, should not report any error.
*/
@Test
public void testDOMNSParserElementAttributeLimitWithoutSecureProcessing() {
if (_isSecureMode)
return; // jaxp secure feature can not be turned off when security
// manager is present
try {
dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
dbf.setNamespaceAware(true);
DocumentBuilder parser = dbf.newDocumentBuilder();
Document doc = parser.parse(this.getClass().getResourceAsStream("DosTest.xml"));
} catch (SAXParseException e) {
Assert.fail(e.getMessage());
} catch (Exception e) {
Assert.fail("Exception " + e.getMessage());
}
}
/*
* Before 8014530: Given XML document has 3 attributes and System property
* is set to 2. Parsing this XML document in non-secure mode, should not
* report an error.
* After 8014530: System properties will override FSP, the result of this
* test should be the same as
* testSystemElementAttributeLimitWithSecureProcessing
*/
@Test
public void testSystemElementAttributeLimitWithoutSecureProcessing() {
if (_isSecureMode)
return; // jaxp secure feature can not be turned off when security
// manager is present
try {
dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
dbf.setNamespaceAware(true);
System.setProperty("elementAttributeLimit", "2");
DocumentBuilder parser = dbf.newDocumentBuilder();
Document doc = parser.parse(this.getClass().getResourceAsStream("DosTest3.xml"));
Assert.fail("SAXParserException is expected, as given XML document contains more than 2 attributes");
} catch (Exception e) {
String errMsg = e.getMessage();
Throwable cause = e.getCause();
if (cause != null) {
errMsg += cause.getMessage();
}
if (errMsg.contains("JAXP0001")) {
// expected
} else {
Assert.fail("Unexpected error: " + e.getMessage());
}
} finally {
System.clearProperty("elementAttributeLimit");
}
}
/*
* Given XML document has 3 attributes and System property is set to 2.
* Parsing this XML document in secure mode, should report an error.
*/
@Test
public void testSystemElementAttributeLimitWithSecureProcessing() {
try {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
System.setProperty("elementAttributeLimit", "2");
DocumentBuilder parser = dbf.newDocumentBuilder();
Document doc = parser.parse(this.getClass().getResourceAsStream("DosTest3.xml"));
Assert.fail("SAXParserException is expected, as given XML document contains more than 2 attributes");
} catch (SAXParseException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
Assert.fail("Exception " + e.getMessage());
} finally {
System.setProperty("elementAttributeLimit", "");
}
}
/*
* Default value for secure processing feature should be true.
*/
@Test
public void testDOMSecureProcessingDefaultValue() {
try {
dbf = DocumentBuilderFactory.newInstance();
Assert.assertTrue(dbf.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING), "Default value for secureProcessing feature should be true");
} catch (Exception e) {
Assert.fail("Exception " + e.getMessage());
}
}
/*
* Default value for secure processing feature should be true.
*/
@Test
public void testSAXSecureProcessingDefaultValue() {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
Assert.assertTrue(spf.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING), "Default value for secureProcessing feature should be true");
} catch (Exception e) {
Assert.fail("Exception " + e.getMessage());
}
}
/*
* This method sets system property for maxOccurLimit=2 and secure process
* feature is off. Given doument contains more than 2 elements and hence an
* error should be reported.
*/
@Test
public void testSystemMaxOccurLimitWithoutSecureProcessing() {
if (_isSecureMode)
return; // jaxp secure feature can not be turned off when security
// manager is present
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
spf.setValidating(true);
System.setProperty("maxOccurLimit", "2");
// Set the properties for Schema Validation
String SCHEMA_LANG = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
String SCHEMA_TYPE = "http://www.w3.org/2001/XMLSchema";
// Get the Schema location as a File object
File schemaFile = new File(this.getClass().getResource("toys.xsd").toURI());
// Get the parser
SAXParser parser = spf.newSAXParser();
parser.setProperty(SCHEMA_LANG, SCHEMA_TYPE);
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaFile);
InputStream is = this.getClass().getResourceAsStream("toys.xml");
MyErrorHandler eh = new MyErrorHandler();
parser.parse(is, eh);
Assert.assertFalse(eh.errorOccured, "Not Expected Error");
System.setProperty("maxOccurLimit", "");
} catch (Exception e) {
Assert.fail("Exception occured: " + e.getMessage());
}
}
/*
* This test will take longer time to execute( abt 120sec). This method
* tries to validate a document. This document contains an element whose
* maxOccur is '3002'. Since secure processing feature is off, document
* should be parsed without any errors.
*/
@Test
public void testValidMaxOccurLimitWithOutSecureProcessing() {
if (_isSecureMode)
return; // jaxp secure feature can not be turned off when security
// manager is present
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
spf.setValidating(true);
// Set the properties for Schema Validation
String SCHEMA_LANG = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
String SCHEMA_TYPE = "http://www.w3.org/2001/XMLSchema";
// Get the Schema location as a File object
File schemaFile = new File(this.getClass().getResource("toys3002.xsd").toURI());
// Get the parser
SAXParser parser = spf.newSAXParser();
parser.setProperty(SCHEMA_LANG, SCHEMA_TYPE);
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaFile);
InputStream is = this.getClass().getResourceAsStream("toys.xml");
MyErrorHandler eh = new MyErrorHandler();
parser.parse(is, eh);
Assert.assertFalse(eh.errorOccured, "Expected Error as maxOccurLimit is exceeded");
} catch (Exception e) {
Assert.fail("Exception occured: " + e.getMessage());
}
}
/*
* Before 8014530: System property is set to 2. Given XML document has more
* than 2 entity references. Parsing this document in non-secure mode,
* should *not* report an error.
* After 8014530: System properties will override FSP, the result of this
* test should be the same as
* testSystemElementAttributeLimitWithSecureProcessing
*/
@Test
public void testSystemEntityExpansionLimitWithOutSecureProcessing() {
if (_isSecureMode)
return; // jaxp secure feature can not be turned off when security
// manager is present
try {
System.setProperty("entityExpansionLimit", "2");
dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
dbf.setValidating(true);
DocumentBuilder parser = dbf.newDocumentBuilder();
Document doc = parser.parse(this.getClass().getResourceAsStream("entity.xml"));
Assert.fail("SAXParserException is expected, as given XML document contains more 2 entity references");
} catch (Exception e) {
String errMsg = e.getMessage();
Throwable cause = e.getCause();
if (cause != null) {
errMsg += cause.getMessage();
}
if (errMsg.contains("JAXP0001")) {
// expected
} else {
Assert.fail("Unexpected error: " + e.getMessage());
}
} finally {
System.clearProperty("entityExpansionLimit");
}
}
/*
* System property is set to 2. Given XML document has more than 2 entity
* references. Parsing this document in secure mode, should report an error.
*/
@Test
public void testSystemEntityExpansionLimitWithSecureProcessing() {
try {
dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
System.setProperty("entityExpansionLimit", "2");
DocumentBuilder parser = dbf.newDocumentBuilder();
Document doc = parser.parse(this.getClass().getResourceAsStream("entity.xml"));
Assert.fail("SAXParserException is expected, as given XML document contains more 2 entity references");
} catch (SAXParseException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
Assert.fail("Exception " + e.getMessage());
} finally {
System.setProperty("entityExpansionLimit", "");
}
}
/*
* Given XML document has more than 64000 entity references. Parsing this
* document in secure mode, should report an error.
*/
@Test
public void testEntityExpansionLimitWithSecureProcessing() {
try {
dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
DocumentBuilder parser = dbf.newDocumentBuilder();
Document doc = parser.parse(this.getClass().getResourceAsStream("entity64K.xml"));
Assert.fail("SAXParserException is expected, as given XML document contains more 2 entity references");
} catch (SAXParseException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
Assert.fail("Exception " + e.getMessage());
} finally {
System.setProperty("entityExpansionLimit", "");
}
}
/*
* Given XML document has more than 64000 entity references. Parsing this
* document in non-secure mode, should not report any error.
*/
@Test
public void testEntityExpansionLimitWithOutSecureProcessing() {
if (_isSecureMode)
return; // jaxp secure feature can not be turned off when security
// manager is present
try {
dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
dbf.setValidating(true);
DocumentBuilder parser = dbf.newDocumentBuilder();
Document doc = parser.parse(this.getClass().getResourceAsStream("entity64K.xml"));
} catch (SAXParseException e) {
Assert.fail("Exception " + e.getMessage());
} catch (Exception e) {
Assert.fail("Exception " + e.getMessage());
} finally {
System.setProperty("entityExpansionLimit", "");
}
}
}

View File

@ -0,0 +1,74 @@
/*
* 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;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/*
* @bug 6341770
* @summary Test external entity linked to non-ASCII base URL.
*/
public class Bug6341770 {
// naming a file "aux" would fail on windows.
@Test
public void testNonAsciiURI() {
try {
File dir = File.createTempFile("sko\u0159ice", null);
dir.delete();
dir.mkdir();
File main = new File(dir, "main.xml");
PrintWriter w = new PrintWriter(new FileWriter(main));
w.println("<!DOCTYPE r [<!ENTITY aux SYSTEM \"aux1.xml\">]>");
w.println("<r>&aux;</r>");
w.flush();
w.close();
File aux = new File(dir, "aux1.xml");
w = new PrintWriter(new FileWriter(aux));
w.println("<x/>");
w.flush();
w.close();
System.out.println("Parsing: " + main);
SAXParserFactory.newInstance().newSAXParser().parse(main, new DefaultHandler() {
public void startElement(String uri, String localname, String qname, Attributes attr) throws SAXException {
System.out.println("encountered <" + qname + ">");
}
});
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception: " + e.getMessage());
}
System.out.println("OK.");
}
}

View File

@ -0,0 +1,52 @@
/*
* 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;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6361283
* @summary Test SAXParser returns version as 1.1 for XML 1.1 document.
*/
public class Bug6361283 {
@Test
public void testXMLVersion() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
Assert.assertTrue(factory.getFeature("http://xml.org/sax/features/use-locator2"), "use-locator2 should have value as true");
MyDefaultHandler dh = new MyDefaultHandler();
parser.parse(this.getClass().getResourceAsStream("catalog.xml"), dh);
Assert.assertTrue(dh.xmlVersion.equals("1.1"), "XML Document version should be 1.1");
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception occured: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,62 @@
/*
* 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;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.XMLReader;
/*
* @bug 6506304
* @summary Test MalformedURLException: unknown protocol won't be thrown when there is a space within the full path file name.
*/
public class Bug6506304Test {
public static boolean isWindows = false;
static {
if (System.getProperty("os.name").indexOf("Windows") > -1) {
isWindows = true;
}
};
@Test
public void testPath() throws Exception {
if (isWindows) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser jaxpParser = factory.newSAXParser();
XMLReader reader = jaxpParser.getXMLReader();
reader.parse("C:/space error/x.xml");
System.exit(0);
} catch (Exception e) {
System.out.println(e.getMessage());
if (e.getMessage().equalsIgnoreCase("unknown protocol: c")) {
Assert.fail("jdk5 allowed the above form");
} else if (e.getMessage().indexOf("(The system cannot find the path specified)") > 0) {
// expected
}
}
}
}
}

View File

@ -0,0 +1,63 @@
/*
* 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;
import java.io.FileReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/*
* @bug 6518733
* @summary Test SAX parser handles several attributes that each contain a newline within the attribute value.
*/
public class Bug6518733 {
@Test
public void test() {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new InputSource(new FileReader(getClass().getResource("Bug6518733.xml").getFile())), new Handler());
} catch (Exception ex) {
ex.printStackTrace();
}
}
static class Handler extends org.xml.sax.helpers.DefaultHandler {
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
// Make sure that the value of attribute q7 is "7 G"
if (qName.equals("obj")) {
Assert.assertTrue(attrs.getValue("", "q7").equals("7 G"));
}
}
}
}

View File

@ -0,0 +1,32 @@
<?xml version="1.0"?>
<obj
q1="1
A"
q2="2
B"
q3="3
C"
q4="4
D"
q5="5
E"
q6="6
F"
q7="7
G"
q8="8
H"
q9="9
I"
/>

View File

@ -0,0 +1,176 @@
/*
* 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;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.XMLConstants;
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.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/*
* @bug 6564400
* @summary Test ignorable whitespace handling with schema validation.
*/
public class Bug6564400 {
private boolean sawIgnorable = false;
Schema schema = null;
public Bug6564400(String name) {
String xsdFile = "Bug6564400.xsd";
File schemaFile = new File(xsdFile);
// Now attempt to load up the schema
try {
SchemaFactory schFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schema = schFactory.newSchema(new StreamSource(getClass().getResourceAsStream(xsdFile)));
} catch (Exception e) {
// Nevermind, bad things will happen later
}
}
@Test
public void testDOM() throws ParserConfigurationException, SAXException, IOException {
InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");
// Set the options on the DocumentFactory to remove comments, remove
// whitespace
// and validate against the schema.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setIgnoringComments(true);
docFactory.setIgnoringElementContentWhitespace(true);
docFactory.setSchema(schema);
DocumentBuilder parser = docFactory.newDocumentBuilder();
Document xmlDoc = parser.parse(xmlFile);
boolean ok = dump(xmlDoc, true);
Assert.assertEquals(true, ok);
}
@Test
public void testSAX() throws ParserConfigurationException, SAXException, IOException {
InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");
// Parse with SAX
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
saxFactory.setSchema(schema);
SAXParser saxparser = saxFactory.newSAXParser();
sawIgnorable = false;
saxparser.parse(xmlFile, new MyHandler());
Assert.assertEquals(true, sawIgnorable);
}
@Test
public void testConformantDOM() throws ParserConfigurationException, SAXException, IOException {
InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");
// Set the options on the DocumentFactory to remove comments, remove
// whitespace
// and validate against the schema.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setIgnoringComments(true);
docFactory.setIgnoringElementContentWhitespace(true);
docFactory.setSchema(schema);
docFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace", true);
DocumentBuilder parser = docFactory.newDocumentBuilder();
Document xmlDoc = parser.parse(xmlFile);
boolean ok = dump(xmlDoc, true);
Assert.assertEquals(false, ok);
}
@Test
public void testConformantSAX() throws ParserConfigurationException, SAXException, IOException {
InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");
// Parse with SAX
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
saxFactory.setSchema(schema);
saxFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace", true);
SAXParser saxparser = saxFactory.newSAXParser();
sawIgnorable = false;
saxparser.parse(xmlFile, new MyHandler());
Assert.assertEquals(false, sawIgnorable);
}
private boolean dump(Node node) {
return dump(node, false);
}
private boolean dump(Node node, boolean silent) {
return dump(node, silent, 0);
}
private boolean dump(Node node, boolean silent, int depth) {
boolean ok = true;
if (!silent) {
for (int i = 0; i < depth; i++) {
System.out.print(" ");
}
System.out.println(node);
}
if (node.getNodeType() == Node.TEXT_NODE) {
String text = ((Text) node).getData();
ok = ok && text.trim().length() > 0;
}
if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.DOCUMENT_NODE) {
Node child = node.getFirstChild();
while (child != null) {
ok = ok && dump(child, silent, depth + 1);
child = child.getNextSibling();
}
}
return ok;
}
public class MyHandler extends DefaultHandler {
public void ignorableWhitespace(char[] ch, int start, int length) {
sawIgnorable = true;
}
}
}

View File

@ -0,0 +1,4 @@
<Person>
<FirstName>Doofus</FirstName><!-- MONKEY -->
<LastName>McGee</LastName>
</Person>

View File

@ -0,0 +1,9 @@
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Person' type='PersonType'/>
<xsd:complexType name='PersonType'>
<xsd:sequence>
<xsd:element name='FirstName' type='xsd:string'/>
<xsd:element name='LastName' type='xsd:string'/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>

View File

@ -0,0 +1,69 @@
/*
* 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;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6573786
* @summary Test parser error messages are formatted.
*/
public class Bug6573786 {
String _cache = "";
@Test
public void test() {
final String XML = "" + "<?xml version='1.0' encoding='UTF-8' standalone='bad_value' ?>" + "<root />";
runTest(XML);
}
@Test
public void test1() {
final String XML = "" + "<?xml version='1.0' standalone='bad_value' encoding='UTF-8' ?>" + "<root />";
runTest(XML);
}
void runTest(String xmlString) {
Bug6573786ErrorHandler handler = new Bug6573786ErrorHandler();
try {
InputStream is = new StringBufferInputStream(xmlString);
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(is, handler);
} catch (Exception e) {
if (handler.fail) {
Assert.fail("The value of standalone attribute should be merged into the error message.");
}
}
}
}

View File

@ -0,0 +1,47 @@
/*
* 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;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class Bug6573786ErrorHandler extends DefaultHandler {
public boolean fail = false;
public void fatalError(SAXParseException e) throws SAXException {
System.out.println(e.getMessage());
if (e.getMessage().indexOf("bad_value") < 0) {
fail = true;
}
} // fatalError ()
public void error(SAXParseException e) throws SAXException {
System.out.println(e.getMessage());
} // error ()
public void warning(SAXParseException e) throws SAXException {
System.out.println(e.getMessage());
} // warning ()
}

View File

@ -0,0 +1,171 @@
/*
* 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;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
/*
* @bug 6594813
* @summary Test SAXParser output is wellformed with name space.
*/
public class Bug6594813 {
public Bug6594813(String name) {
}
private static final String TESTXML = "<?xml version='1.0' ?>\n"
+ "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns1='http://faulttestservice.org/wsdl'>\n"
+ "<soapenv:Body>\n" + "<soapenv:Fault xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>\n" + "<faultcode>\n"
+ "soapenv:Server</faultcode>\n" + "<faultstring>\n" + "com.sun.ts.tests.jaxws.sharedwebservices.faultservice.DummyException</faultstring>\n"
+ "<detail>\n" + "<ns1:DummyException>\n" + "<dummyField1>\n" + "dummyString1</dummyField1>\n" + "<dummyField2>\n" + "dummyString2</dummyField2>\n"
+ "</ns1:DummyException>\n" + "</detail>\n" + "</soapenv:Fault>\n" + "</soapenv:Body>\n" + "</soapenv:Envelope>\n";
// simplest XML to re-declare same prefix/namespace mappings
private static final String SIMPLE_TESTXML = "<?xml version='1.0' ?>\n" + "<prefix:ElementName xmlns:prefix='URI'>\n"
+ "<prefix:ElementName xmlns:prefix='URI'>\n" + "</prefix:ElementName>\n" + "</prefix:ElementName>\n";
private String runTransform(SAXParser sp) throws Exception {
// Run identity transform using SAX parser
SAXSource src = new SAXSource(sp.getXMLReader(), new InputSource(new StringReader(TESTXML)));
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringWriter sw = new StringWriter();
transformer.transform(src, new StreamResult(sw));
String result = sw.getBuffer().toString();
// System.out.println(result);
return result;
}
private void checkWellFormedness(String xml) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true); // Same as default
spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
SAXParser sp = spf.newSAXParser();
// Re-parse output to make sure that it is well formed
sp.parse(new InputSource(new StringReader(xml)), new DefaultHandler());
}
/**
* Test an identity transform of an XML document with NS decls using a
* non-ns-aware parser. Output result to a StreamSource. Set ns-awareness to
* FALSE and prefixes to FALSE.
*/
@Test
public void testXMLNoNsAwareStreamResult1() {
try {
// Create SAX parser *without* enabling ns
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(false); // Same as default
spf.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
SAXParser sp = spf.newSAXParser();
// Make sure that the output is well formed
String xml = runTransform(sp);
checkWellFormedness(xml);
} catch (Throwable ex) {
Assert.fail(ex.toString());
}
}
/**
* Test an identity transform of an XML document with NS decls using a
* non-ns-aware parser. Output result to a StreamSource. Set ns-awareness to
* FALSE and prefixes to TRUE.
*/
@Test
public void testXMLNoNsAwareStreamResult2() {
try {
// Create SAX parser *without* enabling ns
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(false); // Same as default
spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
SAXParser sp = spf.newSAXParser();
// Make sure that the output is well formed
String xml = runTransform(sp);
checkWellFormedness(xml);
} catch (Throwable ex) {
Assert.fail(ex.toString());
}
}
/**
* Test an identity transform of an XML document with NS decls using a
* non-ns-aware parser. Output result to a StreamSource. Set ns-awareness to
* TRUE and prefixes to FALSE.
*/
@Test
public void testXMLNoNsAwareStreamResult3() {
try {
// Create SAX parser *without* enabling ns
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true); // Same as default
spf.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
SAXParser sp = spf.newSAXParser();
// Make sure that the output is well formed
String xml = runTransform(sp);
checkWellFormedness(xml);
} catch (Throwable ex) {
Assert.fail(ex.toString());
}
}
/**
* Test an identity transform of an XML document with NS decls using a
* non-ns-aware parser. Output result to a StreamSource. Set ns-awareness to
* TRUE and prefixes to TRUE.
*/
@Test
public void testXMLNoNsAwareStreamResult4() {
try {
// Create SAX parser *without* enabling ns
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true); // Same as default
spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
SAXParser sp = spf.newSAXParser();
// Make sure that the output is well formed
String xml = runTransform(sp);
checkWellFormedness(xml);
} catch (Throwable ex) {
Assert.fail(ex.toString());
}
}
}

View File

@ -0,0 +1,3 @@
<!ENTITY % label.qname "IGNORE" >
<!ENTITY % xhtml PUBLIC "-//W3C//DTD XHTML 1.1//EN" "Bug6608841_xhtml11-flat.dtd">
%xhtml;

View File

@ -0,0 +1,55 @@
/*
* 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;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/*
* @bug 6608841
* @summary Test SAX parses external parameter entity.
*/
public class Bug6608841 {
public Bug6608841(String name) {
}
@Test
public void testParse() throws ParserConfigurationException, SAXException, IOException {
String file = getClass().getResource("Bug6608841.xml").getFile();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
parser.parse(new File(file), new MyHandler());
}
public class MyHandler extends DefaultHandler {
}
}

View File

@ -0,0 +1,10 @@
<!DOCTYPE html SYSTEM "Bug6608841.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some Title</title>
</head>
<body>
<h1>Some Title</h1>
<p>This is a test. This is only a test.</p>
</body>
</html>

View File

@ -0,0 +1 @@
<?doc type="doctype" role="title" { XHTML 1.1 } ?>

View File

@ -0,0 +1,83 @@
/*
* 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;
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/*
* @bug 6518733
* @summary Test SAX parser handles several attributes with newlines.
*/
public class Bug6690015 {
public Bug6690015() {
}
@Test
public void test() {
try {
FileInputStream fis = new FileInputStream(getClass().getResource("bug6690015.xml").getFile());
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(fis));
Element root = doc.getDocumentElement();
NodeList textnodes = root.getElementsByTagName("text");
int len = textnodes.getLength();
int index = 0;
int attindex = 0;
int attrlen = 0;
NamedNodeMap attrs = null;
while (index < len) {
Element te = (Element) textnodes.item(index);
attrs = te.getAttributes();
attrlen = attrs.getLength();
attindex = 0;
Node node = null;
while (attindex < attrlen) {
node = attrs.item(attindex);
System.out.println("attr: " + node.getNodeName() + " is shown holding value: " + node.getNodeValue());
attindex++;
}
index++;
System.out.println("-------------");
}
fis.close();
} catch (Exception e) {
Assert.fail("Exception: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,164 @@
/*
* 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;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/*
* @bug 6518733
* @summary Test SAX parser handles several attributes with containing "&gt;".
*/
public class Bug6760982 {
@Test
public void test() {
try {
Document xmlDoc = _Parse(new File(getClass().getResource("bug6760982.xml").getFile()));
Node node = xmlDoc.getDocumentElement();
_ProcessNode(node, 0);
_Flush();
} catch (Exception e) {
_ErrPrintln("Exception: " + e.toString());
Assert.fail("Exception: " + e.getMessage());
}
}
private static void _Flush() {
System.out.flush();
System.err.flush();
}
private static void _Println(String str, int level) {
for (int i = 0; i < level; i++)
System.out.print(" ");
System.out.println(str);
System.out.flush();
}
private static void _ErrPrintln(String aStr) {
System.out.flush();
System.err.println(aStr);
System.err.flush();
}
private static Document _Parse(File f) throws Exception {
FileReader rd = new FileReader(f);
Document doc = _Parse(rd);
rd.close();
return doc;
}
private static Document _Parse(Reader src) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false); // to improve performance
DocumentBuilder xmlParser = dbf.newDocumentBuilder();
InputSource is = new InputSource(src);
return xmlParser.parse(is);
}
private static void _PrintAttributes(Node n, int level) {
NamedNodeMap nnmap = n.getAttributes();
if (nnmap != null && nnmap.getLength() > 0) {
_Println("<attribs> (" + nnmap.getClass() + "):", level + 1);
for (int i = 0; i < nnmap.getLength(); i++) {
Node an = nnmap.item(i);
String nameStr = an.getNodeName();
String valueStr = an.getNodeValue();
if (valueStr != "")
nameStr += " = " + valueStr;
_Println(nameStr, level + 2);
}
}
}
private static void _ProcessChildren(Node n, int level) throws Exception {
NodeList nlist = n.getChildNodes();
if (nlist != null)
for (int i = 0; i < nlist.getLength(); i++)
_ProcessNode(nlist.item(i), level + 1);
}
private static void _ProcessNode(Node n, int level) throws Exception {
n.getAttributes();
n.getChildNodes();
// At this point, for JVM 1.6 and Xerces <= 1.3.1,
// Test-XML.xml::mytest:Y's attribute is (already) bad.
switch (n.getNodeType()) {
case Node.TEXT_NODE:
String str = n.getNodeValue().trim();
/* ...Only print non-empty strings... */
if (str.length() > 0) {
String valStr = n.getNodeValue();
_Println(valStr, level);
}
break;
case Node.COMMENT_NODE:
break;
default: {
String nodeNameStr = n.getNodeName();
_Println(nodeNameStr + " (" + n.getClass() + "):", level);
/* ...Print children... */
_ProcessChildren(n, level);
/* ...Print optional node attributes... */
_PrintAttributes(n, level);
}
}
}
}

View File

@ -0,0 +1,74 @@
/*
* 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;
import java.io.ByteArrayInputStream;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.ProcessingInstruction;
import org.xml.sax.InputSource;
/*
* @bug 6849942
* @summary Test parsing an XML that starts with a processing instruction and no prolog.
*/
public class Bug6849942Test {
@Test
public void test() throws Exception {
try {
ByteArrayInputStream bais = new ByteArrayInputStream("<?xmltarget foo?><test></test>".getBytes());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder xmlParser = factory.newDocumentBuilder();
// DOMParser p = new DOMParser();
Document document = xmlParser.parse(new InputSource(bais));
String result = ((ProcessingInstruction) document.getFirstChild()).getData();
System.out.println(result);
if (!result.equalsIgnoreCase("foo")) {
Assert.fail("missing PI data");
}
} catch (Exception e) {
}
}
@Test
public void testWProlog() throws Exception {
try {
ByteArrayInputStream bais = new ByteArrayInputStream("<?xml version=\"1.1\" encoding=\"UTF-8\"?><?xmltarget foo?><test></test>".getBytes());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder xmlParser = factory.newDocumentBuilder();
// DOMParser p = new DOMParser();
Document document = xmlParser.parse(new InputSource(bais));
String result = ((ProcessingInstruction) document.getFirstChild()).getData();
System.out.println(result);
if (!result.equalsIgnoreCase("foo")) {
Assert.fail("missing PI data");
}
} catch (Exception e) {
}
}
}

View File

@ -0,0 +1 @@
<!ELEMENT arg (#PCDATA)>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : test1.xml
Created on : 2012/04/13, 18:21
Author : 10385373
Description:
Purpose of the document follows.
-->
<root>
</root>

View File

@ -0,0 +1,209 @@
/*
* 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;
import java.io.File;
import java.io.IOException;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/*
* @bug 7157608
* @summary Test feature standard-uri-conformant works.
*/
public class Bug7157608Test {
public static boolean isWindows = false;
static {
if (System.getProperty("os.name").indexOf("Windows") > -1) {
isWindows = true;
}
};
String xml1, xml2;
@BeforeMethod
protected void setUp() throws IOException {
File file1 = new File(getClass().getResource("Bug7157608.xml").getFile());
xml1 = file1.getPath().replace("\\", "\\\\");
File file2 = new File(getClass().getResource("Bug7157608_1.xml").getFile());
xml2 = file2.getPath();
}
// case 1
// standard-uri-confomant is false
// dtd-validation is false
@Test
public void test1() {
if (isWindows) {
try {
ParserSettings ps = new ParserSettings();
DocumentBuilder db = getDocumentBuilder(ps);
InputSource is = new InputSource();
is.setSystemId(xml1);
Document doc = db.parse(is);
System.out.println("test1() :OK");
} catch (Exception e) {
Assert.fail("test1() :NG");
}
}
}
// case 2
// standard-uri-confomant is false
// dtd-validation is true
@Test
public void test2() {
if (isWindows) {
try {
ParserSettings ps = new ParserSettings();
ps.validating = true;
DocumentBuilder db = getDocumentBuilder(ps);
InputSource is = new InputSource(xml2);
Document doc = db.parse(is);
System.out.println("test2() :OK");
} catch (Exception e) {
Assert.fail("test2() :NG");
// logger.info(e.getMessage());
}
}
}
// case 3
// standard-uri-confomant is true
@Test
public void test3() {
if (isWindows) {
try {
ParserSettings ps = new ParserSettings();
ps.standardUriConformant = true;
DocumentBuilder db = getDocumentBuilder(ps);
InputSource is = new InputSource();
is.setSystemId(xml1);
Document doc = db.parse(is);
Assert.fail("test3() :NG");
} catch (IOException e) {
String returnedErr = e.getMessage();
String expectedStr = "Opaque part contains invalid character";
if (returnedErr.indexOf(expectedStr) >= 0) {
System.out.println("test3() :OK");
} else {
Assert.fail("test3() :NG");
}
} catch (Exception e) {
System.out.println("test3() :NG");
}
}
}
// case 4
// standard-uri-confomant is true
// dtd-validation is true
@Test
public void test4() {
if (isWindows) {
try {
ParserSettings ps = new ParserSettings();
ps.standardUriConformant = true;
ps.validating = true;
DocumentBuilder db = getDocumentBuilder(ps);
InputSource is = new InputSource(xml2);
Document doc = db.parse(is);
Assert.fail("test4() :NG");
} catch (IOException e) {
String returnedErr = e.getMessage();
String expectedStr = "Opaque part contains invalid character";
if (returnedErr.indexOf(expectedStr) >= 0) {
System.out.println("test3() :OK");
} else {
Assert.fail("test3() :NG");
}
} catch (Exception e) {
Assert.fail("test4() :NG");
}
}
}
public DocumentBuilder getDocumentBuilder(ParserSettings ps) {
DocumentBuilder db = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
if (ps.standardUriConformant) {
dbf.setFeature("http://apache.org/xml/features/standard-uri-conformant", true);
}
dbf.setValidating(ps.validating);
db = dbf.newDocumentBuilder();
db.setErrorHandler(new MyHandler());
} catch (Exception e) {
Assert.fail("standard-uri-conformant not recognized");
}
return db;
}
class MyHandler extends DefaultHandler {
@Override
public void warning(SAXParseException e) throws SAXException {
printDetail("**Warning**", e);
}
@Override
public void error(SAXParseException e) throws SAXException {
printDetail("**Error**", e);
throw new SAXException("Error encountered");
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
printDetail("**Fatal Error**", e);
throw new SAXException("Fatal Error encountered");
}
public void printDetail(String msg, SAXParseException e) {
System.out.println(msg);
System.out.println(e.getMessage());
System.out.println(" Line: " + e.getLineNumber());
System.out.println(" Column: " + e.getColumnNumber());
System.out.println(" URI: " + e.getSystemId());
}
}
class ParserSettings {
boolean standardUriConformant = false;
boolean validating = false;
}
}

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : test2.xml
Created on : 2012/04/13, 20:08
Author : 10385373
Description:
Purpose of the document follows.
-->
<!DOCTYPE arg PUBLIC '-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN' 'Bug7157608.dtd'>
<arg>
test
</arg>

View File

@ -0,0 +1,72 @@
/*
* 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;
import java.io.IOException;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/*
* @bug 7166896
* @summary Test DocumentBuilder.parse(String uri) supports IPv6 format.
*/
public class Bug7166896Test {
@Test
public void test() throws Exception {
final String url = "http://[fe80::la03:73ff:fead:f7b0]/note.xml";
final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
System.out.println("URL is " + url);
try {
builder = domFactory.newDocumentBuilder();
// here comes the MalformedURLException. With Java6 / 7 it looks
// like this:
// java.net.MalformedURLException: For input string:
// ":la03:73ff:fead:f7b0%5D"
// which is not fine.
// with xerces 2.11.0 it complains about a non-existing host, which
// is fine
System.out.println("passing URL to DocumentBuilder.parse()");
doc = builder.parse(url);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
String em = e.getMessage();
System.err.println("Error message: " + em);
if (em.contains("For input string: \":la03:73ff:fead:f7b0%5D\"")) {
Assert.fail("failed to accept IPv6 address");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,79 @@
/*
* 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;
import java.io.FileOutputStream;
import java.util.ArrayList;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.sun.org.apache.bcel.internal.classfile.ClassParser;
import com.sun.org.apache.bcel.internal.classfile.ConstantClass;
import com.sun.org.apache.bcel.internal.classfile.ConstantPool;
import com.sun.org.apache.bcel.internal.classfile.ConstantUtf8;
import com.sun.org.apache.bcel.internal.classfile.JavaClass;
import com.sun.org.apache.bcel.internal.classfile.Method;
import com.sun.org.apache.bcel.internal.generic.ClassGen;
import com.sun.org.apache.bcel.internal.generic.MethodGen;
/*
* @bug 8003147
* @summary Test port fix for BCEL bug 39695.
*/
public class Bug8003147Test {
@Test
public void test() throws Exception {
String classfile = getClass().getResource("Bug8003147Test.class").getPath();
JavaClass jc = new ClassParser(classfile).parse();
// rename class
ConstantPool cp = jc.getConstantPool();
int cpIndex = ((ConstantClass) cp.getConstant(jc.getClassNameIndex())).getNameIndex();
cp.setConstant(cpIndex, new ConstantUtf8("javax/xml/parsers/Bug8003147TestPrime"));
ClassGen gen = new ClassGen(jc);
Method[] methods = jc.getMethods();
int index;
for (index = 0; index < methods.length; index++) {
if (methods[index].getName().equals("doSomething")) {
break;
}
}
Method m = methods[index];
MethodGen mg = new MethodGen(m, gen.getClassName(), gen.getConstantPool());
gen.replaceMethod(m, mg.getMethod());
String path = classfile.replace("Bug8003147Test", "Bug8003147TestPrime");
gen.getJavaClass().dump(new FileOutputStream(path));
try {
Class.forName("javax.xml.parsers.Bug8003147TestPrime");
} catch (ClassFormatError cfe) {
cfe.printStackTrace();
Assert.fail("modified version of class does not pass verification");
}
}
public void doSomething(double d, ArrayList<Integer> list) {
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<personnel>
<person id="Big.Boss" A100 = ""
A101 = "" A102 = "" A103 = ""
>
<name><family>Boss</family> <given>Big</given></name>
<email>chief@foo.com</email>
<link subordinates="one.worker two.worker three.worker four.worker five.worker"/>
</person>
<person id="one.worker">
<name><family>Worker</family> <given>One</given></name>
<email>one@foo.com</email>
<link manager="Big.Boss"/>
</person>
<person id="two.worker">
<name><family>Worker</family> <given>Two</given></name>
<email>two@foo.com</email>
<link manager="Big.Boss"/>
</person>
<person id="three.worker">
<name><family>Worker</family> <given>Three</given></name>
<email>three@foo.com</email>
<link manager="Big.Boss"/>
</person>
<person id="four.worker">
<name><family>Worker</family> <given>Four</given></name>
<email>four@foo.com</email>
<link manager="Big.Boss"/>
</person>
<person id="five.worker">
<name><family>Worker</family> <given>Five</given></name>
<email>five@foo.com</email>
<link manager="Big.Boss"/>
</person>
</personnel>

View File

@ -0,0 +1,73 @@
/*
* 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;
import java.net.URL;
import java.net.URLClassLoader;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @summary Test Classloader for SAXParserFactory.
*/
public class FactoryFindTest {
boolean myClassLoaderUsed = false;
@Test
public void testFactoryFind() {
try {
// System.setProperty("jaxp.debug", "true");
SAXParserFactory factory = SAXParserFactory.newInstance();
Assert.assertTrue(factory.getClass().getClassLoader() == null);
Thread.currentThread().setContextClassLoader(null);
factory = SAXParserFactory.newInstance();
Assert.assertTrue(factory.getClass().getClassLoader() == null);
Thread.currentThread().setContextClassLoader(new MyClassLoader());
factory = SAXParserFactory.newInstance();
if (System.getSecurityManager() == null)
Assert.assertTrue(myClassLoaderUsed);
else
Assert.assertFalse(myClassLoaderUsed);
} catch (Exception ex) {
}
}
class MyClassLoader extends URLClassLoader {
public MyClassLoader() {
super(new URL[0]);
}
public Class loadClass(String name) throws ClassNotFoundException {
myClassLoaderUsed = true;
return super.loadClass(name);
}
}
}

View File

@ -0,0 +1,47 @@
/*
* 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;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.ext.Locator2;
import org.xml.sax.helpers.DefaultHandler;
public class MyDefaultHandler extends DefaultHandler {
private Locator myLocator = null;
String xmlVersion = "";
public void setDocumentLocator(Locator locator) {
myLocator = locator;
}
public void startElement(String uri, String localName, String qName, Attributes attributes) {
try {
xmlVersion = ((Locator2) myLocator).getXMLVersion();
} catch (Exception e) {
}
}
}

View File

@ -0,0 +1,55 @@
/*
* 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;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class MyErrorHandler extends DefaultHandler {
public boolean errorOccured = false;
public void error(SAXParseException e) throws SAXException {
System.err.println("Error: " + "[[" + e.getPublicId() + "]" + "[" + e.getSystemId() + "]]" + "[[" + e.getLineNumber() + "]" + "[" + e.getColumnNumber()
+ "]] " + e);
errorOccured = true;
}
public void fatalError(SAXParseException e) throws SAXException {
System.err.println("Fatal Error: " + e);
errorOccured = true;
}
public void warning(SAXParseException e) throws SAXException {
System.err.println("Warning: " + e);
errorOccured = true;
}
}

View File

@ -0,0 +1,85 @@
/*
* 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;
import java.io.StringReader;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
/*
* @summary Test SAXParser doesn't accept empty stream.
*/
public class ParseEmptyStream {
SAXParserFactory factory = null;
public ParseEmptyStream(String name) {
try {
factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Test
public void testEmptyStream() {
try {
SAXParser parser = factory.newSAXParser();
InputSource source = new InputSource(new StringReader(""));
parser.parse(source, new MyHandler());
Assert.fail("Inputstream without document element accepted");
} catch (Exception ex) {
System.out.println("Exception thrown: " + ex.getMessage());
// Premature end of file exception expected
}
}
@Test
public void testXmlDeclOnly() {
try {
SAXParser parser = factory.newSAXParser();
InputSource source = new InputSource(new StringReader("<?xml version='1.0' encoding='utf-8'?>"));
parser.parse(source, new MyHandler());
Assert.fail("Inputstream without document element accepted");
} catch (Exception ex) {
System.out.println("Exception thrown: " + ex.getMessage());
// Premature end of file exception expected
}
}
static class MyHandler extends DefaultHandler {
public void startDocument() {
System.out.println("Start document called");
}
public void endDocument() {
System.out.println("End document called");
}
}
}

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<block>
<lang>
<text dna="8233" ro="hello, and i'll type some normal characters in (&gt;=1.5 mm) ro" it="here to make sure international characters don't play a part(&gt;=1.5mm) it" tr="make sure international characters don't play a part (&gt;=1.5 mm) tr" pt_br="make sure international characters don't play a part (&gt;=1,5 mm) pt_br" de="make sure international characters don't play a part (&gt;=1,5 mm) de" el="make sure international characters don't play a part (&gt;= 1.5 mm) el" zh_cn="make sure international characters don't play a part¿&gt;= 1.5 mm¿ zh_cn" pt="make sure international characters don't play a part (&gt;=1,5 mm) pt" bg="make sure international characters don't play a part (&gt;= 1.5 mm) bg" fr="make sure international characters don't play a part (&gt;= 1,5 mm) fr" en="make sure international characters don't play a part (&gt;= 1.5 mm) en" ru="make sure international characters don't play a part (&gt;=1.5 ¿¿) ru" es="make sure international characters don't play a part (&gt;=1.5 mm) es" ja="make sure international characters don't play a part¿&gt;=1.5mm¿ ja" nl="make sure international characters don't play a part (&gt;= 1,5 mm) nl" />
</lang>
</block>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Test>
<mytest a= '[]'
b= '[]'
c= '[]'
d= '[]'
e= '[]'
f= '[]'
Y= '[]'
Z= 'ZZ[]'
/>
</Test>

View File

@ -0,0 +1,2 @@
<?xml version="1.1" encoding="UTF-8"?>
<stardb xmlns="http://www.astro.com/astro" xmlns:astro="http://www.astro.com/astro" xsi:schemaLocation="http://www.astro.com/astro catalog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><_test01></_test01><test-02 xmlns:xsi=""></test-02><test.03></test.03><_test-04>T%e!s#t$</_test-04><star><hr>1</hr><constellation/><fullname/><ra><h>00</h><m>05</m><s>09.9</s><dv>0.08608333333333333</dv></ra><dec><sgn/><d>45</d><m>13</m><s>45</s><dv>45.22916666666667</dv></dec><glng>114.44</glng><glat>-16.88</glat><vmag>6.70</vmag><spec>A1Vn</spec></star><star><hr>2</hr><constellation/><fullname/><ra><h>00</h><m>05</m><s>03.8</s><dv>0.08438888888888889</dv></ra><dec><sgn>-</sgn><d>00</d><m>30</m><s>11</s><dv>-0.5030555555555556</dv></dec><glng>98.33</glng><glat>-61.14</glat><vmag>6.29</vmag><spec>gG9</spec></star><star><hr>3</hr><constellation>Psc</constellation><fullname>33 Psc</fullname><ra><h>00</h><m>05</m><s>20.1</s><dv>0.08891666666666666</dv></ra><dec><sgn>-</sgn><d>05</d><m>42</m><s>27</s><dv>-5.7075000000000005</dv></dec><glng>93.75</glng><glat>-65.93</glat><vmag>4.61</vmag><spec>K0IIIbCN-0.5</spec></star><star><hr>4</hr><constellation>Peg</constellation><fullname>86 Peg</fullname><ra><h>00</h><m>05</m><s>42.0</s><dv>0.095</dv></ra><dec><sgn/><d>13</d><m>23</m><s>46</s><dv>13.39611111111111</dv></dec><glng>106.19</glng><glat>-47.98</glat><vmag>5.51</vmag><spec>G5III</spec></star><star><hr>5</hr><constellation/><fullname/><ra><h>00</h><m>06</m><s>16.0</s><dv>0.10444444444444445</dv></ra><dec><sgn/><d>58</d><m>26</m><s>12</s><dv>58.43666666666666</dv></dec><glng>117.03</glng><glat>-03.92</glat><vmag>5.96</vmag><spec>G5V</spec></star><star><hr>6</hr><constellation/><fullname/><ra><h>00</h><m>06</m><s>19.0</s><dv>0.10527777777777779</dv></ra><dec><sgn>-</sgn><d>49</d><m>04</m><s>30</s><dv>-49.075</dv></dec><glng>321.61</glng><glat>-66.38</glat><vmag>5.70</vmag><spec>G1IV</spec></star><star><hr>7</hr><constellation>Cas</constellation><fullname>10 Cas</fullname><ra><h>00</h><m>06</m><s>26.5</s><dv>0.10736111111111112</dv></ra><dec><sgn/><d>64</d><m>11</m><s>46</s><dv>64.19611111111111</dv></dec><glng>118.06</glng><glat>1.75</glat><vmag>5.59</vmag><spec>B9III</spec></star><star><hr>8</hr><constellation/><fullname/><ra><h>00</h><m>06</m><s>36.8</s><dv>0.11022222222222222</dv></ra><dec><sgn/><d>29</d><m>01</m><s>17</s><dv>29.02138888888889</dv></dec><glng>111.26</glng><glat>-32.83</glat><vmag>6.13</vmag><spec>K0V</spec></star><star><hr>9</hr><constellation/><fullname/><ra><h>00</h><m>06</m><s>50.1</s><dv>0.11391666666666667</dv></ra><dec><sgn>-</sgn><d>23</d><m>06</m><s>27</s><dv>-23.1075</dv></dec><glng>52.21</glng><glat>-79.14</glat><vmag>6.18</vmag><spec>A7V</spec></star><star><hr>10</hr><constellation/><fullname/><ra><h>00</h><m>07</m><s>18.2</s><dv>0.12172222222222222</dv></ra><dec><sgn>-</sgn><d>17</d><m>23</m><s>11</s><dv>-17.386388888888888</dv></dec><glng>74.36</glng><glat>-75.90</glat><vmag>6.19</vmag><spec>A6Vn</spec></star></stardb>

View File

@ -0,0 +1,122 @@
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.astro.com/astro"
xmlns:astro="http://www.astro.com/astro"
elementFormDefault="qualified"
attributeFormDefault="qualified"
>
<!-- Star Identification String Type -->
<xs:simpleType name="staridType">
<xs:restriction base="xs:string">
<xs:maxLength value="4"/>
</xs:restriction>
</xs:simpleType>
<!-- Hour Type -->
<xs:simpleType name="hourType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0.0"/>
<xs:maxInclusive value="24.0"/>
</xs:restriction>
</xs:simpleType>
<!-- Minute Type -->
<xs:simpleType name="minuteType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0.0"/>
<xs:maxInclusive value="60.0"/>
</xs:restriction>
</xs:simpleType>
<!-- Second Type -->
<xs:simpleType name="secondType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0.0"/>
<xs:maxInclusive value="60.0"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="decimalValueType">
<xs:restriction base="xs:decimal">
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="degType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="-90.0"/>
<xs:maxInclusive value="90.0"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="vmagType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="-3.0"/>
<xs:maxInclusive value="12.0"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="signType">
<xs:restriction base="xs:string">
<xs:enumeration value="+"/>
<xs:enumeration value="-"/>
<xs:enumeration value=""/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="raType">
<xs:sequence>
<xs:element name="h" type="astro:hourType"/>
<xs:element name="m" type="astro:minuteType"/>
<xs:element name="s" type="astro:secondType"/>
<xs:element name="dv" type="astro:decimalValueType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="decType">
<xs:sequence>
<xs:element name="sgn" type="astro:signType"/>
<xs:element name="d" type="astro:degType"/>
<xs:element name="m" type="astro:minuteType"/>
<xs:element name="s" type="astro:secondType"/>
<xs:element name="dv" type="astro:decimalValueType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="starType">
<xs:sequence>
<xs:element name="hr" type="astro:staridType"/>
<xs:element name="constellation" type="xs:string"/>
<xs:element name="fullname" type="xs:string"/>
<xs:element name="ra" type="astro:raType"/>
<xs:element name="dec" type="astro:decType"/>
<xs:element name="glng" type="xs:decimal"/>
<xs:element name="glat" type="xs:decimal"/>
<xs:element name="vmag" type="astro:vmagType"/>
<xs:element name="spec" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<!-- The real part of the catalog starts here -->
<xs:element name="stardb">
<xs:complexType>
<xs:sequence>
<!-- for testing purposes -->
<xs:element name="_test01" type="xs:string"
minOccurs="0" maxOccurs="1"/>
<xs:element name="test-02" type="xs:string"/>
<xs:element name="test.03" type="xs:string"/>
<xs:element name="_test-04" type="xs:string"/>
<!-- astro data elements -->
<xs:element name="star" type="astro:starType"
minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<!-- The real part of the catalog ends here -->
</xs:schema>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE author [
<!ELEMENT author ANY>
<!ENTITY writer "Jan Egil Refsnes.">
<!ENTITY copyright "Copyright XML101.">
<!ENTITY something "ABC">
]>
<author>&writer;&copyright;&something;&something;</author>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tn="foo"
targetNamespace="foo" elementFormDefault="qualified">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="a">
<xs:complexType>
<xs:sequence>
<xs:element ref="tn:b"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="ref" maxOccurs="unbounded" minOccurs="0" type="xs:string" />
</xs:sequence>
</xs:complexType>
<!-- identity constraint -->
<xs:key name="key">
<xs:selector xpath=".//tn:a/tn:b|.//tn:a/tn:b/tn:c"/>
<xs:field xpath="@id"/>
</xs:key>
<xs:keyref name="keyref" refer="tn:key">
<xs:selector xpath=".//tn:ref"/>
<xs:field xpath="."/>
</xs:keyref>
</xs:element>
<xs:element name="c">
<xs:complexType>
<xs:attribute name="id" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element name="b">
<xs:complexType>
<xs:sequence>
<xs:element ref="tn:c" minOccurs="0" />
</xs:sequence>
<xs:attribute name="id" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:schema>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<root xmlns="foo">
<a>
<b id="id1">
<c id="id2"/>
</b>
</a>
<ref>id2</ref>
</root>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<root xmlns="foo">
<undefined />
</root>

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : toys.xml
Created on : August 11, 2003, 6:42 PM
Author : Prasad Subramanian
Description:
-->
<toys>
<toy>
<name>Lego-Model01</name>
<price>65.99</price>
</toy>
<toy>
<name>Lego-Model2</name>
<price>69.99</price>
</toy>
<toy>
<name>Lego-Model3</name>
<price>14.99</price>
</toy>
<toy>
<name>Barbie-Pink</name>
<price>12.99</price>
</toy>
<toy>
<name>Barbie-Blue</name>
<price>13.99</price>
</toy>
<toy>
<name>Barbie-White</name>
<price>13.99</price>
</toy>
<toy>
<name>Barbie-Plain</name>
<price>13.99</price>
</toy>
</toys>

View File

@ -0,0 +1,17 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="toys">
<xs:complexType>
<xs:sequence>
<xs:element name="toy" maxOccurs="200">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" minOccurs="0"/>
<xs:element name="price" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

View File

@ -0,0 +1,17 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="toys">
<xs:complexType>
<xs:sequence>
<xs:element name="toy" maxOccurs="3002">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" minOccurs="0"/>
<xs:element name="price" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

View File

@ -0,0 +1,114 @@
/*
* 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.xinclude;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.stream.StreamResult;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/*
* @bug 6794483
* @summary Test JAXP parser can parse xml file using <xi:include> to include another xml, which has an empty element.
*/
public class Bug6794483Test {
@Test
public final void test() {
String xml = getClass().getResource("test1.xml").getPath();
Document doc = parseXmlFile(xml);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
TransformerFactory transformerFact = TransformerFactory.newInstance();
transformerFact.setAttribute("indent-number", new Integer(4));
Transformer transformer;
try {
transformer = transformerFact.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
// "true" indicate Append content If file exist in system
transformer.transform(new DOMSource(doc), result);
System.out.println("test" + sw);
} catch (TransformerConfigurationException ex) {
ex.printStackTrace();
Assert.fail("unexpected TransformerConfigurationException");
} catch (TransformerException ex) {
ex.printStackTrace();
Assert.fail("unexpected TransformerException");
}
}
public Document parseXmlFile(String fileName) {
System.out.println("Parsing XML file... " + fileName);
DocumentBuilder docBuilder = null;
Document doc = null;
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setCoalescing(true);
docBuilderFactory.setXIncludeAware(true);
System.out.println("Include: " + docBuilderFactory.isXIncludeAware());
docBuilderFactory.setNamespaceAware(true);
docBuilderFactory.setExpandEntityReferences(true);
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
File sourceFile = new File(fileName);
try {
doc = docBuilder.parse(sourceFile);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("XML file parsed");
return doc;
}
}

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<scenario xsi:noNamespaceSchemaLocation="..\xsd\Scenario.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude">
<!-- Configuration data for Device-->
<Device>
<xi:include href="test2.xml" xpointer="element(/1/1)" parse="xml"/>
</Device>
</scenario>

View File

@ -0,0 +1,12 @@
<test2>
<N1>
<node1>Node1 Value</node1>
<node2>Node2 Value</node2>
<node3/>
<node4>Node4 Value</node4>
<node5>
<node6>Node6 Value</node6>
</node5>
</N1>
</test2>

View File

@ -0,0 +1,62 @@
/*
* 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.stream.AttributeLocalNameTest;
import java.io.StringReader;
import javax.xml.stream.StreamFilter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @summary Test XMLStreamReader.getAttributeLocalName().
*/
public class AttributeLocalNameTest {
static final String XML = "<?xml version=\"1.0\"?>" + "<S:Envelope foo=\"bar\" xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"></S:Envelope>";
@Test
public void testOne() {
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createFilteredReader(factory.createXMLStreamReader(new StringReader(XML)), new Filter());
reader.next();
reader.hasNext(); // force filter to cache
Assert.assertTrue(reader.getAttributeLocalName(0) != null);
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Unexpected Exception: " + e.getMessage());
}
}
class Filter implements StreamFilter {
public boolean accept(XMLStreamReader reader) {
return true;
}
}
}

View File

@ -0,0 +1,65 @@
/*
* 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.stream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6370703
* @summary Test StAX parser can parse attribute default value when START_ELEMENT.
*/
public class Bug6370703 {
private static String INPUT_FILE = "sgml.xml";
@Test
public void testStartElement() {
try {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(this.getClass().getResource(INPUT_FILE).toExternalForm(),
this.getClass().getResourceAsStream(INPUT_FILE));
while (xsr.hasNext()) {
int event = xsr.next();
if (event == XMLStreamReader.START_ELEMENT) {
String localName = xsr.getLocalName();
boolean print = "para".equals(localName);
int nrOfAttr = xsr.getAttributeCount();
if (print) {
Assert.assertTrue(nrOfAttr > 0, "Default attribute declared in DTD is missing");
}
}
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception occured: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,47 @@
/*
* 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.stream;
import javax.xml.stream.XMLInputFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6378422
* @summary Test setting reuse-instance property on StAX factory.
*/
public class Bug6378422 {
@Test
public void testReuseInstanceProp() {
try {
XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty("reuse-instance", Boolean.valueOf(true));
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception occured: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,54 @@
/*
* 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.stream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6380870
* @summary Test StAX parser can parse VoiceXML DTD.
*/
public class Bug6380870 {
private static String INPUT_FILE = "basic-form.vxml";
@Test
public void testStreamReader() {
try {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader reader = xif.createXMLStreamReader(this.getClass().getResource(INPUT_FILE).toExternalForm(),
this.getClass().getResourceAsStream(INPUT_FILE));
while (reader.hasNext())
reader.next();
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception occured: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,79 @@
/*
* Copyright (c) 2013, 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.stream;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6489502
* @summary Test XMLInputFactory works correctly in case it repeats to create reader.
*/
public class Bug6489502 {
public java.io.File input;
public final String filesDir = "./";
protected XMLInputFactory inputFactory = XMLInputFactory.newInstance();
protected XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
private static String xml = "<?xml version=\"1.0\"?><PLAY><TITLE>The Tragedy of Hamlet, Prince of Denmark</TITLE></PLAY>";
@Test
public void testEventReader1() {
try {
// Check if event reader returns the correct event
XMLEventReader e1 = inputFactory.createXMLEventReader(inputFactory.createXMLStreamReader(new java.io.StringReader(xml)));
Assert.assertEquals(e1.peek().getEventType(), XMLStreamConstants.START_DOCUMENT);
// Repeat same steps to test factory state
XMLEventReader e2 = inputFactory.createXMLEventReader(inputFactory.createXMLStreamReader(new java.io.StringReader(xml)));
Assert.assertEquals(e2.peek().getEventType(), XMLStreamConstants.START_DOCUMENT);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void testEventReader2() {
try {
// Now advance underlying reader and then call peek on event reader
XMLStreamReader s1 = inputFactory.createXMLStreamReader(new java.io.StringReader(xml));
Assert.assertEquals(s1.getEventType(), XMLStreamConstants.START_DOCUMENT);
s1.next();
s1.next(); // advance to <TITLE>
Assert.assertTrue(s1.getLocalName().equals("TITLE"));
XMLEventReader e3 = inputFactory.createXMLEventReader(s1);
Assert.assertEquals(e3.peek().getEventType(), XMLStreamConstants.START_ELEMENT);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
}

View File

@ -0,0 +1,170 @@
/*
* 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.stream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6509774
* @summary Test Property javax.xml.stream.supportDTD, DTD events are now returned even if supportDTD=false.
*/
public class Bug6509774 {
@Test
public void test0() {
try {
XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty("javax.xml.stream.supportDTD", Boolean.TRUE);
XMLStreamReader xsr = xif.createXMLStreamReader(
getClass().getResource("sgml_Bug6509774.xml").toString(),
getClass().getResourceAsStream("sgml_Bug6509774.xml"));
Assert.assertTrue(xsr.getEventType() == XMLStreamConstants.START_DOCUMENT);
int event = xsr.next();
// Must be a DTD event since DTDs are supported
Assert.assertTrue(event == XMLStreamConstants.DTD);
while (xsr.hasNext()) {
event = xsr.next();
}
Assert.assertTrue(event == XMLStreamConstants.END_DOCUMENT);
xsr.close();
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void test1() {
try {
XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty("javax.xml.stream.supportDTD", Boolean.FALSE);
XMLStreamReader xsr = xif.createXMLStreamReader(
getClass().getResource("sgml_Bug6509774.xml").toString(),
getClass().getResourceAsStream("sgml_Bug6509774.xml"));
Assert.assertTrue(xsr.getEventType() == XMLStreamConstants.START_DOCUMENT);
int event = xsr.next();
// Should not be a DTD event since they are ignored
Assert.assertTrue(event == XMLStreamConstants.DTD);
while (xsr.hasNext()) {
event = xsr.next();
}
Assert.assertTrue(event == XMLStreamConstants.END_DOCUMENT);
xsr.close();
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void test2() {
try {
XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty("javax.xml.stream.supportDTD", Boolean.FALSE);
XMLStreamReader xsr = xif.createXMLStreamReader(
getClass().getResource("sgml-bad-systemId.xml").toString(),
getClass().getResourceAsStream("sgml-bad-systemId.xml"));
Assert.assertTrue(xsr.getEventType() == XMLStreamConstants.START_DOCUMENT);
int event = xsr.next();
// Should not be a DTD event since they are ignored
Assert.assertTrue(event == XMLStreamConstants.DTD);
while (xsr.hasNext()) {
event = xsr.next();
}
Assert.assertTrue(event == XMLStreamConstants.END_DOCUMENT);
xsr.close();
}
catch (Exception e) {
// Bogus systemId in XML document should not result in exception
Assert.fail(e.getMessage());
}
}
}

View File

@ -0,0 +1,104 @@
/*
* 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.stream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6688002
* @summary Test single instance of XMLOutputFactory/XMLInputFactory create multiple Writer/Readers in parallel.
*/
public class Bug6688002Test {
private static final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
private static final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
private static final int NO_THREADS = 3;
@Test
public void testMultiThread() throws Exception {
Thread[] threads = new Thread[NO_THREADS];
for (int i = 0; i < NO_THREADS; i++) {
threads[i] = new Thread(new MyRunnable(i));
}
for (int i = 0; i < NO_THREADS; i++) {
threads[i].start();
}
for (int i = 0; i < NO_THREADS; i++) {
threads[i].join();
}
}
public class MyRunnable implements Runnable {
final int no;
MyRunnable(int no) {
this.no = no;
}
public void run() {
try {
FileOutputStream fos = new FileOutputStream("" + no);
XMLStreamWriter w = getWriter(fos);
// System.out.println("Writer="+w+" Thread="+Thread.currentThread());
w.writeStartDocument();
w.writeStartElement("hello");
for (int j = 0; j < 50; j++) {
w.writeStartElement("a" + j);
w.writeEndElement();
}
w.writeEndElement();
w.writeEndDocument();
w.close();
fos.close();
FileInputStream fis = new FileInputStream("" + no);
XMLStreamReader r = getReader(fis);
while (r.hasNext()) {
r.next();
}
r.close();
fis.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
}
public static/* synchronized */XMLStreamReader getReader(InputStream is) throws Exception {
return inputFactory.createXMLStreamReader(is);
// return XMLStreamReaderFactory.create(null, is, true);
}
public static/* synchronized */XMLStreamWriter getWriter(OutputStream os) throws Exception {
return outputFactory.createXMLStreamWriter(os);
// return XMLStreamWriterFactory.createXMLStreamWriter(os);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,92 @@
/*
* 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.stream;
import javax.xml.namespace.QName;
import javax.xml.stream.events.XMLEvent;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6976938
* @summary Test StAX parser won't throw StackOverflowError while reading valid XML file, in case the text content of an XML element contains many lines like "&lt; ... &gt;".
*/
public class Bug6976938Test {
private static final String INPUT_FILE = "Bug6976938.xml";
public static final String VF_GENERIC_TT_NAMESPACE = "http://www.vodafone.com/oss/xml/TroubleTicket";
public static final QName ATTACHMENT_NAME = new QName(VF_GENERIC_TT_NAMESPACE, "attachment");
@Test
public void testEventReader() {
XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
eventReaderTest(xif);
}
@Test
public void testEventReader1() {
XMLInputFactory xif = XMLInputFactory.newInstance();
eventReaderTest(xif);
}
public void eventReaderTest(XMLInputFactory xif) {
XMLEventReader eventReader = null;
try {
eventReader = xif.createXMLEventReader(this.getClass().getResourceAsStream(INPUT_FILE));
XMLEventReader filteredEventReader = xif.createFilteredReader(eventReader, new EventFilter() {
public boolean accept(XMLEvent event) {
if (!event.isStartElement()) {
return false;
}
QName elementQName = event.asStartElement().getName();
if ((elementQName.getLocalPart().equals(ATTACHMENT_NAME.getLocalPart()) || elementQName.getLocalPart().equals("Attachment"))
&& elementQName.getNamespaceURI().equals(VF_GENERIC_TT_NAMESPACE)) {
return true;
}
return false;
}
});
if (filteredEventReader.hasNext()) {
System.out.println("containsAttachments() returns true");
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
} finally {
if (eventReader != null) {
try {
eventReader.close();
} catch (XMLStreamException xse) {
// Ignored by intention
}
}
}
}
}

View File

@ -0,0 +1,106 @@
/*
* 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.stream.CoalesceTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @summary Test Coalesce property works.
*/
public class CoalesceTest {
String countryElementContent = "START India CS}}}}}} India END";
String descriptionElementContent = "a&b";
String fooElementContent = "&< cdatastart<><>>><>><<<<cdataend entitystart insert entityend";
@Test
public void testCoalesceProperty() {
try {
XMLInputFactory xifactory = XMLInputFactory.newInstance();
xifactory.setProperty(XMLInputFactory.IS_COALESCING, new Boolean(true));
InputStream xml = this.getClass().getResourceAsStream("coalesce.xml");
XMLStreamReader streamReader = xifactory.createXMLStreamReader(xml);
while (streamReader.hasNext()) {
int eventType = streamReader.next();
if (eventType == XMLStreamConstants.START_ELEMENT && streamReader.getLocalName().equals("country")) {
eventType = streamReader.next();
if (eventType == XMLStreamConstants.CHARACTERS) {
String text = streamReader.getText();
if (!text.equals(countryElementContent)) {
System.out.println("String dont match");
System.out.println("text = " + text);
System.out.println("countryElementContent = " + countryElementContent);
}
// assertTrue(text.equals(countryElementContent));
}
}
if (eventType == XMLStreamConstants.START_ELEMENT && streamReader.getLocalName().equals("description")) {
eventType = streamReader.next();
if (eventType == XMLStreamConstants.CHARACTERS) {
String text = streamReader.getText();
if (!text.equals(descriptionElementContent)) {
System.out.println("String dont match");
System.out.println("text = " + text);
System.out.println("descriptionElementContent = " + descriptionElementContent);
}
Assert.assertTrue(text.equals(descriptionElementContent));
}
}
if (eventType == XMLStreamConstants.START_ELEMENT && streamReader.getLocalName().equals("foo")) {
eventType = streamReader.next();
if (eventType == XMLStreamConstants.CHARACTERS) {
String text = streamReader.getText();
if (!text.equals(fooElementContent)) {
System.out.println("String dont match");
System.out.println("text = " + text);
System.out.println("fooElementContent = " + fooElementContent);
}
Assert.assertTrue(text.equals(fooElementContent));
}
}
}
} catch (XMLStreamException ex) {
if (ex.getNestedException() != null) {
ex.getNestedException().printStackTrace();
}
// ex.printStackTrace() ;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE city [
<!ENTITY a "insert">
<!ENTITY b "<element1>subtree</element1>">
]>
<city name = "Bangalore" population = "100000">
<country state = "Karnatka">START India <![CDATA[CS}}}}}}]]> India END</country>
<foo>&amp;&lt; <![CDATA[cdatastart<><>>><>><<<<cdataend]]> entitystart &a; entityend</foo>
&b;
<description>a&amp;b</description>
<?CityHotels Information about the hotels is passed to different appications for processing. ?>
</city>

View File

@ -0,0 +1,175 @@
/*
* 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.stream.EntitiesTest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/*
* @summary Test StAX parses entity.
*/
public class EntityTest {
XMLInputFactory factory = null;
String output = "";
@BeforeMethod
protected void setUp() {
try {
factory = XMLInputFactory.newInstance();
} catch (Exception ex) {
Assert.fail("Could not create XMLInputFactory");
}
}
@AfterMethod
protected void tearDown() {
factory = null;
}
@Test
public void testProperties() {
Assert.assertTrue(factory.isPropertySupported("javax.xml.stream.isReplacingEntityReferences"));
}
@Test
public void testCharacterReferences() {
try {
URL fileName = EntityTest.class.getResource("testCharRef.xml");
URL outputFileName = EntityTest.class.getResource("testCharRef.xml.output");
XMLStreamReader xmlr = factory.createXMLStreamReader(new InputStreamReader(fileName.openStream()));
int eventType = 0;
while (xmlr.hasNext()) {
eventType = xmlr.next();
handleEvent(xmlr, eventType);
}
System.out.println("Output:");
System.out.println(output);
Assert.assertTrue(compareOutput(new InputStreamReader(outputFileName.openStream()), new StringReader(output)));
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail(ex.getMessage());
}
}
private void handleEvent(XMLStreamReader xmlr, int eventType) {
switch (eventType) {
case XMLEvent.START_ELEMENT:
handleStartElement(xmlr);
break;
case XMLEvent.END_ELEMENT:
handleEndElement(xmlr);
break;
case XMLEvent.CHARACTERS:
handleCharacters(xmlr);
break;
case XMLEvent.COMMENT:
handleComment(xmlr);
break;
case XMLEvent.ENTITY_REFERENCE:
break;
case XMLEvent.ATTRIBUTE:
break;
case XMLEvent.DTD:
break;
case XMLEvent.CDATA:
break;
default:
break;
}
}
private void handleStartElement(XMLStreamReader xmlr) {
output += "<";
output += xmlr.getLocalName();
if (xmlr.hasText())
output += xmlr.getText();
printAttributes(xmlr);
output += ">";
}
private void handleEndElement(XMLStreamReader xmlr) {
output += "</";
output += xmlr.getLocalName();
output += ">";
}
private void handleComment(XMLStreamReader xmlr) {
if (xmlr.hasText())
output += xmlr.getText();
}
private void handleCharacters(XMLStreamReader xmlr) {
if (xmlr.hasText())
output += xmlr.getText();
}
private void printAttributes(XMLStreamReader xmlr) {
if (xmlr.getAttributeCount() > 0) {
int count = xmlr.getAttributeCount();
for (int i = 0; i < count; i++) {
output += xmlr.getAttributeName(i);
output += "=";
output += xmlr.getAttributeValue(i);
/*
* String name = xmlr.getAttributeName(i) ; String value =
* xmlr.getAttributeValue(i) ;
* System.out.println(name+"="+value);
*/
}
}
}
protected boolean compareOutput(Reader expected, Reader actual) throws IOException {
LineNumberReader expectedOutput = new LineNumberReader(expected);
LineNumberReader actualOutput = new LineNumberReader(actual);
while (expectedOutput.ready() && actualOutput.ready()) {
String expectedLine = expectedOutput.readLine();
String actualLine = actualOutput.readLine();
if (!expectedLine.equals(actualLine)) {
System.out.println("Entityreference expansion failed, line no: " + expectedOutput.getLineNumber());
System.out.println("Expected: " + expectedLine);
System.out.println("Actual : " + actualLine);
return false;
}
}
expectedOutput.close();
actualOutput.close();
return true;
}
}

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE juicers [
<!ENTITY ch1 "T">
]>
<juicers>
<reftest>TES&ch1;CHARREF</reftest>
</juicers>

View File

@ -0,0 +1,5 @@
<juicers>
<reftest>TESTCHARREF</reftest>
</juicers>

View File

@ -0,0 +1,221 @@
/*
* 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.stream;
import org.testng.annotations.Test;
import org.testng.Assert;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.util.EventReaderDelegate;
/*
* @summary Test EventReaderDelegate.
*/
public class EventReaderDelegateTest {
public EventReaderDelegateTest(String name) {
}
@Test
public void testGetElementText() {
try {
XMLInputFactory ifac = XMLInputFactory.newFactory();
XMLEventReader reader = ifac.createXMLEventReader(new FileInputStream(new File(getClass().getResource("toys.xml").getFile())));
EventReaderDelegate delegate = new EventReaderDelegate(reader);
while (delegate.hasNext()) {
XMLEvent event = (XMLEvent) delegate.next();
switch (event.getEventType()) {
case XMLStreamConstants.START_ELEMENT: {
String name = event.asStartElement().getName().toString();
if (name.equals("name") || name.equals("price")) {
System.out.println(delegate.getElementText());
} else {
try {
delegate.getElementText();
} catch (XMLStreamException e) {
System.out.println("Expected XMLStreamException in getElementText()");
}
}
}
}
}
delegate.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Assert.fail("FileNotFoundException in testGetElementText()");
} catch (XMLStreamException e) {
e.printStackTrace();
Assert.fail("XMLStreamException in testGetElementText()");
} catch (FactoryConfigurationError e) {
e.printStackTrace();
Assert.fail("FactoryConfigurationError in testGetElementText()");
}
}
@Test
public void testRemove() {
try {
XMLInputFactory ifac = XMLInputFactory.newFactory();
XMLEventReader reader = ifac.createXMLEventReader(new FileInputStream(new File(getClass().getResource("toys.xml").getFile())));
EventReaderDelegate delegate = new EventReaderDelegate(reader);
delegate.remove();
} catch (FileNotFoundException e) {
e.printStackTrace();
Assert.fail("FileNotFoundException in testRemove()");
} catch (XMLStreamException e) {
e.printStackTrace();
Assert.fail("XMLStreamException in testRemove()");
} catch (FactoryConfigurationError e) {
e.printStackTrace();
Assert.fail("FactoryConfigurationError in testRemove()");
} catch (UnsupportedOperationException e) {
System.out.println("Expected exception in remove()");
}
}
@Test
public void testPeek() {
try {
XMLInputFactory ifac = XMLInputFactory.newFactory();
XMLEventReader reader = ifac.createXMLEventReader(new FileInputStream(new File(getClass().getResource("toys.xml").getFile())));
EventReaderDelegate delegate = new EventReaderDelegate();
delegate.setParent(reader);
while (delegate.hasNext()) {
XMLEvent peekevent = delegate.peek();
XMLEvent event = (XMLEvent) delegate.next();
if (peekevent != event) {
Assert.fail("peek() does not return same XMLEvent with next()");
}
}
delegate.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Assert.fail("FileNotFoundException in testPeek()");
} catch (XMLStreamException e) {
e.printStackTrace();
Assert.fail("XMLStreamException in testPeek()");
} catch (FactoryConfigurationError e) {
e.printStackTrace();
Assert.fail("FactoryConfigurationError in testPeek()");
}
}
@Test
public void testNextTag() {
try {
XMLInputFactory ifac = XMLInputFactory.newFactory();
ifac.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
XMLEventReader reader = ifac.createXMLEventReader(new FileInputStream(new File(getClass().getResource("toys.xml").getFile())));
EventReaderDelegate delegate = new EventReaderDelegate(reader);
if ((Boolean) (delegate.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) != Boolean.FALSE) {
Assert.fail("getProperty() does not return correct value");
}
while (delegate.hasNext()) {
XMLEvent event = delegate.peek();
if (event.isEndElement() || event.isStartElement()) {
XMLEvent nextevent = delegate.nextTag();
if (!(nextevent.getEventType() == XMLStreamConstants.START_ELEMENT || nextevent.getEventType() == XMLStreamConstants.END_ELEMENT)) {
Assert.fail("nextTag() does not return correct event type");
}
} else {
delegate.next();
}
}
delegate.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Assert.fail("FileNotFoundException in testNextTag()");
} catch (XMLStreamException e) {
e.printStackTrace();
Assert.fail("XMLStreamException in testNextTag()");
} catch (FactoryConfigurationError e) {
e.printStackTrace();
Assert.fail("FactoryConfigurationError in testNextTag()");
}
}
@Test
public void testNextEvent() {
try {
XMLInputFactory ifac = XMLInputFactory.newFactory();
ifac.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
XMLEventReader reader = ifac.createXMLEventReader(new FileInputStream(new File(getClass().getResource("toys.xml").getFile())));
EventReaderDelegate delegate = new EventReaderDelegate();
delegate.setParent(reader);
if ((Boolean) (delegate.getParent().getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) != Boolean.FALSE) {
Assert.fail("XMLEventReader.getProperty() does not return correct value");
}
if ((Boolean) (delegate.getProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) != Boolean.FALSE) {
Assert.fail("EventReaderDelegate.getProperty() does not return correct value");
}
while (delegate.hasNext()) {
XMLEvent event = delegate.nextEvent();
switch (event.getEventType()) {
case XMLStreamConstants.START_ELEMENT: {
System.out.println(event.asStartElement().getName());
break;
}
case XMLStreamConstants.END_ELEMENT: {
System.out.println(event.asEndElement().getName());
break;
}
case XMLStreamConstants.END_DOCUMENT: {
System.out.println(event.isEndDocument());
break;
}
case XMLStreamConstants.START_DOCUMENT: {
System.out.println(event.isStartDocument());
break;
}
case XMLStreamConstants.CHARACTERS: {
System.out.println(event.asCharacters().getData());
break;
}
case XMLStreamConstants.COMMENT: {
System.out.println(event.toString());
break;
}
}
}
delegate.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Assert.fail("FileNotFoundException in testNextEvent()");
} catch (XMLStreamException e) {
e.printStackTrace();
Assert.fail("XMLStreamException in testNextEvent()");
} catch (FactoryConfigurationError e) {
e.printStackTrace();
Assert.fail("FactoryConfigurationError in testNextEvent()");
}
}
}

View File

@ -0,0 +1,174 @@
/*
* 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.stream.Events;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.Comment;
import javax.xml.stream.events.DTD;
import javax.xml.stream.events.EndDocument;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.Namespace;
import javax.xml.stream.events.ProcessingInstruction;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6631268
* @summary Test XMLEvent.writeAsEncodedUnicode can output the event content.
*/
public class Issue41Test {
public java.io.File input;
public final String filesDir = "./";
protected XMLInputFactory inputFactory;
protected XMLOutputFactory outputFactory;
@Test
public void testEvents() {
XMLEventFactory f = XMLEventFactory.newInstance();
final String contents = "test <some> text & more! [[]] --";
final String prefix = "prefix";
final String uri = "http://foo";
final String localName = "elem";
try {
StartDocument sd = f.createStartDocument();
writeAsEncodedUnicode(sd);
Comment c = f.createComment("some comments");
writeAsEncodedUnicode(c);
StartElement se = f.createStartElement(prefix, uri, localName);
ProcessingInstruction pi = f.createProcessingInstruction("target", "data");
writeAsEncodedUnicode(pi);
Namespace ns = f.createNamespace(prefix, uri);
writeAsEncodedUnicode(ns);
Characters characters = f.createCharacters(contents);
writeAsEncodedUnicode(characters);
// CData
Characters cdata = f.createCData(contents);
writeAsEncodedUnicode(cdata);
// Attribute
QName attrName = new QName("http://test.com", "attr", "ns");
Attribute attr = f.createAttribute(attrName, "value");
writeAsEncodedUnicode(attr);
// prefix, uri, localName
EndElement ee = f.createEndElement(prefix, uri, localName);
writeAsEncodedUnicode(ee);
EndDocument ed = f.createEndDocument();
writeAsEncodedUnicode(ed);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
/**
* DTDEvent instances constructed via event reader are missing the notation
* and entity declaration information
*/
@Test
public void testDTDEvent() {
String XML = "<?xml version='1.0' ?>" + "<!DOCTYPE root [\n" + "<!ENTITY intEnt 'internal'>\n" + "<!ENTITY extParsedEnt SYSTEM 'url:dummy'>\n"
+ "<!NOTATION notation PUBLIC 'notation-public-id'>\n" + "<!NOTATION notation2 SYSTEM 'url:dummy'>\n"
+ "<!ENTITY extUnparsedEnt SYSTEM 'url:dummy2' NDATA notation>\n" + "]>" + "<root />";
try {
XMLEventReader er = getReader(XML);
XMLEvent evt = er.nextEvent(); // StartDocument
evt = er.nextEvent(); // DTD
if (evt.getEventType() != XMLStreamConstants.DTD) {
Assert.fail("Expected DTD event");
}
DTD dtd = (DTD) evt;
writeAsEncodedUnicode(dtd);
List entities = dtd.getEntities();
if (entities == null) {
Assert.fail("No entity found. Expected 3.");
} else {
writeAsEncodedUnicode((XMLEvent) entities.get(0));
writeAsEncodedUnicode((XMLEvent) entities.get(1));
writeAsEncodedUnicode((XMLEvent) entities.get(2));
}
List notations = dtd.getNotations();
if (notations == null) {
Assert.fail("No notation found. Expected 2.");
} else {
writeAsEncodedUnicode((XMLEvent) notations.get(0));
writeAsEncodedUnicode((XMLEvent) notations.get(1));
}
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
private XMLEventReader getReader(String XML) throws Exception {
inputFactory = XMLInputFactory.newInstance();
// Check if event reader returns the correct event
XMLEventReader er = inputFactory.createXMLEventReader(new StringReader(XML));
return er;
}
/**
* The return of XMLEvent writeAsEncodedUnicode method is not defined This
* method merely tests that the output exists
*/
public void writeAsEncodedUnicode(XMLEvent evt) throws XMLStreamException {
if (evt.getEventType() == XMLStreamConstants.END_DOCUMENT) {
return;
}
StringWriter sw = new StringWriter();
evt.writeAsEncodedUnicode(sw);
Assert.assertTrue(sw.toString().length() > 0);
System.out.println(sw.toString());
}
}

View File

@ -0,0 +1,111 @@
/*
* 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.stream.Events;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.events.DTD;
import javax.xml.stream.events.EntityDeclaration;
import javax.xml.stream.events.NotationDeclaration;
import javax.xml.stream.events.XMLEvent;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @bug 6620632
* @summary Test XMLEventReader can parse notation and entity information from DTD Event.
*/
public class Issue48Test {
public java.io.File input;
public final String filesDir = "./";
protected XMLInputFactory inputFactory;
protected XMLOutputFactory outputFactory;
/**
* DTDEvent instances constructed via event reader are missing the notation
* and entity declaration information
*/
@Test
public void testDTDEvent() {
String XML = "<?xml version='1.0' ?>" + "<!DOCTYPE root [\n" + "<!ENTITY intEnt 'internal'>\n" + "<!ENTITY extParsedEnt SYSTEM 'url:dummy'>\n"
+ "<!NOTATION notation PUBLIC 'notation-public-id'>\n" + "<!NOTATION notation2 SYSTEM 'url:dummy'>\n"
+ "<!ENTITY extUnparsedEnt SYSTEM 'url:dummy2' NDATA notation>\n" + "]>" + "<root />";
try {
XMLEventReader er = getReader(XML);
XMLEvent evt = er.nextEvent(); // StartDocument
evt = er.nextEvent(); // DTD
if (evt.getEventType() != XMLStreamConstants.DTD) {
Assert.fail("Expected DTD event");
}
DTD dtd = (DTD) evt;
List entities = dtd.getEntities();
if (entities == null) {
Assert.fail("No entity found. Expected 3.");
} else {
Assert.assertEquals(entities.size(), 3);
}
// Let's also verify they are all of right type...
testListElems(entities, EntityDeclaration.class);
List notations = dtd.getNotations();
if (notations == null) {
Assert.fail("No notation found. Expected 2.");
} else {
Assert.assertEquals(notations.size(), 2);
}
// Let's also verify they are all of right type...
testListElems(notations, NotationDeclaration.class);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
private XMLEventReader getReader(String XML) throws Exception {
inputFactory = XMLInputFactory.newInstance();
// Check if event reader returns the correct event
XMLEventReader er = inputFactory.createXMLEventReader(new StringReader(XML));
return er;
}
private void testListElems(List l, Class expType) {
Iterator it = l.iterator();
while (it.hasNext()) {
Object o = it.next();
Assert.assertNotNull(o);
Assert.assertTrue(expType.isAssignableFrom(o.getClass()));
}
}
}

View File

@ -0,0 +1,67 @@
/*
* 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.stream.Events;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.events.StartDocument;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @summary Test encodingSet/standaloneSet returns correct result in case encoding/standalone is set when constructing StartDocument.
*/
public class Issue53Test {
@Test
public void testEncodingSet() {
XMLEventFactory f = XMLEventFactory.newInstance();
try {
StartDocument sd = f.createStartDocument("UTF-8");
System.out.println("Encoding: " + sd.getCharacterEncodingScheme());
System.out.println("Encoding set: " + sd.encodingSet());
Assert.assertTrue(sd.encodingSet(), "encoding is set, should return true.");
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void testStandaloneSet() {
XMLEventFactory f = XMLEventFactory.newInstance();
try {
StartDocument sd = f.createStartDocument("UTF-8", "1.0", true);
System.out.println(sd.isStandalone());
System.out.println(sd.standaloneSet());
Assert.assertTrue(sd.standaloneSet(), "standalone is set, should return true.");
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
}

View File

@ -0,0 +1,80 @@
/*
* 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.stream.Events;
import java.io.StringReader;
import javax.xml.stream.Location;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.events.XMLEvent;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* @summary Test XMLEvent.getLocation() returns a non-volatile Location.
*/
public class Issue58Test {
public java.io.File input;
public final String filesDir = "./";
protected XMLInputFactory inputFactory;
protected XMLOutputFactory outputFactory;
@Test
public void testLocation() {
String XML = "<?xml version='1.0' ?>" + "<!DOCTYPE root [\n" + "<!ENTITY intEnt 'internal'>\n" + "<!ENTITY extParsedEnt SYSTEM 'url:dummy'>\n"
+ "<!NOTATION notation PUBLIC 'notation-public-id'>\n" + "<!NOTATION notation2 SYSTEM 'url:dummy'>\n"
+ "<!ENTITY extUnparsedEnt SYSTEM 'url:dummy2' NDATA notation>\n" + "]>\n" + "<root />";
try {
XMLEventReader er = getReader(XML);
XMLEvent evt = er.nextEvent(); // StartDocument
Location loc1 = evt.getLocation();
System.out.println("Location 1: " + loc1.getLineNumber() + "," + loc1.getColumnNumber());
evt = er.nextEvent(); // DTD
// loc1 should not change so its line number should still be 1
Assert.assertTrue(loc1.getLineNumber() == 1);
Location loc2 = evt.getLocation();
System.out.println("Location 2: " + loc2.getLineNumber() + "," + loc2.getColumnNumber());
evt = er.nextEvent(); // root
System.out.println("Location 1: " + loc1.getLineNumber() + "," + loc1.getColumnNumber());
Assert.assertTrue(loc1.getLineNumber() == 1);
Assert.assertTrue(loc2.getLineNumber() == 7);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
private XMLEventReader getReader(String XML) throws Exception {
inputFactory = XMLInputFactory.newInstance();
// Check if event reader returns the correct event
XMLEventReader er = inputFactory.createXMLEventReader(new StringReader(XML));
return er;
}
}

View File

@ -0,0 +1,141 @@
/*
* 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.stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Properties;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/*
* @summary Test SaTX factory using factory property and using ContextClassLoader.
*/
public class FactoryFindTest {
boolean myClassLoaderUsed = false;
final static String FACTORY_KEY = "javax.xml.stream.XMLInputFactory";
@BeforeClass
public void setup(){
policy.PolicyUtil.changePolicy(getClass().getResource("FactoryFindTest.policy").getFile());
}
@Test
public void testFactoryFindUsingStaxProperties() {
// If property is defined, will take precendence so this test
// is ignored :(
if (System.getProperty(FACTORY_KEY) != null) {
return;
}
Properties props = new Properties();
String configFile = System.getProperty("java.home") + File.separator + "lib" + File.separator + "stax.properties";
File f = new File(configFile);
if (f.exists()) {
try {
FileInputStream fis = new FileInputStream(f);
props.load(fis);
fis.close();
} catch (FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
} else {
props.setProperty(FACTORY_KEY, "com.sun.xml.internal.stream.XMLInputFactoryImpl");
try {
FileOutputStream fos = new FileOutputStream(f);
props.store(fos, null);
fos.close();
f.deleteOnExit();
} catch (FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
}
XMLInputFactory factory = XMLInputFactory.newInstance();
Assert.assertTrue(factory.getClass().getName().equals(props.getProperty(FACTORY_KEY)));
}
@Test
public void testFactoryFind() {
try {
// System.setProperty("jaxp.debug", "true");
XMLInputFactory factory = XMLInputFactory.newInstance();
Assert.assertTrue(factory.getClass().getClassLoader() == null);
Thread.currentThread().setContextClassLoader(null);
factory = XMLInputFactory.newInstance();
Assert.assertTrue(factory.getClass().getClassLoader() == null);
Thread.currentThread().setContextClassLoader(new MyClassLoader());
factory = XMLInputFactory.newInstance();
if (System.getSecurityManager() == null)
Assert.assertTrue(myClassLoaderUsed);
else
Assert.assertFalse(myClassLoaderUsed);
XMLOutputFactory ofactory = XMLOutputFactory.newInstance();
Assert.assertTrue(ofactory.getClass().getClassLoader() == null);
Thread.currentThread().setContextClassLoader(null);
ofactory = XMLOutputFactory.newInstance();
Assert.assertTrue(ofactory.getClass().getClassLoader() == null);
Thread.currentThread().setContextClassLoader(new MyClassLoader());
ofactory = XMLOutputFactory.newInstance();
if (System.getSecurityManager() == null)
Assert.assertTrue(myClassLoaderUsed);
else
Assert.assertFalse(myClassLoaderUsed);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
class MyClassLoader extends URLClassLoader {
public MyClassLoader() {
super(new URL[0]);
}
public Class loadClass(String name) throws ClassNotFoundException {
myClassLoaderUsed = true;
return super.loadClass(name);
}
}
}

View File

@ -0,0 +1,23 @@
grant {
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
permission java.lang.RuntimePermission "accessDeclaredMembers";
permission java.io.FilePermission "${test.classes}/../../-", "read, write, delete";
permission java.io.FilePermission ".", "read, write, delete";
permission java.util.PropertyPermission "*", "read, write";
permission java.lang.RuntimePermission "setSecurityManager";
permission java.lang.RuntimePermission "createSecurityManager";
permission java.lang.RuntimePermission "createClassLoader";
permission java.lang.RuntimePermission "setIO";
permission java.lang.RuntimePermission "setContextClassLoader";
permission java.security.SecurityPermission "getPolicy";
permission java.io.FilePermission "${test.src}/-", "read, write, delete";
permission java.io.FilePermission "${user.dir}/-", "read, write, delete";
permission java.io.FilePermission "${java.io.tmpdir}/-", "read, write, delete";
permission java.io.FilePermission "${java.home}/lib/stax.properties", "read, write, delete";
};

Some files were not shown because too many files have changed in this diff Show More